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

$class_id     = (int)($_GET['class_id'] ?? 0);
$subject_id   = (int)($_GET['subject_id'] ?? 0); 
$subject_name = $_GET['subject_name'] ?? 'Subject'; 
$session      = $_GET['session'] ?? '';
$term         = $_GET['term'] ?? '';

if (!$class_id || !$subject_id || empty($session) || empty($term)) {
    die("Missing parameters.");
}

// 1. FETCH DATA
$query = "SELECT s.id, s.fullname, r.ca_score, r.exam_score, r.status, r.rejection_reason,
          (SELECT er.score FROM exam_results er JOIN exams e ON er.exam_id = e.id 
           WHERE er.student_id = s.id AND e.subject_id = ? ORDER BY er.id DESC LIMIT 1) as cbt_score
          FROM students s 
          LEFT JOIN results r ON s.id = r.student_id 
          AND r.subject_id = ? AND r.term = ? AND r.session = ?
          WHERE s.class_id = ? ORDER BY s.fullname ASC";

$stmt = $pdo->prepare($query);
$stmt->execute([$subject_id, $subject_id, $term, $session, $class_id]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. STATUS ENGINE
$status = $students[0]['status'] ?? 'not_started';
$rejection_reason = $students[0]['rejection_reason'] ?? null;

// Only lock if it is actually sitting with the Admin (pending) or finished (approved)
$is_locked = ($status === 'pending' || $status === 'approved');

// 3. SAVE AS DRAFT OR SUBMIT TO ADMIN
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$is_locked) {
    $new_status = isset($_POST['submit_to_admin']) ? 'pending' : 'saved';
    
    try {
        $pdo->beginTransaction();
        foreach ($_POST['ca'] as $student_id => $ca_val) {
            $student_id = (int)$student_id;
            $ca_score   = (float)$ca_val;
            $exam_score = (float)($_POST['exam'][$student_id] ?? 0);
            $total      = $ca_score + $exam_score;

            $sql = "INSERT INTO results 
                    (student_id, subject_id, class_id, subject_name, ca_score, exam_score, total_score, term, session, status, rejection_reason) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
                    ON DUPLICATE KEY UPDATE 
                    ca_score = VALUES(ca_score), exam_score = VALUES(exam_score), total_score = VALUES(total_score),
                    status = VALUES(status), rejection_reason = NULL";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$student_id, $subject_id, $class_id, $subject_name, $ca_score, $exam_score, $total, $term, $session, $new_status]);
        }
        $pdo->commit();
        header("Location: ".$_SERVER['REQUEST_URI']."&msg=Success");
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Score Entry | <?= htmlspecialchars($subject_name) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3b82f6;
            --success: #10b981;
            --danger: #ef4444;
            --slate-50: #f8fafc;
            --slate-100: #f1f5f9;
            --slate-700: #334155;
            --border: #e2e8f0;
        }

        body { 
            font-family: 'Inter', system-ui, sans-serif; 
            background-color: #f4f7f6; 
            color: #1e293b; 
            margin: 0; 
            padding: 40px 20px; 
        }

        .container { 
            max-width: 1000px; 
            margin: auto; 
            background: white; 
            padding: 30px; 
            border-radius: 20px; 
            box-shadow: 0 10px 25px -5px rgba(0,0,0,0.05); 
        }

        /* Top Navigation */
        .top-nav { margin-bottom: 25px; }
        .btn-back { 
            text-decoration: none; 
            color: #64748b; 
            font-weight: 600; 
            font-size: 14px; 
            display: inline-flex; 
            align-items: center; 
            gap: 8px; 
        }
        .btn-back:hover { color: var(--primary); }

        /* Header Area */
        .header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding-bottom: 20px; 
            border-bottom: 1px solid var(--border);
            margin-bottom: 25px;
        }

        .header h2 { margin: 0; font-size: 22px; font-weight: 800; }
        .status-badge { 
            font-size: 12px; 
            padding: 4px 12px; 
            border-radius: 99px; 
            text-transform: uppercase; 
            font-weight: 700;
            background: var(--slate-100);
        }
        .status-rejected { background: #fee2e2; color: #b91c1c; }
        .status-pending { background: #e0e7ff; color: #3730a3; }
        .status-approved { background: #dcfce7; color: #166534; }

        /* Rejection Message */
        .rejection-box { 
            background: #fff1f2; 
            border: 1px solid #fecdd3; 
            padding: 20px; 
            border-radius: 12px; 
            margin-bottom: 25px; 
            display: flex; 
            gap: 15px;
            align-items: flex-start;
        }
        .rejection-box i { color: var(--danger); font-size: 20px; }
        .rejection-box div b { color: #9f1239; display: block; margin-bottom: 5px; }
        .rejection-box p { margin: 0; color: #be123c; font-size: 14px; line-height: 1.5; }

        /* Table Design */
        table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
        th { 
            text-align: left; 
            padding: 12px 15px; 
            background: var(--slate-50); 
            color: #64748b; 
            font-size: 11px; 
            text-transform: uppercase; 
            letter-spacing: 0.05em;
            border-bottom: 2px solid var(--border);
        }
        td { padding: 15px; border-bottom: 1px solid var(--border); vertical-align: middle; }
        
        input[type="number"] { 
            width: 80px; 
            padding: 8px 12px; 
            border: 1px solid var(--border); 
            border-radius: 8px; 
            font-family: inherit;
            font-weight: 600;
        }
        input[type="number"]:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(59,130,246,0.1); }
        input:disabled { background: #f1f5f9; cursor: not-allowed; border-color: transparent; }

        .cbt-score { font-weight: 700; color: var(--primary); background: #eff6ff; padding: 4px 10px; border-radius: 6px; }

        /* Actions */
        .flex-actions { 
            display: flex; 
            gap: 12px; 
            justify-content: flex-end; 
            padding-top: 20px; 
            border-top: 1px solid var(--border); 
        }

        .btn { 
            padding: 12px 24px; 
            border-radius: 10px; 
            border: none; 
            font-weight: 700; 
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            gap: 8px; 
            transition: 0.2s; 
        }

        .btn-draft { background: white; color: var(--slate-700); border: 1px solid var(--border); }
        .btn-draft:hover { background: var(--slate-50); }

        .btn-submit { background: var(--success); color: white; }
        .btn-submit:hover { background: #059669; transform: translateY(-1px); }

        .btn-sync { background: var(--primary); color: white; font-size: 13px; padding: 8px 16px; }

        .btn-locked { background: var(--slate-100); color: #94a3b8; cursor: not-allowed; }

        .alert-success { background: #dcfce7; color: #166534; padding: 15px; border-radius: 10px; margin-bottom: 20px; font-weight: 600; }
    </style>
</head>
<body>

<div class="container">
    <div class="top-nav">
        <a href="dashboard.php" class="btn-back"><i class="fa fa-arrow-left"></i> Back to Dashboard</a>
    </div>

    <?php if ($status === 'rejected' && $rejection_reason): ?>
        <div class="rejection-box">
            <i class="fa fa-circle-exclamation"></i>
            <div>
                <b>Correction Required from Admin:</b>
                <p><?= htmlspecialchars($rejection_reason) ?></p>
            </div>
        </div>
    <?php endif; ?>

    <div class="box">
        <div class="header">
            <div>
                <h2><?= htmlspecialchars($subject_name) ?></h2>
                <span class="status-badge status-<?= $status ?>"><?= str_replace('_', ' ', $status) ?></span>
            </div>
            <?php if (!$is_locked): ?>
                <button type="button" class="btn btn-sync" onclick="syncCBT()">
                    <i class="fa fa-sync"></i> Sync CBT Scores
                </button>
            <?php endif; ?>
        </div>

        <?php if (isset($_GET['msg'])): ?>
            <div class="alert-success"><i class="fa fa-check-circle"></i> Scores saved successfully!</div>
        <?php endif; ?>

        <form method="POST">
            <table>
                <thead>
                    <tr>
                        <th>Student Fullname</th>
                        <th>Continuous Assessment (40)</th>
                        <th>Exam Score (60)</th>
                        <th>CBT Score (Ref)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $s): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($s['fullname']) ?></strong></td>
                        <td>
                            <input type="number" step="0.01" max="40" name="ca[<?= $s['id'] ?>]" 
                                   value="<?= $s['ca_score'] ?? 0 ?>" <?= $is_locked ? 'disabled' : '' ?>>
                        </td>
                        <td>
                            <input type="number" step="0.01" max="60" name="exam[<?= $s['id'] ?>]" id="exam_<?= $s['id'] ?>" 
                                   value="<?= $s['exam_score'] ?? 0 ?>" <?= $is_locked ? 'disabled' : '' ?>>
                        </td>
                        <td>
                            <span class="cbt-score" id="cbt_val_<?= $s['id'] ?>"><?= $s['cbt_score'] ?? 0 ?></span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="flex-actions">
                <?php if (!$is_locked): ?>
                    <button type="submit" name="save_draft" class="btn btn-draft">
                        <i class="fa fa-save"></i> Save Draft
                    </button>
                    <button type="submit" name="submit_to_admin" class="btn btn-submit" 
                            onclick="return confirm('Ready to submit? This will lock the scores for Admin review.')">
                        <i class="fa fa-paper-plane"></i> Push to Admin
                    </button>
                <?php else: ?>
                    <div class="btn btn-locked">
                        <i class="fa fa-lock"></i> Scores Locked (<?= ucfirst($status) ?>)
                    </div>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<script>
function syncCBT() {
    <?php foreach ($students as $s): ?>
        document.getElementById('exam_<?= $s['id'] ?>').value = document.getElementById('cbt_val_<?= $s['id'] ?>').innerText;
    <?php endforeach; ?>
    alert("CBT scores synced to Exam column. Don't forget to save!");
}
</script>

</body>
</html>