<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

// Stats
$total_students = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role = 'student'")->fetchColumn();
$total_exams = (int)$pdo->query("SELECT COUNT(*) FROM exams")->fetchColumn();
$active_exams = (int)$pdo->query("SELECT COUNT(*) FROM exams WHERE status = 'active'")->fetchColumn();
$total_results = (int)$pdo->query("SELECT COUNT(*) FROM results")->fetchColumn();

// Attempts today by hour
$hours_stmt = $pdo->query("
    SELECT HOUR(r.date_taken) AS h, COUNT(*) AS c
    FROM results r
    WHERE DATE(r.date_taken) = CURDATE()
    GROUP BY HOUR(r.date_taken)
    ORDER BY HOUR(r.date_taken)
");
$hour_counts = array_fill(0, 24, 0);
foreach ($hours_stmt->fetchAll() as $row) {
    $hour = (int)$row['h'];
    $hour_counts[$hour] = (int)$row['c'];
}
$max_hour_count = max($hour_counts);
$max_hour_count = $max_hour_count > 0 ? $max_hour_count : 1;
$total_today_attempts = array_sum($hour_counts);

// Attempts by exam today (top 5)
$exams_today_stmt = $pdo->query("
    SELECT e.title, COUNT(r.result_id) AS cnt
    FROM results r
    JOIN exams e ON r.exam_id = e.exam_id
    WHERE DATE(r.date_taken) = CURDATE()
    GROUP BY e.exam_id
    ORDER BY cnt DESC
    LIMIT 5
");
$exams_today = $exams_today_stmt->fetchAll();

// Exam overview (latest 10)
$exams_stmt = $pdo->query("
    SELECT e.exam_id, e.title, e.status, e.session, e.term, s.name AS subject_name, c.class_name,
           COUNT(r.result_id) AS attempt_count
    FROM exams e
    LEFT JOIN subjects s ON e.subject_id = s.subject_id
    LEFT JOIN classes c ON e.class_id = c.class_id
    LEFT JOIN results r ON e.exam_id = r.exam_id
    GROUP BY e.exam_id
    ORDER BY e.exam_id DESC
    LIMIT 10
");
$exam_overview = $exams_stmt->fetchAll();

// Students overview (latest 10)
$students_stmt = $pdo->query("
    SELECT u.user_id, u.username, u.full_name, c.class_name
    FROM users u
    LEFT JOIN classes c ON u.class_id = c.class_id
    WHERE u.role = 'student'
    ORDER BY u.user_id DESC
    LIMIT 10
");
$students_overview = $students_stmt->fetchAll();
// Live log
try {
    $log_stmt = $pdo->query("
        SELECT l.*, u.username, u.full_name, e.title AS exam_title
        FROM student_activity_log l
        LEFT JOIN users u ON l.user_id = u.user_id
        LEFT JOIN exams e ON l.exam_id = e.exam_id
        ORDER BY l.created_at DESC
        LIMIT 25
    ");
    $live_logs = $log_stmt->fetchAll();
} catch (PDOException $e) {
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS student_activity_log (
                log_id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                activity VARCHAR(50) NOT NULL,
                exam_id INT DEFAULT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_user_created (user_id, created_at)
            ) ENGINE=InnoDB
        ");
        $live_logs = [];
    } catch (PDOException $e2) {
        $live_logs = [];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        <div class="card fade-in">
            <h1>Dashboard</h1>
            <div class="grid" style="grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px;">
                <div class="card" style="padding:16px;">
                    <h3>Total Students</h3>
                    <div style="font-size:28px; font-weight:700; color: var(--heading-color);"><?php echo $total_students; ?></div>
                </div>
                <div class="card" style="padding:16px;">
                    <h3>Total Exams</h3>
                    <div style="font-size:28px; font-weight:700; color: var(--heading-color);"><?php echo $total_exams; ?></div>
                </div>
                <div class="card" style="padding:16px;">
                    <h3>Active Exams</h3>
                    <div style="font-size:28px; font-weight:700; color: var(--heading-color);"><?php echo $active_exams; ?></div>
                </div>
                <div class="card" style="padding:16px;">
                    <h3>Total Attempts</h3>
                    <div style="font-size:28px; font-weight:700; color: var(--heading-color);"><?php echo $total_results; ?></div>
                </div>
            </div>
        </div>
        
        <div class="card fade-in">
            <h3>Live Log (Latest 25)</h3>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Time</th>
                            <th>Student</th>
                            <th>Activity</th>
                            <th>Exam</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($live_logs as $log): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($log['created_at']); ?></td>
                            <td><?php echo htmlspecialchars(($log['full_name'] ?: $log['username']) ?: ''); ?></td>
                            <td><?php echo htmlspecialchars($log['activity']); ?></td>
                            <td><?php echo htmlspecialchars($log['exam_title'] ?: '-'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($live_logs)): ?>
                        <tr><td colspan="4">No activity yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card fade-in">
            <h3>Attempts Today</h3>
            <?php if ($total_today_attempts > 0): ?>
                <div style="display:flex; align-items:flex-end; gap:12px;">
                    <div style="display:flex; flex-direction:column; justify-content:space-between; height: 180px; padding: 6px 0; color: var(--secondary-color); font-size: 12px;">
                        <span><?php echo $max_hour_count; ?></span>
                        <span><?php echo (int)ceil($max_hour_count/2); ?></span>
                        <span>0</span>
                    </div>
                    <div style="flex:1; display: grid; grid-template-columns: repeat(24, 1fr); align-items: end; gap: 6px; height: 180px; padding: 10px; background: #fff; border: 1px solid var(--border-color); border-radius: 8px;">
                        <?php for ($h = 0; $h < 24; $h++): 
                            $val = $hour_counts[$h];
                            $height = ($val / $max_hour_count) * 150;
                        ?>
                            <div style="display:flex; flex-direction:column; align-items:center; gap:6px;">
                                <div style="font-size:11px; color: var(--secondary-color);"><?php echo $val ?: ''; ?></div>
                                <div title="<?php echo $val; ?>" style="width: 100%; height: <?php echo (int)$height; ?>px; background: var(--primary-color); border-radius: 6px;"></div>
                                <div style="font-size: 11px; color: var(--secondary-color);"><?php echo $h; ?></div>
                            </div>
                        <?php endfor; ?>
                    </div>
                </div>
                <div style="margin-top:8px; font-size:12px; color: var(--secondary-color);">
                    Total attempts today: <strong><?php echo $total_today_attempts; ?></strong>
                </div>
            <?php else: ?>
                <div style="padding: 16px; background: #fff; border: 1px solid var(--border-color); border-radius: 8px; color: var(--secondary-color);">
                    No attempts recorded yet today.
                </div>
            <?php endif; ?>
        </div>

        <div class="card fade-in">
            <h3>Exam Overview</h3>
            <table>
                <thead>
                    <tr>
                        <th>Exam Title</th>
                        <th>Class</th>
                        <th>Subject</th>
                        <th>Session/Term</th>
                        <th>Status</th>
                        <th>Attempts</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($exam_overview as $ex): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($ex['title']); ?></td>
                        <td><?php echo htmlspecialchars($ex['class_name'] ?? 'All'); ?></td>
                        <td><?php echo htmlspecialchars($ex['subject_name']); ?></td>
                        <td><?php echo htmlspecialchars(trim(($ex['session'] ?? '') . ' ' . ($ex['term'] ?? ''))); ?></td>
                        <td>
                            <span class="btn <?php echo ($ex['status'] === 'active') ? 'btn-success' : 'btn-warning'; ?>" style="pointer-events:none; padding:6px 10px;">
                                <?php echo ucfirst($ex['status']); ?>
                            </span>
                        </td>
                        <td><?php echo (int)$ex['attempt_count']; ?></td>
                        <td>
                            <a href="results.php?view=list&exam_id=<?php echo $ex['exam_id']; ?>" class="btn btn-primary">Results</a>
                            <a href="preview_exam.php?exam_id=<?php echo $ex['exam_id']; ?>" class="btn" target="_blank">Preview</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="card fade-in">
            <h3>Students Overview</h3>
            <table>
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Name</th>
                        <th>Class</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students_overview as $s): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($s['username']); ?></td>
                        <td><?php echo htmlspecialchars($s['full_name'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($s['class_name'] ?? 'N/A'); ?></td>
                        <td>
                            <a href="users.php" class="btn">Manage</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div class="card fade-in">
            <h3>Top Exams by Attempts Today</h3>
            <?php if (!empty($exams_today)): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Exam Title</th>
                            <th>Attempts</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($exams_today as $et): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($et['title']); ?></td>
                            <td><?php echo (int)$et['cnt']; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div style="padding: 12px; background: #fff; border: 1px solid var(--border-color); border-radius: 8px; color: var(--secondary-color);">
                    No attempts yet today.
                </div>
            <?php endif; ?>
        </div>
        
        <div class="main-footer">
            &copy; 2026 Designed by FGV
        </div>
    </div>
</body>
</html>
