<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

require_once '../config.php';
require_once 'helpers.php';
require_once 'lib/exam_utils.php';

$allowed_roles = ['admin', 'headteacher', 'director', 'supervisor', 'tutor'];
if (!in_array($_SESSION['role'], $allowed_roles, true)) {
    header('Location: ../dashboard.php?error=access_denied');
    exit;
}

$conn = getDBConnection();
$viewExamId = (int) ($_GET['view'] ?? 0);
$selectedExam = $viewExamId ? loadExamRecord($viewExamId) : null;
$sessionUser = ['user_id' => (int) $_SESSION['user_id'], 'role' => $_SESSION['role'] ?? ''];

// Filters
$filterStatus  = trim((string) ($_GET['status']  ?? ''));
$filterClass   = trim((string) ($_GET['class']   ?? ''));
$filterSubject = trim((string) ($_GET['subject']  ?? ''));

$where  = ['1=1'];
$params = [];
$types  = '';
if ($filterStatus  !== '') { $where[] = 'e.status = ?';       $params[] = $filterStatus;  $types .= 's'; }
if ($filterClass   !== '') { $where[] = 'e.class_name = ?';   $params[] = $filterClass;   $types .= 's'; }
if ($filterSubject !== '') { $where[] = 'e.subject_name LIKE ?'; $params[] = "%{$filterSubject}%"; $types .= 's'; }
$w = implode(' AND ', $where);

$query = "SELECT e.*, u.full_name AS creator_name
          FROM generated_exams e
          LEFT JOIN users u ON e.created_by = u.id
          WHERE {$w}
          ORDER BY FIELD(e.status, 'review_requested', 'reviewed', 'approved', 'draft', 'published'), e.updated_at DESC, e.created_at DESC";

$exams = [];
if ($types !== '') {
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $exams[] = $row;
    $stmt->close();
} else {
    $result = $conn->query($query);
    if ($result) while ($row = $result->fetch_assoc()) $exams[] = $row;
}

// Get classes from Class Management + statuses for filter dropdowns
$classes  = examsGetClasses($conn);
$statuses = ['draft', 'review_requested', 'reviewed', 'approved', 'published', 'archived'];

// Bulk action handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'], $_POST['selected_ids'])) {
    $bulk   = in_array($_POST['bulk_action'], ['publish', 'archive', 'delete']) ? $_POST['bulk_action'] : '';
    $ids    = array_map('intval', (array) $_POST['selected_ids']);
    if ($bulk && count($ids) > 0) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $bindTypes = str_repeat('i', count($ids));
        if ($bulk === 'delete') {
            $bs = $conn->prepare("DELETE FROM generated_exams WHERE id IN ({$placeholders})");
        } elseif ($bulk === 'publish') {
            $bs = $conn->prepare("UPDATE generated_exams SET status='published' WHERE id IN ({$placeholders})");
        } else {
            $bs = $conn->prepare("UPDATE generated_exams SET status='archived' WHERE id IN ({$placeholders})");
        }
        $bs->bind_param($bindTypes, ...$ids);
        $bs->execute();
        $bs->close();
        header('Location: view_exams.php?bulk_done=' . $bulk);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Workflow - EduTrack PRO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .board-container { max-width: 1450px; margin: 30px auto; padding: 20px; }
        .section-card { background: #fff; border-radius: 14px; padding: 24px; margin-bottom: 24px; box-shadow: 0 6px 20px rgba(0,0,0,.05); border: 1px solid #e9ecef; }
        .exam-preview { background: #fff; border: 1px solid #dee2e6; border-radius: 12px; padding: 24px; min-height: 350px; }
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('exams_generator/' . basename($_SERVER['PHP_SELF'])); ?>
        </nav>
    <div class="main-content">
        <main class="content">
            <div class="board-container">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-diagram-project text-primary me-2"></i>Exam Workflow Board</h2>
                    <a href="exam_paper_generator.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>New Exam</a>
                </div>

                <!-- Filter bar -->
                <?php if (isset($_GET['bulk_done'])): ?>
                    <div class="alert alert-success alert-dismissible fade show mb-3">
                        Bulk action "<?= htmlspecialchars((string) $_GET['bulk_done']) ?>" completed.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form method="GET" class="row g-2 align-items-end mb-3" id="filterForm">
                    <div class="col-md-3">
                        <label class="form-label fw-semibold small">Search Title/Subject</label>
                        <input type="text" name="subject" class="form-control form-control-sm"
                               placeholder="e.g. Mathematics" value="<?= htmlspecialchars($filterSubject) ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Class</label>
                        <select name="class" class="form-select form-select-sm">
                            <option value="">All Classes</option>
                            <?php foreach ($classes as $cls): ?>
                                <option value="<?= htmlspecialchars($cls) ?>" <?= $cls === $filterClass ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($cls) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Status</label>
                        <select name="status" class="form-select form-select-sm">
                            <option value="">All Statuses</option>
                            <?php foreach ($statuses as $st): ?>
                                <option value="<?= $st ?>" <?= $st === $filterStatus ? 'selected' : '' ?>>
                                    <?= ucfirst(str_replace('_', ' ', $st)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-search me-1"></i> Filter
                        </button>
                        <a href="view_exams.php" class="btn btn-outline-secondary btn-sm ms-1">
                            <i class="fas fa-times"></i> Clear
                        </a>
                    </div>
                    <div class="col-auto ms-auto text-muted small">
                        <?= count($exams) ?> exam(s) found
                    </div>
                </form>

                <div class="section-card">
                    <form method="POST" id="bulkForm">
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <select name="bulk_action" class="form-select form-select-sm" style="max-width:160px">
                            <option value="">Bulk Action…</option>
                            <option value="publish">Publish Selected</option>
                            <option value="archive">Archive Selected</option>
                            <option value="delete">Delete Selected</option>
                        </select>
                        <button type="submit" class="btn btn-sm btn-outline-secondary"
                                onclick="return confirmBulk()">Apply</button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle" id="examsTable">
                            <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAll" class="form-check-input"></th>
                                <th>Title</th>
                                <th>Status</th>
                                <th>Class</th>
                                <th>Subject</th>
                                <th>Creator</th>
                                <th>Updated</th>
                                <th>Actions</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($exams)): ?>
                                <tr><td colspan="8" class="text-center py-4 text-muted">
                                    <?php if ($filterStatus || $filterClass || $filterSubject): ?>
                                        No exams match the current filters. <a href="view_exams.php">Clear filters</a>
                                    <?php else: ?>
                                        No exams yet. <a href="exam_paper_generator.php">Create your first exam</a>
                                    <?php endif; ?>
                                </td></tr>
                            <?php else: ?>
                                <?php foreach ($exams as $exam): ?>
                                    <tr>
                                        <td><input type="checkbox" name="selected_ids[]"
                                                   value="<?= (int) $exam['id'] ?>" class="form-check-input exam-cb"></td>
                                        <td><strong><?= htmlspecialchars($exam['title']) ?></strong></td>
                                        <td><span class="badge <?= getStatusBadgeClass($exam['status'] ?? 'draft') ?>"><?= htmlspecialchars(getStatusLabel($exam['status'] ?? 'draft')) ?></span></td>
                                        <td><?= htmlspecialchars($exam['class_name']) ?></td>
                                        <td><?= htmlspecialchars($exam['subject_name']) ?></td>
                                        <td><?= htmlspecialchars($exam['creator_name'] ?? 'System') ?></td>
                                        <td class="small text-muted"><?= htmlspecialchars(date('d M Y', strtotime($exam['updated_at'] ?? $exam['created_at']))) ?></td>
                                        <td>
                                            <a class="btn btn-sm btn-outline-primary me-1"
                                               href="view_exams.php?view=<?= (int) $exam['id'] ?>"><i class="fas fa-eye"></i></a>
                                            <a class="btn btn-sm btn-outline-success"
                                               href="download_pdf.php?id=<?= (int) $exam['id'] ?>"><i class="fas fa-download"></i></a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    </form>
                </div>

                <?php if ($selectedExam): ?>
                    <div class="row g-4">
                        <div class="col-lg-4">
                            <?php echo generateWorkflowSummaryHtml($selectedExam, $sessionUser); ?>
                            <div id="workflowBoardStatus"></div>
                        </div>
                        <div class="col-lg-8">
                            <div class="section-card">
                                <div id="workflowBoardPreview" class="exam-preview"><?php echo generateExamPreviewHtml($selectedExam); ?></div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    if ($('#examsTable tbody tr').length > 1) {
        $('#examsTable').DataTable({
            pageLength: 25,
            order: [[6, 'desc']],
            columnDefs: [{ orderable: false, targets: [0, 7] }]
        });
    }

    $('#selectAll').on('change', function() {
        $('.exam-cb').prop('checked', this.checked);
    });
});

function confirmBulk() {
    const action = document.querySelector('[name="bulk_action"]').value;
    const selected = document.querySelectorAll('.exam-cb:checked').length;
    if (!action) { alert('Please select a bulk action.'); return false; }
    if (selected === 0) { alert('Please select at least one exam.'); return false; }
    const actionLabel = action === 'delete' ? 'DELETE' : action.charAt(0).toUpperCase() + action.slice(1);
    return confirm(`${actionLabel} ${selected} selected exam(s)? This cannot be undone.`);
}
</script>
<script>
$(document).on('click', '.workflow-action-btn', function () {
    const action = $(this).data('action');
    const examId = <?php echo (int) ($selectedExam['id'] ?? 0); ?>;
    if (!examId) return;

    $.ajax({
        url: 'ajax/workflow_action.php',
        type: 'POST',
        dataType: 'json',
        data: { exam_id: examId, workflow_action: action, note: $('#workflowNote').val() || '' },
        success: function (response) {
            if (!response.success) {
                $('#workflowBoardStatus').html('<div class="alert alert-danger">' + response.message + '</div>');
                return;
            }
            $('#workflowBoardStatus').html('<div class="alert alert-success">' + response.message + '</div>');
            $('.card.border-0.shadow-sm.mb-3').replaceWith(response.workflow_html);
            $('#workflowBoardPreview').html(response.preview);
        },
        error: function () {
            $('#workflowBoardStatus').html('<div class="alert alert-danger">Workflow action failed.</div>');
        }
    });
});
</script>
</body>
</html>
