<?php
// admin/cbt_approval.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

// 1. SECURITY: Admin only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login.php"); exit();
}

$message = "";

// --- ACTION: BULK APPROVAL/REJECTION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $exam_id = (int)$_POST['exam_id'];
    $note = trim($_POST['rejection_note'] ?? '');
    $new_status = ($_POST['bulk_action'] === 'approve_all') ? 1 : 2; // 1=Active, 2=Rejected
    
    try {
        $pdo->beginTransaction();
        // Update Exam Status
        $stmt1 = $pdo->prepare("UPDATE exams SET status = ? WHERE id = ?");
        $stmt1->execute([$new_status, $exam_id]);
        
        // Update All Questions in that exam
        $stmt2 = $pdo->prepare("UPDATE questions SET status = ?, rejection_note = ? WHERE exam_id = ? AND status = 'pending'");
        $stmt2->execute([($new_status == 1 ? 'approved' : 'rejected'), $note, $exam_id]);
        
        $pdo->commit();
        header("Location: cbt_approval.php?msg=" . ($new_status == 1 ? 'approved' : 'rejected'));
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = "<div class='alert error'>System Error: " . $e->getMessage() . "</div>";
    }
}

// --- VIEW LOGIC ---
$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : null;

if ($exam_id) {
    $stmt = $pdo->prepare("SELECT q.*, e.exam_title FROM questions q JOIN exams e ON q.exam_id = e.id WHERE q.exam_id = ? AND q.status = 'pending'");
    $stmt->execute([$exam_id]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!$questions) { header("Location: cbt_approval.php"); exit(); }
} else {
    $stmt = $pdo->query("SELECT e.id, e.exam_title, u.fullname, COUNT(q.id) as q_count 
                         FROM exams e JOIN questions q ON q.exam_id = e.id 
                         JOIN users u ON e.teacher_id = u.id 
                         WHERE q.status = 'pending' OR e.status = 0
                         GROUP BY e.id HAVING q_count > 0");
    $pending_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vetting Center | Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { 
            --primary: #0f172a; --accent: #6366f1; --bg: #f8fafc; 
            --success: #10b981; --danger: #ef4444; --card-shadow: 0 10px 15px -3px rgba(0,0,0,0.04);
        }
        
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--primary); margin: 0; padding: 0; line-height: 1.6; }
        .wrapper { max-width: 1100px; margin: 0 auto; padding: 40px 20px; }

        /* Navigation */
        .glass-nav { 
            background: rgba(255, 255, 255, 0.8); backdrop-filter: blur(12px); 
            display: flex; justify-content: space-between; align-items: center;
            padding: 15px 25px; border-radius: 20px; border: 1px solid #ffffff;
            box-shadow: var(--card-shadow); margin-bottom: 40px; position: sticky; top: 20px; z-index: 100;
        }

        .btn-nav { text-decoration: none; padding: 10px 18px; border-radius: 12px; font-weight: 700; font-size: 13px; display: flex; align-items: center; gap: 8px; transition: 0.2s; }
        .btn-back { background: #f1f5f9; color: #475569; }
        .btn-dash { background: var(--primary); color: white; }

        /* Grid Cards */
        .vetting-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; }
        .vet-card { 
            background: white; border-radius: 24px; padding: 25px; border: 1px solid #f1f5f9; 
            text-decoration: none; color: inherit; box-shadow: var(--card-shadow); display: block;
        }
        .vet-card:hover { transform: translateY(-5px); border-color: var(--accent); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.06); }
        
        .q-count { background: #eef2ff; color: var(--accent); padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 800; }

        /* Details View */
        .q-container { background: white; border-radius: 24px; padding: 30px; margin-bottom: 20px; border: 1px solid #f1f5f9; box-shadow: var(--card-shadow); }
        .option-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 15px; }
        .option { padding: 12px; border-radius: 10px; background: #f8fafc; font-size: 14px; border: 1px solid transparent; }
        .option.correct { background: #dcfce7; color: #166534; font-weight: 700; border-color: #bbf7d0; }

        /* Decision Panel */
        .decision-bar { 
            background: white; border-radius: 24px; padding: 30px; margin-top: 50px; 
            border: 2px solid #f1f5f9; box-shadow: 0 -10px 40px rgba(0,0,0,0.03); 
        }
        textarea { width: 100%; border: 1px solid #e2e8f0; border-radius: 15px; padding: 15px; font-family: inherit; margin: 15px 0; resize: none; }
        .btn-action { border: none; padding: 16px 30px; border-radius: 15px; font-weight: 800; cursor: pointer; flex: 1; color: white; display: flex; align-items: center; justify-content: center; gap: 10px; font-size: 15px; }
        .btn-approve { background: var(--success); box-shadow: 0 10px 15px -3px rgba(16, 185, 129, 0.2); }
        .btn-reject { background: var(--danger); box-shadow: 0 10px 15px -3px rgba(239, 68, 68, 0.2); }

        .alert { padding: 15px; border-radius: 15px; text-align: center; font-weight: 700; margin-bottom: 25px; }
        .alert.success { background: #dcfce7; color: #166534; }
    </style>
</head>
<body>

<div class="wrapper">
    <nav class="glass-nav">
        <?php if($exam_id): ?>
            <a href="cbt_approval.php" class="btn-nav btn-back"><i class="fa fa-arrow-left"></i> Back to Queue</a>
        <?php else: ?>
            <span style="font-weight: 800; font-size: 18px;"><i class="fa fa-shield-halved" style="color:var(--accent)"></i> Vetting Center</span>
        <?php endif; ?>
        <a href="dashboard.php" class="btn-nav btn-dash">Dashboard</a>
    </nav>

    <?php if(isset($_GET['msg'])): ?>
        <div class="alert success">Action completed: Exam set has been <?= $_GET['msg'] ?>.</div>
    <?php endif; ?>

    <?php if (!$exam_id): ?>
        <h1 style="font-weight: 800;">Pending Review</h1>
        <p style="color: #64748b; margin-bottom: 30px;">Select an exam set to review and approve for the student lobby.</p>
        
        <div class="vetting-grid">
            <?php foreach ($pending_exams as $e): ?>
                <a href="?exam_id=<?= $e['id'] ?>" class="vet-card">
                    <div style="display:flex; justify-content: space-between; align-items: flex-start;">
                        <span class="q-count"><?= $e['q_count'] ?> QUESTIONS</span>
                        <i class="fa fa-chevron-right" style="color: #cbd5e1; font-size: 12px;"></i>
                    </div>
                    <h3 style="margin: 15px 0 5px 0; font-weight: 800;"><?= htmlspecialchars($e['exam_title']) ?></h3>
                    <p style="margin:0; font-size: 13px; color: #64748b;">Submitted by: <strong><?= htmlspecialchars($e['fullname']) ?></strong></p>
                </a>
            <?php endforeach; ?>
        </div>

        <?php if(empty($pending_exams)): ?>
            <div style="text-align:center; padding: 80px 0;">
                <i class="fa fa-circle-check" style="font-size: 50px; color: #cbd5e1;"></i>
                <h3 style="color: #94a3b8;">Queue is empty. Everything is up to date!</h3>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div style="margin-bottom: 40px;">
            <h1 style="font-weight: 800; margin: 0;"><?= htmlspecialchars($questions[0]['exam_title']) ?></h1>
            <p style="color: #64748b;">Reviewing all questions in this set. Decision applied to the whole subject.</p>
        </div>

        <?php foreach ($questions as $i => $q): ?>
            <div class="q-container">
                <div style="font-size: 12px; font-weight: 800; color: var(--accent); margin-bottom: 10px;">QUESTION <?= $i+1 ?></div>
                <div style="font-size: 18px; font-weight: 700;"><?= htmlspecialchars($q['question_text']) ?></div>
                
                <div class="option-row">
                    <div class="option <?= $q['correct_option'] == 'A' ? 'correct' : '' ?>">A: <?= htmlspecialchars($q['option_a']) ?></div>
                    <div class="option <?= $q['correct_option'] == 'B' ? 'correct' : '' ?>">B: <?= htmlspecialchars($q['option_b']) ?></div>
                    <div class="option <?= $q['correct_option'] == 'C' ? 'correct' : '' ?>">C: <?= htmlspecialchars($q['option_c']) ?></div>
                    <div class="option <?= $q['correct_option'] == 'D' ? 'correct' : '' ?>">D: <?= htmlspecialchars($q['option_d']) ?></div>
                </div>
            </div>
        <?php endforeach; ?>

        <div class="decision-bar">
            <h3 style="margin: 0;"><i class="fa fa-gavel"></i> Final Decision</h3>
            <p style="font-size: 13px; color: #64748b;">Provide feedback if rejecting so the teacher can make corrections.</p>
            
            <form method="POST">
                <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
                <textarea name="rejection_note" placeholder="Optional: Type correction notes for the teacher here..."></textarea>
                
                <div style="display: flex; gap: 20px;">
                    <button type="submit" name="bulk_action" value="reject_all" class="btn-action btn-reject" onclick="return confirm('Send back to teacher for corrections?')">
                        <i class="fa fa-circle-xmark"></i> Reject Entire Set
                    </button>
                    <button type="submit" name="bulk_action" value="approve_all" class="btn-action btn-approve" onclick="return confirm('Approve and publish this exam?')">
                        <i class="fa fa-circle-check"></i> Approve & Publish
                    </button>
                </div>
            </form>
        </div>
    <?php endif; ?>
</div>

</body>
</html>