<?php
// FILE PATH: C:\xampp\htdocs\Project\student\dashboard.php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$db_path = "../config/database.php";

if (file_exists($db_path)) {
    require_once $db_path;
} else {
    die("Configuration Error: database.php not found.");
}

// ACCESS CONTROL
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    header("Location: ../auth/login.php"); 
    exit();
}

$student_id = $_SESSION['user_id']; 

try {
    // 1. FETCH STUDENT DATA
    $stmt = $pdo->prepare("SELECT s.*, c.class_name 
                           FROM students s 
                           LEFT JOIN classes c ON s.class_id = c.id 
                           WHERE s.id = ?");
    $stmt->execute([$student_id]);
    $user = $stmt->fetch();

    if (!$user) {
        die("User profile not found.");
    }

    // 2. FETCH SYSTEM SETTINGS
    $stmtSet = $pdo->query("SELECT * FROM system_settings LIMIT 1");
    $settings = $stmtSet->fetch();
    
    $sys_session = trim($settings['active_session'] ?? '');
    $sys_term    = trim($settings['active_term'] ?? '');

    // 3. FETCH PENDING CBT EXAMS COUNT (SYNCED WITH LOBBY LOGIC)
    $active_exams_count = 0;
    if (!empty($user['class_id'])) {
        $stmtCbt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM exams e 
            WHERE e.class_id = ? 
            AND UPPER(TRIM(e.status)) = 'ACTIVE'
            -- Exclude exams the student has already submitted
            AND e.id NOT IN (
                SELECT exam_id 
                FROM exam_results 
                WHERE student_id = ?
            )
            -- Only count exams that actually have questions uploaded
            AND (SELECT COUNT(*) FROM questions WHERE exam_id = e.id) > 0
        ");

        $stmtCbt->execute([
            $user['class_id'], 
            $student_id
        ]);
        $active_exams_count = (int)$stmtCbt->fetchColumn();
    }

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | <?= htmlspecialchars($user['fullname']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --primary: #3498db; 
            --primary-dark: #2980b9;
            --dark: #1a252f; 
            --sidebar-bg: #1a252f;
            --bg: #f8f9fa; 
            --text-main: #2c3e50; 
            --text-muted: #7f8c8d;
            --white: #ffffff; 
            --shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        body { font-family: 'Inter', 'Segoe UI', sans-serif; margin: 0; background: var(--bg); display: flex; color: var(--text-main); min-height: 100vh; }
        
        /* Sidebar Styling */
        .sidebar { width: 260px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: white; transition: all 0.3s; z-index: 1000; left: 0; }
        .sidebar-header { padding: 30px 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-logo { width: 70px; height: 70px; object-fit: contain; background: white; border-radius: 50%; padding: 5px; margin-bottom: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        .sidebar-header h2 { font-size: 16px; margin: 0; color: var(--primary); letter-spacing: 1px; }

        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a { display: flex; align-items: center; padding: 12px 25px; color: #bdc3c7; text-decoration: none; transition: 0.3s; font-size: 14px; border-left: 4px solid transparent; }
        .sidebar-nav a i { margin-right: 12px; width: 20px; text-align: center; font-size: 16px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: rgba(255,255,255,0.05); color: white; border-left: 4px solid var(--primary); }
        
        /* Main Content */
        .main-content { margin-left: 260px; flex: 1; padding: 30px; box-sizing: border-box; transition: all 0.3s; width: 100%; }
        
        .mobile-toggle { display: none; position: fixed; top: 20px; right: 20px; z-index: 1001; background: var(--primary); color: white; border: none; padding: 10px 15px; border-radius: 5px; cursor: pointer; box-shadow: var(--shadow); }

        /* Top Header */
        .top-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; gap: 20px; }
        .welcome-msg h1 { margin: 0; font-size: 24px; font-weight: 700; }
        .welcome-msg p { margin: 5px 0 0; color: var(--text-muted); font-size: 14px; }

        /* Profile Card */
        .profile-card { 
            background: linear-gradient(135deg, var(--white) 0%, #fefefe 100%); 
            padding: 30px; 
            border-radius: 16px; 
            box-shadow: var(--shadow); 
            display: flex; 
            align-items: center; 
            gap: 25px; 
            margin-bottom: 30px; 
            border: 1px solid rgba(0,0,0,0.05);
            flex-wrap: wrap;
        }
        .profile-pic { width: 100px; height: 100px; border-radius: 12px; object-fit: cover; border: 3px solid var(--white); box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        .profile-info h2 { margin: 0; font-size: 22px; }
        .reg-badge { background: #eef2f7; padding: 4px 12px; border-radius: 6px; font-size: 13px; font-weight: 600; color: var(--text-muted); display: inline-block; margin: 8px 0; }
        .class-tag { background: var(--primary); color: white; padding: 4px 12px; border-radius: 6px; font-size: 12px; font-weight: bold; margin-left: 10px; }

        /* Stats Grid */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card { background: var(--white); padding: 20px; border-radius: 12px; box-shadow: var(--shadow); border-top: 4px solid var(--primary); display: flex; flex-direction: column; align-items: center; }
        .stat-card i { font-size: 24px; color: var(--primary); margin-bottom: 10px; }
        .stat-card h4 { margin: 0; font-size: 12px; color: var(--text-muted); text-transform: uppercase; }
        .stat-card p { margin: 8px 0 0; font-size: 18px; font-weight: 700; color: var(--text-main); }

        .details-section { background: var(--white); padding: 25px; border-radius: 16px; box-shadow: var(--shadow); }
        .section-title { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 15px; flex-wrap: wrap; gap: 10px; }
        .section-title h3 { margin: 0; font-size: 18px; display: flex; align-items: center; gap: 10px; }
        
        .info-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 25px; }
        .info-item { display: flex; flex-direction: column; }
        .info-item label { font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 4px; }
        .info-item span { font-size: 15px; font-weight: 500; color: var(--text-main); word-break: break-word; }

        .alert-box { margin-top: 30px; background: #fff8e1; border-left: 5px solid #ffc107; padding: 20px; border-radius: 10px; display: flex; gap: 15px; align-items: flex-start; }
        .logout-link { color: #e74c3c !important; font-weight: bold; margin-top: 50px; }

        @media (max-width: 992px) {
            .sidebar { left: -260px; }
            .sidebar.active { left: 0; }
            .main-content { margin-left: 0; }
            .mobile-toggle { display: block; }
        }
    </style>
</head>
<body>

    <button class="mobile-toggle" onclick="toggleSidebar()">
        <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=School&background=3498db&color=fff'">
            <h2>STUDENT PORTAL</h2>
            <p style="font-size: 10px; color: #7f8c8d; margin-top: 5px;"><?= htmlspecialchars($settings['school_name'] ?? 'School Management') ?></p>
        </div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="active"><i class="fa fa-home"></i> Dashboard</a>
            <a href="cbt_lobby.php"><i class="fa fa-edit" style="color: #2ecc71;"></i> Take CBT Exam</a>
            <a href="results.php"><i class="fa fa-chart-line"></i> My Results</a>
            <a href="dashboard.php"><i class="fa fa-calendar-check"></i> Attendance</a>
            <a href="profile.php"><i class="fa fa-user-cog"></i> Profile Settings</a>
            <a href="../auth/logout.php" class="logout-link"><i class="fa fa-sign-out-alt"></i> Logout</a>
        </nav>
    </div>

    <div class="main-content">
        <div class="top-header">
            <div class="welcome-msg">
                <h1>Hello, <?= htmlspecialchars(explode(' ', $user['fullname'])[0]) ?>! 👋</h1>
                <p>Here is what's happening with your academic profile.</p>
            </div>
            <div style="text-align: right;">
                <p style="margin:0; font-weight: 600; color: var(--text-main);"><?= date('l') ?></p>
                <p style="margin:0; font-size: 13px; color: var(--text-muted);"><?= date('jS F, Y') ?></p>
            </div>
        </div>

        <div class="profile-card">
            <img src="../uploads/students/<?= htmlspecialchars($user['photo'] ?: 'default.png') ?>" 
                 class="profile-pic" 
                 onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($user['fullname']) ?>&background=3498db&color=fff'">
            
            <div class="profile-info">
                <h2><?= htmlspecialchars($user['fullname']) ?> <span class="class-tag"><?= htmlspecialchars($user['class_name'] ?? 'Unassigned') ?></span></h2>
                <span class="reg-badge"><i class="fa fa-id-card"></i> <?= htmlspecialchars($user['reg_number']) ?></span>
                <p style="margin: 5px 0 0; font-size: 14px; color: var(--text-muted);"><i class="fa fa-map-marker-alt"></i> <?= htmlspecialchars($user['address'] ?? 'No Address') ?></p>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card" style="border-top-color: #2ecc71;">
                <i class="fa fa-laptop-code" style="color: #2ecc71;"></i>
                <h4>Available Exams</h4>
                <p><?= $active_exams_count ?> Pending</p>
                <a href="cbt_lobby.php" style="font-size: 11px; color: #2ecc71; text-decoration: none; font-weight: bold; margin-top: 5px;">ENTER LOBBY &rarr;</a>
            </div>

            <div class="stat-card">
                <i class="fa fa-calendar"></i>
                <h4>Current Session</h4>
                <p><?= htmlspecialchars($sys_session) ?></p>
            </div>
            <div class="stat-card" style="border-top-color: #27ae60;">
                <i class="fa fa-clock" style="color: #27ae60;"></i>
                <h4>Active Term</h4>
                <p><?= htmlspecialchars($sys_term) ?></p>
            </div>
            <div class="stat-card" style="border-top-color: #f1c40f;">
                <i class="fa fa-user-check" style="color: #f1c40f;"></i>
                <h4>Account Status</h4>
                <p><?= htmlspecialchars($user['status'] ?? 'Active') ?></p>
            </div>
        </div>

        <div class="details-section">
            <div class="section-title">
                <h3><i class="fa fa-clipboard-list" style="color: var(--primary);"></i> Personal Details</h3>
                <a href="profile.php" style="text-decoration: none; color: var(--primary); font-size: 13px; font-weight: bold;"><i class="fa fa-edit"></i> Edit Profile</a>
            </div>
            
            <div class="info-grid">
                <div class="info-item"><label>Gender</label><span><?= htmlspecialchars($user['gender'] ?? 'N/A') ?></span></div>
                <div class="info-item"><label>Date of Birth</label><span><?= !empty($user['dob']) ? date('d M, Y', strtotime($user['dob'])) : 'Not Set' ?></span></div>
                <div class="info-item"><label>Email Address</label><span><?= htmlspecialchars($user['email'] ?? 'N/A') ?></span></div>
                <div class="info-item"><label>Phone</label><span><?= htmlspecialchars($user['phone'] ?? 'N/A') ?></span></div>
                <div class="info-item"><label>Parent/Guardian</label><span><?= htmlspecialchars($user['parent_name'] ?? 'N/A') ?></span></div>
                <div class="info-item"><label>Parent Phone</label><span><?= htmlspecialchars($user['parent_phone'] ?? 'N/A') ?></span></div>
            </div>
        </div>

        <?php if(!empty($settings['announcement'])): ?>
        <div class="alert-box">
            <i class="fa fa-bullhorn" style="color: #ffc107; font-size: 20px;"></i>
            <div>
                <h4 style="margin: 0 0 5px 0;">School Announcement</h4>
                <p style="margin: 0; font-size: 14px; color: #5d4037; line-height: 1.5;"><?= nl2br(htmlspecialchars($settings['announcement'])) ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleSidebar() { document.getElementById('sidebar').classList.toggle('active'); }
    </script>
</body>
</html>