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

// --- UPDATED AUTH CHECK ---
// Allow both admin and subadmin to manage result releases
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

// 1. Fetch current system settings
$stmtSet = $pdo->query("SELECT * FROM system_settings LIMIT 1");
$settings = $stmtSet->fetch();
$school_name = $settings['school_name'] ?? "School Portal";

// 2. Handle Session/Term selection
$active_session = $_GET['session'] ?? ($settings['active_session'] ?? "2025/2026");
$active_term = $_GET['term'] ?? ($settings['active_term'] ?? "FIRST TERM");

// 3. AUDIT QUERY
try {
    $stmtMissing = $pdo->prepare("
        SELECT u.fullname as teacher, s.subject_name, c.class_name
        FROM teacher_subjects ts
        JOIN users u ON ts.teacher_id = u.id
        JOIN subjects s ON ts.subject_id = s.id
        JOIN classes c ON ts.class_id = c.id
        WHERE u.role = 'teacher' 
        AND NOT EXISTS (
            SELECT 1 FROM results r 
            WHERE r.subject_id = ts.subject_id 
            AND r.class_id = ts.class_id 
            AND r.session = :sess 
            AND r.term = :term
        )
    ");
    $stmtMissing->execute([':sess' => $active_session, ':term' => $active_term]);
    $pending_teachers = $stmtMissing->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $pending_teachers = [];
    $error_msg = "Database synchronization error.";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Result Release Manager | <?php echo htmlspecialchars($school_name); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --success: #27ae60; --danger: #e74c3c; --slate: #64748b; }
        
        body { font-family: 'Inter', 'Segoe UI', sans-serif; background: #f4f7f6; margin: 0; padding: 15px; color: #333; }
        .container { max-width: 900px; margin: 0 auto; background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
        
        .header-box { border-bottom: 2px solid #eee; margin-bottom: 25px; padding-bottom: 15px; display: flex; justify-content: space-between; align-items: center; }
        h2 { color: var(--primary); margin: 0; font-size: 1.5rem; }
        
        /* RESPONSIVE FILTER GRID */
        .filter-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 25px; background: #f8fafc; padding: 15px; border-radius: 8px; border: 1px solid #e2e8f0; }
        label { display: block; font-weight: bold; margin-bottom: 8px; font-size: 13px; color: var(--slate); }
        select { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; background: white; font-size: 14px; }

        .audit-card { padding: 20px; border-radius: 8px; margin-bottom: 25px; border: 1px solid transparent; }
        .status-warning { background: #fff5f5; border-color: #feb2b2; color: #c53030; }
        .status-success { background: #f0fff4; border-color: #9ae6b4; color: #276749; }
        
        ul { margin-top: 15px; padding-left: 20px; }
        li { margin-bottom: 10px; font-size: 14px; line-height: 1.4; }

        /* RESPONSIVE BUTTON GROUP */
        .btn-group { display: flex; gap: 12px; flex-wrap: wrap; }
        .btn { padding: 14px 20px; border-radius: 6px; border: none; font-weight: 700; cursor: pointer; text-decoration: none; font-size: 14px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
        .btn-release { background: var(--success); color: white; flex: 1; min-width: 200px; }
        .btn-hide { background: var(--danger); color: white; flex: 1; min-width: 200px; }
        .btn-back { background: var(--slate); color: white; padding: 10px 15px; }

        /* MOBILE BREAKPOINTS */
        @media (max-width: 600px) {
            body { padding: 10px; }
            .container { padding: 15px; }
            .header-box { flex-direction: column; align-items: flex-start; gap: 10px; }
            .filter-grid { grid-template-columns: 1fr; } /* Stack filters */
            .btn-group { flex-direction: column; }
            .btn-release, .btn-hide { width: 100%; }
            h2 { font-size: 1.25rem; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header-box">
        <h2><i class="fa fa-bullhorn"></i> Release Manager</h2>
        <a href="dashboard.php" class="btn btn-back"><i class="fa fa-arrow-left"></i> Back</a>
    </div>

    <form method="GET">
        <div class="filter-grid">
            <div>
                <label><i class="fa fa-calendar"></i> Academic Session</label>
                <select name="session" onchange="this.form.submit()">
                    <option value="2024/2025" <?php if($active_session == '2024/2025') echo 'selected'; ?>>2024/2025</option>
                    <option value="2025/2026" <?php if($active_session == '2025/2026') echo 'selected'; ?>>2025/2026</option>
                </select>
            </div>
            <div>
                <label><i class="fa fa-clock"></i> Academic Term</label>
                <select name="term" onchange="this.form.submit()">
                    <option value="FIRST TERM" <?php if($active_term == 'FIRST TERM') echo 'selected'; ?>>FIRST TERM</option>
                    <option value="SECOND TERM" <?php if($active_term == 'SECOND TERM') echo 'selected'; ?>>SECOND TERM</option>
                    <option value="THIRD TERM" <?php if($active_term == 'THIRD TERM') echo 'selected'; ?>>THIRD TERM</option>
                </select>
            </div>
        </div>
    </form>

    <?php if (!empty($pending_teachers)): ?>
        <div class="audit-card status-warning">
            <h3 style="margin-top: 0;"><i class="fa fa-exclamation-triangle"></i> Pending Submissions (<?php echo count($pending_teachers); ?>)</h3>
            <p>Allocations in <strong><?php echo htmlspecialchars($active_term); ?></strong> missing scores:</p>
            <ul>
                <?php foreach ($pending_teachers as $t): ?>
                    <li>
                        <strong><?php echo htmlspecialchars($t['teacher']); ?></strong><br>
                        <small><?php echo htmlspecialchars($t['subject_name']); ?> — <?php echo htmlspecialchars($t['class_name']); ?></small>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php else: ?>
        <div class="audit-card status-success">
            <h3 style="margin-top: 0;"><i class="fa fa-check-circle"></i> Ready for Release</h3>
            <p>All teachers assigned for <strong><?php echo htmlspecialchars($active_term); ?></strong> have submitted scores.</p>
        </div>
    <?php endif; ?>

    <form action="release_results.php" method="POST" onsubmit="return confirm('Update visibility for all results in this term?');">
        <input type="hidden" name="session" value="<?php echo htmlspecialchars($active_session); ?>">
        <input type="hidden" name="term" value="<?php echo htmlspecialchars($active_term); ?>">
        
        <div class="btn-group">
            <button type="submit" name="release_action" value="release" class="btn btn-release">
                <i class="fa fa-eye"></i> PUBLISH ALL RESULTS
            </button>
            <button type="submit" name="release_action" value="hide" class="btn btn-hide">
                <i class="fa fa-eye-slash"></i> HIDE ALL RESULTS
            </button>
        </div>
        <p style="text-align: center; margin-top: 15px;"><small>Action will affect the <strong><?php echo htmlspecialchars($active_term); ?></strong> session.</small></p>
    </form>
</div>

</body>
</html>