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

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

$message = '';
$error = '';

// Handle Reset Attempt
if (isset($_POST['reset_attempt'])) {
    $rid = $_POST['result_id'];
    $stmt = $pdo->prepare("DELETE FROM results WHERE result_id = ?");
    if ($stmt->execute([$rid])) {
        $message = "Student attempt cleared successfully.";
    } else {
        $error = "Failed to clear attempt.";
    }
}

$view = $_GET['view'] ?? 'exams';
$exam_id = $_GET['exam_id'] ?? null;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Results - Admin</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
    <style>
        .breadcrumbs { margin-bottom: 20px; }
        .breadcrumbs a { text-decoration: none; color: #007bff; }
    </style>
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        
        <?php if ($message): ?> <div style="color: green; padding: 10px; background: #e8f5e9; margin-bottom: 10px;"><?php echo $message; ?></div> <?php endif; ?>
        <?php if ($error): ?> <div style="color: red; padding: 10px; background: #ffebee; margin-bottom: 10px;"><?php echo $error; ?></div> <?php endif; ?>

        <?php if ($view == 'list' && $exam_id): ?>
            <?php
            // Fetch Exam Details
            $stmtEx = $pdo->prepare("SELECT * FROM exams WHERE exam_id = ?");
            $stmtEx->execute([$exam_id]);
            $exam = $stmtEx->fetch();

            // Fetch Results for this exam
            $stmt = $pdo->prepare("
                SELECT r.*, u.username, u.full_name, e.total_score 
                FROM results r 
                JOIN users u ON r.user_id = u.user_id 
                JOIN exams e ON r.exam_id = e.exam_id
                WHERE r.exam_id = ? 
                ORDER BY r.date_taken DESC
            ");
            $stmt->execute([$exam_id]);
            $results = $stmt->fetchAll();
            ?>
            
            <div class="breadcrumbs">
                <a href="results.php">Results</a> &gt; <span><?php echo htmlspecialchars($exam['title']); ?></span>
            </div>

            <h1>Results: <?php echo htmlspecialchars($exam['title']); ?></h1>
            
            <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Student</th>
                        <th>Score</th>
                        <th>Total</th>
                        <th>Percentage</th>
                        <th>Date Taken</th>
                        <th>Scaled</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $res): ?>
                    <tr>
                        <td>
                            <?php echo htmlspecialchars($res['full_name'] ?: $res['username']); ?>
                            <br><small style="color:#666;"><?php echo htmlspecialchars($res['username']); ?></small>
                        </td>
                        <td><?php echo $res['score']; ?></td>
                        <td><?php echo $res['total_questions']; ?></td>
                        <td>
                            <?php 
                            $pct = ($res['total_questions'] > 0) ? (($res['score'] / $res['total_questions']) * 100) : 0;
                            echo number_format($pct, 2) . '%';
                            ?>
                        </td>
                        <td><?php echo $res['date_taken']; ?></td>
                        <td>
                            <?php 
                            $scaled = ($res['total_questions'] > 0 && !empty($res['total_score'])) ? ($pct / 100) * (int)$res['total_score'] : 0;
                            echo number_format($scaled, 2) . ' / ' . (int)($res['total_score'] ?? 0);
                            ?>
                        </td>
                        <td>
                            <a href="export_pdf.php?result_id=<?php echo $res['result_id']; ?>" class="btn" target="_blank">PDF</a>
                            
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to clear this attempt? The student will be able to take the exam again.');">
                                <input type="hidden" name="result_id" value="<?php echo $res['result_id']; ?>">
                                <button type="submit" name="reset_attempt" class="btn btn-danger" style="background: #dc3545;">Reset</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($results)): ?>
                        <tr><td colspan="6">No results found for this exam.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>

        <?php else: ?>
            <!-- Grouped by Exam -->
            <h1>Exam Results</h1>
            
            <?php
            $stmt = $pdo->query("
                SELECT e.exam_id, e.title, 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
            ");
            $exams = $stmt->fetchAll();
            ?>

            <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Exam Title</th>
                        <th>Class</th>
                        <th>Subject</th>
                        <th>Session/Term</th>
                        <th>Attempts</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($exams 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 $ex['session'] . ' ' . $ex['term']; ?></td>
                        <td><?php echo $ex['attempt_count']; ?></td>
                        <td>
                            <a href="results.php?view=list&exam_id=<?php echo $ex['exam_id']; ?>" class="btn btn-primary">View Results</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        <?php endif; ?>
        
        <div class="main-footer">
            &copy; 2026 Designed by FGV
        </div>
    </div>
</body>
</html>
