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

// Check if user is logged in and is either admin or subadmin
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

$user_role = $_SESSION['role'];

// --- FETCH GLOBAL SYSTEM SETTINGS ---
$stmt = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
$settings = $stmt->fetch();
$current_session = $settings['active_session'] ?? "Not Set";
$current_term = $settings['active_term'] ?? "Not Set";
$school_name = $settings['school_name'] ?? "School Management System";

// --- FETCH QUICK STATS ---
$total_students = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
$total_teachers = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'teacher'")->fetchColumn();

// --- NEW: FETCH CBT STATS ---
$active_exams = $pdo->query("SELECT COUNT(*) FROM exams WHERE status = 'active'")->fetchColumn();

// Only fetch PIN counts if user is admin
$unused_pins = 0;
if ($user_role === 'admin') {
    $unused_pins = $pdo->query("SELECT COUNT(*) FROM pins WHERE status = 'unused'")->fetchColumn();
}

$pending_results = $pdo->query("SELECT COUNT(*) FROM results WHERE is_approved = 0 AND session = '$current_session' AND term = '$current_term'")->fetchColumn();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | <?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 { --sidebar-width: 260px; }
        body { font-family: 'Segoe UI', Arial, sans-serif; margin: 0; display: flex; background: #f0f2f5; transition: 0.3s; }
        
        /* SIDEBAR STYLES */
        .sidebar { 
            width: var(--sidebar-width); 
            height: 100vh; 
            background: #1a252f; 
            color: white; 
            padding: 20px; 
            position: fixed; 
            box-sizing: border-box; 
            overflow-y: auto; 
            z-index: 1000;
            transition: transform 0.3s ease;
        }
        .sidebar-header { text-align: center; margin-bottom: 25px; border-bottom: 1px solid #2c3e50; padding-bottom: 20px; }
        .sidebar-logo { width: 80px; height: 80px; object-fit: contain; border-radius: 50%; background: white; padding: 5px; margin-bottom: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.3); }
        .sidebar h2 { font-size: 18px; color: #3498db; margin: 0; text-transform: uppercase; }
        
        .sidebar a { color: #ecf0f1; text-decoration: none; display: block; padding: 12px 15px; border-radius: 5px; margin-bottom: 5px; transition: 0.3s; font-size: 14px; }
        .sidebar a:hover { background: #34495e; color: #3498db; }
        .sidebar .active { background: #3498db; color: white; }
        
        /* MOBILE TOGGLE */
        .mobile-nav-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            background: #1a252f;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            z-index: 1100;
            font-size: 20px;
        }

        /* MAIN CONTENT STYLES */
        .main-content { flex: 1; margin-left: var(--sidebar-width); padding: 40px; box-sizing: border-box; width: 100%; transition: 0.3s; }
        
        .header { background: white; padding: 20px 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; }
        .header h1 { margin: 0; font-size: 24px; color: #2c3e50; }
        
        .stats-bar { display: flex; gap: 20px; margin-bottom: 30px; flex-wrap: wrap; }
        .stat-item { background: #34495e; color: white; padding: 15px 20px; border-radius: 8px; font-size: 14px; flex: 1; text-align: center; min-width: 150px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .stat-item span { display: block; font-size: 24px; font-weight: bold; color: #3498db; margin-top: 5px; }
        .pending-count { color: #e67e22 !important; }

        .card-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 25px; }
        .card { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.07); text-align: center; transition: transform 0.2s; border-top: 5px solid transparent; }
        .card:hover { transform: translateY(-5px); }
        .card h3 { margin: 15px 0 10px 0; color: #2c3e50; }
        .card p { color: #7f8c8d; font-size: 14px; margin-bottom: 25px; line-height: 1.5; height: auto; min-height: 40px; }
        
        .btn-group { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
        .btn { text-decoration: none; padding: 10px 18px; border-radius: 6px; font-size: 13px; font-weight: 600; transition: 0.3s; border: none; cursor: pointer; display: inline-block; }
        .btn-primary { background: #3498db; color: white; }
        .btn-success { background: #27ae60; color: white; }
        .btn-dark { background: #1a252f; color: white; }
        .btn-orange { background: #e67e22; color: white; }
        .btn-purple { background: #9b59b6; color: white; }
        .btn-danger { background: #e74c3c; color: white; }
        .btn-cyan { background: #00bcd4; color: white; }

        .logout { color: #e74c3c !important; font-weight: bold; margin-top: 30px; border: 1px solid #e74c3c !important; text-align: center; }
        .logout:hover { background: #e74c3c !important; color: white !important; }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; text-align: center; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }

        /* RESPONSIVE QUERIES */
        @media (max-width: 992px) {
            .mobile-nav-toggle { display: block; }
            .sidebar { transform: translateX(-100%); }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 80px 20px 20px 20px; }
            .header { flex-direction: column; text-align: center; gap: 15px; }
            .header div { text-align: center !important; }
        }

        @media (max-width: 480px) {
            .stat-item { min-width: 100%; }
            .card-container { grid-template-columns: 1fr; }
            .header h1 { font-size: 20px; }
        }
    </style>
</head>
<body>

<button class="mobile-nav-toggle" id="menuBtn">
    <i class="fa fa-bars"></i>
</button>

<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <img src="../assets/img/logo.png" class="sidebar-logo" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($school_name); ?>&background=3498db&color=fff'">
        <h2>Admin Portal</h2>
        <p style="font-size: 12px; color: #bdc3c7; margin: 5px 0 0 0;"><?php echo htmlspecialchars($school_name); ?></p>
    </div>

    <p style="font-size: 11px; color: #7f8c8d; margin-bottom: 5px; padding-left: 15px;">WELCOME,</p>
    <p style="color: white; font-weight: bold; font-size: 16px; margin-top: 0; padding-left: 15px;"><?php echo htmlspecialchars($_SESSION['name'] ?? 'Staff'); ?></p>
    
    <hr style="border: 0; border-top: 1px solid #2c3e50; margin: 15px 0;">
    
    <a href="dashboard.php" class="active">🏠 Dashboard</a>
    <a href="academic/classes.php">📚 Manage Classes</a>
    <a href="academic/subjects.php">📖 Manage Subjects</a>
    <a href="users/students.php">🎓 Manage Students</a>
    <a href="users/teachers.php">👨‍🏫 Manage Teachers</a>
    
    <a href="cbt_approval.php">✅ CBT Approvals</a>
    <a href="push_cbt_results.php">🔄 Sync CBT Scores</a>
    
    <a href="results/index.php">📊 View Results (Broadsheet)</a>
    <a href="select_results.php?mode=view">📝 View Submissions</a>
    <a href="select_results.php?mode=approve">✅ Approve Results</a>
    <a href="manage_release.php">📢 Release Manager</a>
    
    <a href="academic/promote_students.php">🚀 Student Promotion</a>
    
    <?php if ($user_role === 'admin'): ?>
    <a href="academic/session_rollover.php">🔄 Session Rollover</a>
    <?php endif; ?>

    <a href="academic/assign_subjects.php">🔗 Subject Allocation</a>
    
    <?php if ($user_role === 'admin'): ?>
    <a href="pins/view_pins.php">🔑 PIN Records</a>
    <?php endif; ?>

    <a href="settings.php">⚙️ System Settings</a>
    
    <a href="../auth/logout.php" class="logout">Logout</a>
</div>

<div class="main-content">
    <div class="header">
        <div>
            <h1>Dashboard Overview</h1>
            <p style="margin: 5px 0 0 0; color: #7f8c8d;">System status: <span style="color: #27ae60; font-weight: bold;">● Online</span></p>
        </div>
        <div style="text-align: right;">
            <p style="margin: 0; font-weight: bold; color: #2c3e50; font-size: 18px;"><?php echo htmlspecialchars($current_session); ?></p>
            <p style="margin: 0; color: #3498db; font-weight: bold;"><?php echo htmlspecialchars($current_term); ?></p>
        </div>
    </div>

    <div class="stats-bar">
        <div class="stat-item">Total Students <span><?php echo $total_students; ?></span></div>
        <div class="stat-item">Total Staff <span><?php echo $total_teachers; ?></span></div>
        
        <div class="stat-item">Active CBTs <span><?php echo $active_exams; ?></span></div>

        <?php if ($user_role === 'admin'): ?>
        <div class="stat-item">Available PINs <span><?php echo $unused_pins; ?></span></div>
        <?php endif; ?>

        <div class="stat-item">Pending Approval <span class="pending-count"><?php echo $pending_results; ?></span></div>
    </div>

    <div class="card-container">
        <div class="card" style="border-top: 5px solid #00bcd4; background: #f0fbff;">
            <div style="font-size: 40px;">🕒</div>
            <h3>Exam Reschedule</h3>
            <p>Reset student exam attempts and manage re-take permissions for CBT subjects.</p>
            <div class="btn-group">
                <a href="reschedule.php" class="btn btn-cyan">Manage Retakes</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #f1c40f; background: #fffdf5;">
            <div style="font-size: 40px;">💻</div>
            <h3>CBT Suite</h3>
            <p>Review and approve teacher exams, or sync exam scores to terminal reports.</p>
            <div class="btn-group">
                <a href="cbt_approval.php" class="btn btn-orange">Approve Exams</a>
                <a href="push_cbt_results.php" class="btn btn-dark">Sync Scores</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #e74c3c; background: #fffaf9;">
            <div style="font-size: 40px;">🔄</div>
            <h3>Session & Promotion</h3>
            <p>Move students to the next class or perform annual session roll-over.</p>
            <div class="btn-group">
                <a href="academic/promote_students.php" class="btn btn-primary">Promote</a>
                <?php if ($user_role === 'admin'): ?>
                <a href="academic/session_rollover.php" class="btn btn-danger">Rollover</a>
                <?php endif; ?>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #27ae60; background: #f9fffb;">
            <div style="font-size: 40px;">📢</div>
            <h3>Master Release</h3>
            <p>Audit teacher submissions and publish results school-wide.</p>
            <div class="btn-group">
                <a href="manage_release.php" class="btn btn-success">Open Release Manager</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #2c3e50;">
            <div style="font-size: 40px;">📜</div>
            <h3>Result Analysis</h3>
            <p>Generate academic broadsheets or view/print bulk report cards for a class.</p>
            <div class="btn-group">
                <a href="results/index.php" class="btn btn-dark">View Result Center</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #27ae60;">
            <div style="font-size: 40px;">📊</div>
            <h3>Result Approval</h3>
            <p>Verify teacher submissions and approve them for student access.</p>
            <div class="btn-group">
                <a href="select_results.php?mode=view" class="btn btn-dark">Review</a>
                <a href="select_results.php?mode=approve" class="btn btn-success">Approve All</a>
            </div>
        </div>

        <?php if ($user_role === 'admin'): ?>
        <div class="card" style="border-top: 5px solid #e67e22;">
            <div style="font-size: 40px;">🔑</div>
            <h3>Access Control</h3>
            <p>Manage result checker PINs and generate batches for the term.</p>
            <div class="btn-group">
                <a href="pins/generate.php" class="btn btn-orange">Generate</a>
                <a href="pins/view_pins.php" class="btn btn-dark">Logs</a>
            </div>
        </div>
        <?php endif; ?>

        <div class="card" style="border-top: 5px solid #9b59b6;">
            <div style="font-size: 40px;">⚙️</div>
            <h3>System Config</h3>
            <p>Update school details, logo, stamp, and session/term settings.</p>
            <div class="btn-group">
                <a href="settings.php" class="btn btn-purple">Settings</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #3498db;">
            <div style="font-size: 40px;">🎓</div>
            <h3>Students</h3>
            <p>Enroll new students, promote students, or manage class lists.</p>
            <div class="btn-group">
                <a href="users/students.php" class="btn btn-primary">Manage Students</a>
            </div>
        </div>

        <div class="card" style="border-top: 5px solid #34495e;">
            <div style="font-size: 40px;">👨‍🏫</div>
            <h3>Staff & Allocation</h3>
            <p>Add teachers and link them to the subjects they teach in specific classes.</p>
            <div class="btn-group">
                <a href="users/teachers.php" class="btn btn-dark">Staff List</a>
                <a href="academic/assign_subjects.php" class="btn btn-primary">Allocate</a>
            </div>
        </div>
    </div>
</div>

<script>
    const menuBtn = document.getElementById('menuBtn');
    const sidebar = document.getElementById('sidebar');
    menuBtn.addEventListener('click', () => { sidebar.classList.toggle('active'); });
    document.querySelector('.main-content').addEventListener('click', () => {
        if(window.innerWidth <= 992) { sidebar.classList.remove('active'); }
    });
</script>

</body>
</html>