<?php
session_start();
require_once '../config/database.php';

// 1. SECURITY CHECK (Optional but recommended)
// Ensure only admins can access this review page
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login.php");
    exit();
}

// Capture URL parameters
$subject_id = (int)$_GET['subject_id'];
$class_id   = (int)$_GET['class_id'];
$term       = $_GET['term'];
$session    = $_GET['session'];

$msg = "";

// --- 2. HANDLE APPROVAL OR REJECTION ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'];
    $reason = $_POST['rejection_reason'] ?? NULL;

    if ($action === 'approve') {
        // Update status from 'pending' to 'approved'
        $stmt = $pdo->prepare("UPDATE results SET status = 'approved', rejection_reason = NULL 
                               WHERE subject_id = ? AND class_id = ? AND term = ? AND session = ?");
        $stmt->execute([$subject_id, $class_id, $term, $session]);
        $msg = "<div class='alert success'><i class='fa fa-check-circle'></i> Results approved successfully!</div>";
    } elseif ($action === 'reject') {
        // Update status from 'pending' back to 'rejected' so teacher can edit again
        $stmt = $pdo->prepare("UPDATE results SET status = 'rejected', rejection_reason = ? 
                               WHERE subject_id = ? AND class_id = ? AND term = ? AND session = ?");
        $stmt->execute([$reason, $subject_id, $class_id, $term, $session]);
        $msg = "<div class='alert error'><i class='fa fa-times-circle'></i> Results rejected and sent back to teacher.</div>";
    }
}

// --- 3. FETCH RESULTS FOR REVIEW ---
// IMPORTANT: We join classes and subjects to get names, and we filter by status
$stmt = $pdo->prepare("SELECT r.*, s.fullname FROM results r 
                       JOIN students s ON r.student_id = s.id 
                       WHERE r.subject_id = ? AND r.class_id = ? AND r.term = ? AND r.session = ?");
$stmt->execute([$subject_id, $class_id, $term, $session]);
$results = $stmt->fetchAll();

// --- 4. GATEKEEPER CHECK ---
// If the teacher hasn't "Pushed" the results (status is still 'saved'), Admin shouldn't be here.
$current_status = $results[0]['status'] ?? 'not_started';

if ($current_status === 'saved') {
    $msg = "<div class='alert error'><i class='fa fa-lock'></i> ACCESS DENIED: The teacher has saved these scores as a draft but has not submitted them to the Admin for review yet.</div>";
    $hide_actions = true;
} else {
    $hide_actions = false;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Review Results | Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f4f7f6; padding: 20px; color: #333; }
        .container { background: white; padding: 30px; border-radius: 12px; max-width: 950px; margin: auto; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; border-bottom: 2px solid #eee; padding-bottom: 15px; }
        .btn-back { text-decoration: none; color: #666; font-weight: 600; font-size: 14px; transition: 0.3s; display: flex; align-items: center; gap: 8px; }
        .btn-back:hover { color: #3498db; }

        h2 { margin: 0; color: #2c3e50; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 25px; margin-top: 10px; }
        th { background: #f8f9fa; color: #7f8c8d; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; }
        th, td { padding: 14px; border-bottom: 1px solid #eee; text-align: left; }
        tr:hover { background: #fafafa; }
        
        .action-box { background: #f9fafb; padding: 25px; border-radius: 10px; border: 1px solid #e1e4e8; }
        .action-box h3 { margin-top: 0; font-size: 18px; color: #2c3e50; margin-bottom: 15px; }
        
        .btn-approve { background: #10b981; color: white; padding: 12px 25px; border: none; cursor: pointer; border-radius: 6px; font-weight: bold; transition: 0.2s; }
        .btn-approve:hover { background: #059669; transform: translateY(-1px); }
        
        .btn-reject { background: #ef4444; color: white; padding: 12px 25px; border: none; cursor: pointer; border-radius: 6px; font-weight: bold; transition: 0.2s; margin-left: 10px; }
        .btn-reject:hover { background: #dc2626; transform: translateY(-1px); }
        
        textarea { width: 100%; margin-bottom: 15px; padding: 12px; border-radius: 8px; border: 1px solid #ccc; font-family: inherit; box-sizing: border-box; resize: vertical; }
        
        .alert { padding: 15px; margin-bottom: 20px; border-radius: 8px; font-weight: bold; display: flex; align-items: center; gap: 10px; }
        .success { background: #dcfce7; color: #15803d; border-left: 5px solid #10b981; }
        .error { background: #fee2e2; color: #b91c1c; border-left: 5px solid #ef4444; }
        
        .status-badge { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; }
        .st-saved { background: #fef3c7; color: #92400e; }
        .st-pending { background: #e0e7ff; color: #3730a3; }
        .st-approved { background: #dcfce7; color: #166534; }
        .st-rejected { background: #fee2e2; color: #991b1b; }
    </style>
</head>
<body>

<div class="container">
    <div class="top-bar">
        <a href="dashboard.php" class="btn-back">
            <i class="fa fa-arrow-left"></i> Back to Admin Dashboard
        </a>
        <h2 style="font-size: 20px;">Review: <?= htmlspecialchars($results[0]['subject_name'] ?? 'Results') ?></h2>
    </div>

    <?= $msg ?>

    <?php if (!$hide_actions): ?>
    <table>
        <thead>
            <tr>
                <th>Student</th>
                <th>CA Score</th>
                <th>Exam Score</th>
                <th>Total</th>
                <th>Current Status</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($results as $r): ?>
            <tr>
                <td style="font-weight: 600;"><?= htmlspecialchars($r['fullname']) ?></td>
                <td><?= $r['ca_score'] ?></td>
                <td><?= $r['exam_score'] ?></td>
                <td><strong style="color: #2c3e50; font-size: 1.1em;"><?= $r['total_score'] ?></strong></td>
                <td><span class="status-badge st-<?= $r['status'] ?>"><?= strtoupper($r['status']) ?></span></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php if ($current_status === 'pending'): ?>
    <div class="action-box">
        <h3><i class="fa fa-gavel"></i> Decision Panel</h3>
        <form method="POST">
            <textarea name="rejection_reason" rows="3" placeholder="If rejecting, provide feedback for the teacher..."></textarea>
            <div style="display: flex; align-items: center;">
                <button type="submit" name="action" value="approve" class="btn-approve">
                    <i class="fa fa-check-circle"></i> APPROVE & FINALIZE
                </button>
                <button type="submit" name="action" value="reject" class="btn-reject" onclick="return confirm('Are you sure you want to reject these results?')">
                    <i class="fa fa-times-circle"></i> REJECT & RETURN
                </button>
            </div>
        </form>
    </div>
    <?php else: ?>
        <div style="text-align: center; color: #7f8c8d; padding: 20px; border: 2px dashed #eee; border-radius: 10px;">
            <i class="fa fa-info-circle"></i> This result set is currently <strong><?= strtoupper($current_status) ?></strong>. No further actions required.
        </div>
    <?php endif; ?>

    <?php endif; // End hide_actions ?>
</div>

</body>
</html>