<?php
/**
 * Controller - Checking Guidelines
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
controller_only();

$pageTitle = 'Checking Guidelines';
$db = Database::getInstance();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $db->insert('checking_guidelines', [
            'title' => trim($_POST['title'] ?? ''),
            'content' => trim($_POST['content'] ?? ''),
            'session_id' => (int)($_POST['session_id'] ?? 0) ?: null,
            'status' => $_POST['status'] ?? 'active',
            'created_by' => SessionManager::getUserId(),
        ]);
        set_success('Guideline created.');
    } elseif ($action === 'update') {
        $id = (int)($_POST['guideline_id'] ?? 0);
        $db->update('checking_guidelines', [
            'title' => trim($_POST['title'] ?? ''),
            'content' => trim($_POST['content'] ?? ''),
            'session_id' => (int)($_POST['session_id'] ?? 0) ?: null,
            'status' => $_POST['status'] ?? 'active',
        ], 'id = ?', [$id]);
        set_success('Guideline updated.');
    } elseif ($action === 'delete') {
        $db->delete('checking_guidelines', 'id = ?', [(int)($_POST['guideline_id'] ?? 0)]);
        set_success('Guideline deleted.');
    }

    redirect(APP_URL . '/controller/checking_guidelines.php');
}

$guidelines = $db->fetchAll("
    SELECT cg.*, u.full_name as creator_name, s.name as session_name
    FROM checking_guidelines cg
    LEFT JOIN users u ON cg.created_by = u.id
    LEFT JOIN sessions s ON cg.session_id = s.id
    ORDER BY cg.created_at DESC
");
$sessions = $db->fetchAll("SELECT id, name FROM sessions ORDER BY name");

include APP_ROOT . '/templates/header.php';
?>

<div class="toolbar">
    <button class="btn btn-primary" onclick="document.getElementById('createModal').style.display='flex'">+ Add Guideline</button>
</div>

<!-- Create Modal -->
<div class="modal-overlay" id="createModal">
    <div class="modal" style="max-width:700px">
        <div class="modal-header">
            <h3>New Checking Guideline</h3>
            <button class="modal-close" onclick="document.getElementById('createModal').style.display='none'">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="create">
                <div class="form-group">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" class="form-control" required placeholder="Guideline title">
                </div>
                <div class="form-group">
                    <label class="form-label">Content *</label>
                    <textarea name="content" class="form-control" rows="8" required placeholder="Detailed guidelines for checkers..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Session (Optional)</label>
                        <select name="session_id" class="form-control">
                            <option value="">General (All Sessions)</option>
                            <?php foreach ($sessions as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Create</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('createModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if (empty($guidelines)): ?>
<div class="card">
    <div class="empty-state">
        <div class="icon">&#9989;</div>
        <h3>No Guidelines</h3>
        <p>Create checking guidelines for your team.</p>
    </div>
</div>
<?php else: foreach ($guidelines as $g): ?>
<div class="card mb-2">
    <div class="card-header">
        <div>
            <h3><?= e($g['title']) ?></h3>
            <small class="text-muted">
                <?= $g['session_name'] ? 'Session: ' . e($g['session_name']) : 'General' ?> |
                By <?= e($g['creator_name'] ?? '') ?> |
                <?= format_date($g['created_at']) ?>
            </small>
        </div>
        <div class="d-flex gap-1 align-center">
            <?= status_badge($g['status']) ?>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete?')">
                <?= Csrf::field() ?>
                <input type="hidden" name="guideline_id" value="<?= $g['id'] ?>">
                <input type="hidden" name="action" value="delete">
                <button type="submit" class="btn btn-sm btn-danger">&#128465;</button>
            </form>
        </div>
    </div>
    <div class="card-body">
        <div style="white-space:pre-wrap;line-height:1.7"><?= nl2br(e($g['content'])) ?></div>
    </div>
</div>
<?php endforeach; endif; ?>

<?php include APP_ROOT . '/templates/footer.php'; ?>
