<?php
// admin/select_results.php
session_start();
$projectRoot = dirname(__DIR__);
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

/** * 1. FETCH DYNAMIC SETTINGS FROM DATABASE **/
try {
    // Pulling from system_settings table
    $stmt = $pdo->query("SELECT active_session, active_term FROM system_settings LIMIT 1");
    $sys = $stmt->fetch(PDO::FETCH_ASSOC);

    // Define the active targets
    $active_session = $sys['active_session'] ?? '2025/2026'; 
    $active_term = $sys['active_term'] ?? 'FIRST TERM';

    /** 2. FETCH DROPDOWN DATA **/
    $checkCol = $pdo->query("SHOW COLUMNS FROM users LIKE 'fullname'");
    $colName = ($checkCol->rowCount() > 0) ? "fullname" : "name";
    
    $teachers = $pdo->query("SELECT id, $colName AS fullname FROM users WHERE role = 'teacher' ORDER BY fullname ASC")->fetchAll();
    $classes = $pdo->query("SELECT id, class_name FROM classes ORDER BY class_name ASC")->fetchAll();
    $subjects = $pdo->query("SELECT id, subject_name FROM subjects ORDER BY subject_name ASC")->fetchAll();

    // 3. FETCH HISTORICAL SESSIONS
    // Get unique sessions that already have results
    $sessions = $pdo->query("SELECT DISTINCT session FROM results WHERE session IS NOT NULL AND session != '' ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);

    // 4. THE FIX: ENSURE THE ADMIN-SET SESSION IS IN THE LIST
    // If the database query didn't find the current year (because it's new), we add it manually.
    if (!in_array($active_session, $sessions)) {
        $sessions[] = $active_session;
    }
    
    // Sort again so the newest year stays at the top
    rsort($sessions);

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

$term_options = ['FIRST TERM', 'SECOND TERM', 'THIRD TERM'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Results for Approval</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --accent: #3498db; --bg: #f4f7f6; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: var(--bg); padding: 40px 20px; }
        
        .filter-card { 
            background: #fff; padding: 30px; border-radius: 12px; max-width: 600px; margin: 0 auto; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.1); border-top: 5px solid var(--accent); 
        }

        h2 { text-align: center; color: var(--primary); margin-top: 0; }
        .active-banner { 
            background: #ebf8ff; color: #2b6cb0; padding: 10px; border-radius: 6px; 
            text-align: center; font-size: 13px; font-weight: 600; margin-bottom: 25px;
            border: 1px solid #bee3f8;
        }

        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .full-width { grid-column: span 2; }
        label { font-size: 12px; font-weight: 700; color: #4a5568; margin-bottom: 8px; display: block; text-transform: uppercase; }
        
        select { 
            width: 100%; padding: 12px; border: 2px solid #e2e8f0; border-radius: 8px; 
            outline: none; background: #f8fafc; transition: border 0.2s;
        }
        select:focus { border-color: var(--accent); background: #fff; }

        .btn-view { 
            width: 100%; background: var(--primary); color: #fff; border: none; padding: 15px; 
            border-radius: 8px; font-weight: 700; cursor: pointer; margin-top: 20px;
            display: flex; align-items: center; justify-content: center; gap: 10px;
        }
        .btn-view:hover { background: #1a252f; }
        .back { display: block; text-align: center; margin-top: 20px; color: #a0aec0; text-decoration: none; font-size: 13px; }
    </style>
</head>
<body>

<div class="filter-card">
    <h2><i class="fa fa-file-signature"></i> Result Approval</h2>
    <div class="active-banner">
        Current Settings: <?= htmlspecialchars($active_session) ?> | <?= htmlspecialchars($active_term) ?>
    </div>

    <form action="approve_results.php" method="GET">
        <div class="form-grid">
            
            <div class="form-group">
                <label>Academic Session</label>
                <select name="session" required>
                    <?php foreach($sessions as $s): ?>
                        <option value="<?= htmlspecialchars($s) ?>" <?= ($s == $active_session) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($s) ?> <?= ($s == $active_session) ? '(Active)' : '' ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Term</label>
                <select name="term" required>
                    <?php foreach($term_options as $t): ?>
                        <option value="<?= $t ?>" <?= (strtoupper($t) == strtoupper($active_term)) ? 'selected' : '' ?>>
                            <?= $t ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group full-width">
                <label>Teacher</label>
                <select name="teacher_id" required>
                    <option value="">-- Choose Teacher --</option>
                    <?php foreach($teachers as $t): ?>
                        <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['fullname']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Class</label>
                <select name="class_id" required>
                    <option value="">-- Select Class --</option>
                    <?php foreach($classes as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['class_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Subject</label>
                <select name="subject_id" required>
                    <option value="">-- Select Subject --</option>
                    <?php foreach($subjects as $s): ?>
                        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['subject_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

        </div>

        <button type="submit" class="btn-view">
            <i class="fa fa-search"></i> VIEW SUBMITTED RESULTS
        </button>
        
        <a href="dashboard.php" class="back"><i class="fa fa-arrow-left"></i> Return to Dashboard</a>
    </form>
</div>

</body>
</html>