<?php
require_once('source/dbconfig.php');
require_once('source/function.php');

session_start();

// Redirect if not logged in
if (!isset($_SESSION['student']) || !isset($_SESSION['exam_info'])) {
    header("Location: cbt_index.php");
    exit();
}

// Initialize
$student = $_SESSION['student'];
$exam_info = $_SESSION['exam_info'];
$availableExams = [];
$error = null;

try {
    // 1. Check if exams exist for this class/term/session
    $stmt = $DBH->prepare("
        SELECT 
            ec.exam_id,
            e.exam_name,
            e.exam_description,
            COUNT(es.id) AS subject_count
        FROM tbl_exam_class ec
        JOIN tbl_exam e ON ec.exam_id = e.id
        LEFT JOIN tbl_exam_subject es ON ec.exam_id = es.exam_id
        WHERE ec.class = :class
        AND ec.term = :term
        AND ec.session = :session
        GROUP BY ec.exam_id
    ");
    
    $stmt->execute([
        'class' => $exam_info['class'],
        'term' => $exam_info['term'],
        'session' => $exam_info['session']
    ]);
    
    $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($exams)) {
        $availableExams = [];
    } else {
        // 2. Get all subjects for these exams with completion status 
        $stmt = $DBH->prepare("
            SELECT 
                es.id AS exam_subject_id,
                s.id AS subject_id,
                s.subject,
                es.exam_date,
                es.duration_minutes,
                cbt.id AS cbt_result_id,
                cbt.score AS cbt_score,
                cbt.date_taken,
                cbt.correct_answers,
                cbt.total_questions,
                r.exam AS regular_exam_score
            FROM tbl_exam_class ec
            JOIN tbl_exam_subject es ON ec.exam_id = es.exam_id
            JOIN tbl_subject s ON es.subject_id = s.id
            LEFT JOIN tbl_cbt_results cbt ON cbt.subject = s.subject
                                         AND cbt.registration_no = :reg_no
                                         AND cbt.term = ec.term
                                         AND cbt.session = ec.session
            LEFT JOIN tbl_student_results r ON r.subject = s.subject
                                          AND r.registration_no = :reg_no
                                          AND r.term = ec.term
                                          AND r.year = ec.session
            WHERE ec.class = :class
            AND ec.term = :term
            AND ec.session = :session
            ORDER BY es.exam_date ASC, s.subject ASC
        ");
        
        $stmt->execute([
            'reg_no' => $student['registration_no'],
            'class' => $exam_info['class'],
            'term' => $exam_info['term'],
            'session' => $exam_info['session']
        ]);
        
        $availableExams = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
} catch (Exception $e) {
    $error = "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>Welcome - CBT Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .exam-card {
            transition: all 0.3s ease;
            border-left: 4px solid #6c757d;
        }
        .exam-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .future-exam { border-left-color: #ffc107; }
        .available-exam { border-left-color: #17a2b8; }
        .completed-exam { border-left-color: #28a745; }
        .timer-display {
            font-size: 1.2rem;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <div class="text-center mb-4">
            <h2>Welcome, <?= htmlspecialchars($student['fullname']) ?></h2>
            <div class="d-flex justify-content-center gap-2 mb-3">
                <span class="badge bg-primary"><?= htmlspecialchars($student['registration_no']) ?></span>
                <span class="badge bg-secondary"><?= htmlspecialchars($exam_info['class']) ?></span>
                <span class="badge bg-info"><?= htmlspecialchars($exam_info['term']) ?></span>
                <span class="badge bg-success"><?= htmlspecialchars($exam_info['session']) ?></span>
            </div>
        </div>

        <?php if (empty($availableExams)): ?>
            <div class="alert alert-info">
                <h4 class="alert-heading">No Exams Available</h4>
                <p>There are currently no exams scheduled for your class in <?= htmlspecialchars($exam_info['term']) ?> <?= htmlspecialchars($exam_info['session']) ?>.</p>
            </div>
        <?php else: ?>
            <div class="mb-4">
                <h4 class="text-center mb-3">Available Examination Subjects</h4>
                
                <?php foreach ($availableExams as $exam): 
                    $currentDate = new DateTime();
                    $examDate = new DateTime($exam['exam_date']);
                    $isFuture = $examDate > $currentDate;
                    $isCompleted = !empty($exam['cbt_result_id']);
                ?>
                    <div class="exam-card card mb-3 <?= $isFuture ? 'future-exam' : ($isCompleted ? 'completed-exam' : 'available-exam') ?>">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h5 class="card-title"><?= htmlspecialchars($exam['subject']) ?></h5>
                                    <p class="card-text">
                                        <small class="text-muted">
                                            Exam Date: <?= date('F j, Y', strtotime($exam['exam_date'])) ?>
                                            <?php if ($exam['duration_minutes']): ?>
                                                | Duration: <?= $exam['duration_minutes'] ?> minutes
                                            <?php endif; ?>
                                        </small>
                                    </p>
                                </div>
                                <span class="badge <?= $isFuture ? 'bg-warning' : ($isCompleted ? 'bg-success' : 'bg-info') ?>">
                                    <?= $isFuture ? 'Future' : ($isCompleted ? 'Completed' : 'Available') ?>
                                </span>
                            </div>
                            
                            <div class="mt-3">
                                <?php if ($isCompleted): ?>
                                    <div class="alert alert-success py-2">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <p class="mb-1">Completed on <?= date('F j, Y', strtotime($exam['date_taken'])) ?></p>
                                                <p class="mb-0">Score: <strong><?= $exam['cbt_score'] ?>%</strong> (<?= $exam['correct_answers'] ?>/<?= $exam['total_questions'] ?> correct)</p>
                                            </div>
                                            <a href="view_score.php?result_id=<?= $exam['cbt_result_id'] ?>" class="btn btn-sm btn-success">
                                                View Results
                                            </a>
                                        </div>
                                    </div>
                                
                                <?php elseif ($isFuture): ?>
                                    <div class="alert alert-warning py-2">
                                        <p class="mb-0">This exam will be available on <?= date('F j, Y', strtotime($exam['exam_date'])) ?>.</p>
                                    </div>
                                
                                <?php else: ?>
                                    <div class="alert alert-info py-2">
                                        <p class="mb-2">This exam was scheduled for <?= date('F j, Y', strtotime($exam['exam_date'])) ?>.</p>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <?php if ($exam['duration_minutes']): ?>
                                                    <span class="timer-display">Duration: <?= $exam['duration_minutes'] ?> minutes</span>
                                                <?php endif; ?>
                                            </div>
                                            <a href="cbt_exam_now.php?exam_subject_id=<?= $exam['exam_subject_id'] ?>" class="btn btn-primary">
                                                Start Exam
                                            </a>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <div class="text-center mt-4">
            <a href="logout.php" class="btn btn-outline-danger">Logout</a>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>