<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";
date_default_timezone_set('Africa/Lusaka'); 

if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

$studentid = $_SESSION['studentid'];
$intake    = $_SESSION['intake'];
$program   = $_SESSION['program'] ?? '';

$now_ts = time(); // current timestamp

// Fetch scheduled exams for student's intake and program
$query = "SELECT * FROM exam_schedule 
          WHERE intake='$intake' AND program='$program' 
          ORDER BY id  DESC";
$result = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scheduled Exams</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    :root {
        --primary-color: #238665;
        --secondary-color: #34a853;
        --light-bg: #f8f9fa;
        --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        --hover-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
    }
    
    body {
        background-color: #f5f7f9;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        color: #333;
    }
    
    .page-header {
        background: var(--primary-color);
        color: white;
        padding: 20px 0;
        border-radius: 15px ;
        margin-bottom: 30px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .exam-card {
        border: none;
        border-radius: 12px;
        box-shadow: var(--card-shadow);
        transition: all 0.3s ease;
        margin-bottom: 20px;
        overflow: hidden;
    }
    
    .exam-card:hover {
        transform: translateY(-5px);
        box-shadow: var(--hover-shadow);
    }
    
    .card-header {
        background:var(--primary-color);
        color: white;
        font-weight: 600;
        padding: 15px 20px;
        border-bottom: none;
    }
    
    .card-body {
        padding: 20px;
    }
    
    .exam-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }
    
    .exam-detail {
        display: flex;
        align-items: center;
        margin-right: 15px;
        margin-bottom: 10px;
    }
    
    .exam-detail i {
        margin-right: 8px;
        color: var(--primary-color);
        font-size: 16px;
    }
    
    .status-badge {
        padding: 6px 12px;
        border-radius: 50px;
        font-weight: 600;
        font-size: 13px;
    }
    
    .status-upcoming {
        background-color: #fff0c2;
        color: #b38700;
    }
    
    .status-active {
        background-color: #d1fae5;
        color: #065f46;
    }
    
    .status-completed {
        background-color: #fee2e2;
        color: #b91c1c;
    }
    
    .btn-take {
        background: linear-gradient(to right, var(--secondary-color), #4caf50);
        color: white;
        border: none;
        border-radius: 6px;
        padding: 10px 20px;
        font-weight: 600;
        transition: all 0.3s;
        box-shadow: 0 2px 8px rgba(52, 168, 83, 0.3);
    }
    
    .btn-take:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(52, 168, 83, 0.4);
        background: linear-gradient(to right, #2d9c4a, #43a047);
    }
    
    .btn-take:disabled {
        background: #b0b0b0;
        box-shadow: none;
        transform: none;
        cursor: not-allowed;
    }
    
    .result-card {
        background-color: #f8f9fa;
        border-left: 4px solid var(--primary-color);
        border-radius: 6px;
        padding: 15px;
    }
    
    .result-score {
        font-size: 22px;
        font-weight: 700;
        color: var(--primary-color);
    }
    
    .empty-state {
        text-align: center;
        padding: 40px 20px;
        background-color: white;
        border-radius: 12px;
        box-shadow: var(--card-shadow);
    }
    
    .empty-state i {
        font-size: 60px;
        color: #d1d5db;
        margin-bottom: 15px;
    }
    
    .time-indicator {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #f1f8ff;
        padding: 10px 15px;
        border-radius: 8px;
        margin-top: 15px;
        font-size: 14px;
    }
    
    .countdown {
        font-weight: 600;
        color: var(--primary-color);
    }
    
    @media (max-width: 768px) {
        .exam-info {
            flex-direction: column;
        }
        
        .exam-detail {
            margin-right: 0;
            width: 100%;
        }
    }
</style>
</head>
<body>
 <?php include "../include/nav.php"; ?>

    <div class="content" style="padding:0px">
      
        
<div class="page-header">
    <div class="container">
        <div class="d-flex align-items-center" >
            <div>
                <h2 class="mb-1"><i class="fa fa-calendar-check me-2"></i> Notice</h2>
                <p class="mb-0">Your Test has Started reflesh your page </p>
            </div>
        </div>
    </div>
</div>

<div class="container mb-5">
    <?php if(mysqli_num_rows($result) > 0): ?>
        <div class="row">
        <?php while($exam = mysqli_fetch_assoc($result)): 
            $exam_id   = $exam['id'];
            $exam_date = $exam['exam_date'];
            $start_time = $exam['start_time'];
            $end_time   = $exam['end_time'] ?? null;

            // Convert to timestamps
            $start_ts = strtotime($exam_date . ' ' . $start_time);
            $end_ts   = $end_time ? strtotime($exam_date . ' ' . $end_time) : null;

            // Determine if the exam can be taken
            $can_take = ($now_ts >= $start_ts) && (!$end_ts || $now_ts <= $end_ts);
            $is_upcoming = $now_ts < $start_ts;
            $is_completed = false;

            // ✅ Check if student already submitted
            $check_submitted = mysqli_fetch_assoc(mysqli_query(
                $conn,
                "SELECT * FROM exam_results_summary 
                 WHERE exam_id='$exam_id' AND student_id='$studentid' LIMIT 1"
            ));
            
            if ($check_submitted) {
                $is_completed = true;
            }
            
            // Format date for display
            $formatted_date = date('F j, Y', strtotime($exam_date));
            $formatted_start_time = date('g:i A', strtotime($start_time));
            $formatted_end_time = $end_time ? date('g:i A', strtotime($end_time)) : null;
        ?>
            <div class="col-lg-6 col-xl-4 mb-4">
                <div class="exam-card card">
                    <div class="card-header d-flex justify-content-between align-items-center" style="color:var(--primary-color);">
                        <span><?= htmlspecialchars($exam['course']) ?></span>
                        <?php if($is_completed): ?>
                            <span class="status-badge status-completed">Completed</span>
                        <?php elseif($can_take): ?>
                            <span class="status-badge status-active">Active</span>
                        <?php else: ?>
                            <span class="status-badge status-upcoming">Upcoming</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="card-body">
                        <div class="exam-info">
                            <div class="exam-detail">
                                <i class="fas fa-book"></i>
                                <span><?= htmlspecialchars($exam['program']) ?></span>
                            </div>
                            <div class="exam-detail">
                                <i class="fas fa-users"></i>
                                <span><?= htmlspecialchars($exam['intake']) ?></span>
                            </div>
                            <div class="exam-detail">
                                <i class="fas fa-calendar-alt"></i>
                                <span><?= $formatted_date ?></span>
                            </div>
                            <div class="exam-detail">
                                <i class="fas fa-clock"></i>
                                <span>
                                    <?= $formatted_start_time ?>
                                    <?= $formatted_end_time ? " - $formatted_end_time" : "" ?>
                                </span>
                            </div>
                        </div>
                        
                        <?php if($is_completed): ?>
                            <div class="result-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="d-block text-muted small">Your Score</span>
                                        <span class="result-score"><?= $check_submitted['score'] ?>/<?= $check_submitted['total'] ?></span>
                                    </div>
                                    <div class="text-end">
                                        <span class="d-block text-muted small">Submitted</span>
                                        <span class="small"><?= date('M j, Y g:i A', strtotime($check_submitted['submitted_at'])) ?></span>
                                    </div>
                                </div>
                            </div>
                        <?php elseif($can_take): ?>
                            <div class="d-grid">
                                <a href="take_exam.php?exam_id=<?= $exam_id ?>" class="btn btn-take">
                                    <i class="fa fa-pencil-alt me-2"></i> Start Test Now
                                </a>
                            </div>
                            
                            <?php if($end_ts): ?>
                                <div class="time-indicator">
                                    <span>Time remaining:</span>
                                    <span class="countdown" id="countdown-<?= $exam_id ?>"></span>
                                </div>
                                <script>
                                    // Countdown timer for active exams
                                    var endTime<?= $exam_id ?> = new Date(<?= $end_ts * 1000 ?>);
                                    function updateCountdown<?= $exam_id ?>() {
                                        var now = new Date().getTime();
                                        var distance = endTime<?= $exam_id ?> - now;
                                        
                                        if (distance < 0) {
                                            document.getElementById("countdown-<?= $exam_id ?>").innerHTML = "EXPIRED";
                                            return;
                                        }
                                        
                                        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
                                        
                                        document.getElementById("countdown-<?= $exam_id ?>").innerHTML = 
                                            hours + "h " + minutes + "m " + seconds + "s";
                                    }
                                    
                                    setInterval(updateCountdown<?= $exam_id ?>, 1000);
                                    updateCountdown<?= $exam_id ?>();
                                </script>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="d-grid">
                                <button class="btn btn-take" disabled>
                                    <i class="fa fa-clock me-2"></i> Not Available Yet
                                </button>
                            </div>
                            
                            <div class="time-indicator mt-3">
                                <span>Starts in:</span>
                                <span class="countdown" id="countdown-upcoming-<?= $exam_id ?>"></span>
                            </div>
                            <script>
                                // Countdown timer for upcoming exams
                                var startTime<?= $exam_id ?> = new Date(<?= $start_ts * 1000 ?>);
                                function updateUpcomingCountdown<?= $exam_id ?>() {
                                    var now = new Date().getTime();
                                    var distance = startTime<?= $exam_id ?> - now;
                                    
                                    if (distance < 0) {
                                        document.getElementById("countdown-upcoming-<?= $exam_id ?>").innerHTML = "AVAILABLE SOON";
                                        return;
                                    }
                                    
                                    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                                    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                                    
                                    var timeString = "";
                                    if (days > 0) timeString += days + "d ";
                                    if (hours > 0 || days > 0) timeString += hours + "h ";
                                    timeString += minutes + "m";
                                    
                                    document.getElementById("countdown-upcoming-<?= $exam_id ?>").innerHTML = timeString;
                                }
                                
                                setInterval(updateUpcomingCountdown<?= $exam_id ?>, 60000);
                                updateUpcomingCountdown<?= $exam_id ?>();
                            </script>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        </div>
    <?php else: ?>
        <div class="empty-state">
            <i class="fas fa-calendar-times"></i>
            <h4 class="text-muted">No exams scheduled</h4>
            <p class="text-muted">You don't have any exams scheduled at the moment.</p>
        </div>
    <?php endif; ?>
</div>

<script>
    // Add subtle animation to cards when page loads
    document.addEventListener('DOMContentLoaded', function() {
        const cards = document.querySelectorAll('.exam-card');
        cards.forEach((card, index) => {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            setTimeout(() => {
                card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, 100 * index);
        });
    });
</script>
</body>
</html>