Path : /home/vishqocm/pcib.in/student/
File Upload :
Current File : //home/vishqocm/pcib.in/student/exam_details.php

<?php
// Add timezone conversion functions at the top of the file
function get_user_timezone() {
    // Default to IST (Indian Standard Time)
    return 'Asia/Kolkata';
}

function convert_to_user_timezone($datetime_str, $format = 'Y-m-d H:i:s') {
    // This is a simplified version that just returns the time in IST format
    // since we're defaulting to IST timezone
    return date($format, strtotime($datetime_str));
}

$pageTitle = "Exam Details";
include_once('includes/header.php');
require_once('../includes/functions.php');

// Check if exam ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No exam ID provided.";
    header("Location: scheduled-exams.php");
    exit();
}

$exam_id = intval($_GET['id']);
$student_id = $_SESSION['user_id'];

// Get current date
$current_date = date('Y-m-d');

// Get exam details
$exam_query = "
    SELECT es.*, c.title as course_title, c.image as course_image, c.description as course_description,
           CONCAT(i.first_name, ' ', i.last_name) as instructor_name, i.profile_image as instructor_image,
           (SELECT COUNT(*) FROM student_exams se WHERE se.user_id = ? AND se.exam_id = es.id) as attempt_count,
           (SELECT COUNT(*) FROM exam_questions eq WHERE eq.exam_id = es.id) as question_count
    FROM exam_schedules es
    JOIN courses c ON es.course_id = c.id
    LEFT JOIN users i ON c.instructor_id = i.id
    JOIN enrollments e ON e.course_id = c.id AND e.user_id = ?
    WHERE es.id = ? AND e.status = 'completed'
";

$stmt = $conn->prepare($exam_query);
$stmt->bind_param("iii", $student_id, $student_id, $exam_id);
$stmt->execute();
$result = $stmt->get_result();

// Check if exam exists and is accessible to this student
if ($result->num_rows == 0) {
    $_SESSION['error_message'] = "Exam not found or not accessible.";
    header("Location: scheduled-exams.php");
    exit();
}

$exam = $result->fetch_assoc();

// Get previous attempts
$attempts_query = "
    SELECT se.*, DATE_FORMAT(se.attempt_date, '%d %b %Y, %h:%i %p') as formatted_date
    FROM student_exams se
    WHERE se.user_id = ? AND se.exam_id = ?
    ORDER BY se.attempt_date DESC
";

$stmt = $conn->prepare($attempts_query);
$stmt->bind_param("ii", $student_id, $exam_id);
$stmt->execute();
$attempts = $stmt->get_result();

// Calculate exam time status
$exam_datetime = $exam['exam_date'] . ' ' . $exam['start_time'];
$end_datetime = date('Y-m-d H:i:s', strtotime($exam['exam_date'] . ' ' . $exam['end_time']));
$current_datetime = date('Y-m-d H:i:s');

// For display purposes, we'll use the user's timezone
$user_exam_datetime = convert_to_user_timezone($exam_datetime, 'Y-m-d H:i:s');
$user_end_datetime = convert_to_user_timezone($end_datetime, 'Y-m-d H:i:s');

$time_status = 'upcoming';
$can_take_exam = false;
$time_message = '';

// The business logic should still use server time (IST) for determining status
if ($current_datetime < $exam_datetime) {
    $time_status = 'upcoming';
    $time_message = 'Exam has not started yet';
} else if ($current_datetime <= $end_datetime) {
    $time_status = 'in_progress';
    $can_take_exam = true;
    $time_message = 'Exam is currently in progress';
} else {
    $time_status = 'ended';
    $time_message = 'Exam has ended';
    
    // Check if late attempts are allowed
    if ($exam['allow_late_attempts']) {
        $can_take_exam = true;
        $time_message .= ', but late attempts are allowed';
    }
}

// Check attempt limits
if ($exam['attempt_count'] >= $exam['attempts_allowed'] && $exam['attempts_allowed'] > 0) {
    $can_take_exam = false;
    $time_message = 'Maximum attempts reached (' . $exam['attempt_count'] . '/' . $exam['attempts_allowed'] . ')';
}
?>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Exam Details</h2>
        <a href="scheduled-exams.php" class="btn btn-outline-primary">
            <i class="fas fa-arrow-left me-2"></i>Back to Exams
        </a>
    </div>
    
    <?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i> <?php echo $_SESSION['success_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['success_message']); endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $_SESSION['error_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['error_message']); endif; ?>

    <!-- Exam Details -->
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-clipboard-list me-2"></i><?php echo htmlspecialchars($exam['title']); ?></h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-4">
                        <h4>About This Exam</h4>
                        <p><?php echo htmlspecialchars($exam['description'] ?? 'No description available.'); ?></p>
                    </div>
                    
                    <div class="mb-4">
                        <h5>Exam Details</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-calendar-day me-2"></i>Date:</span>
                                        <span class="fw-bold"><?php echo date('d M Y', strtotime($exam['exam_date'])); ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-clock me-2"></i>Time:</span>
                                        <span class="fw-bold">
                                            <?php 
                                            // Show both IST and user local time
                                            $ist_start = date('h:i A', strtotime($exam['start_time']));
                                            $ist_end = date('h:i A', strtotime($exam['end_time']));
                                            
                                            // Convert to user timezone
                                            $user_start = convert_to_user_timezone($exam['exam_date'] . ' ' . $exam['start_time'], 'h:i A');
                                            $user_end = convert_to_user_timezone($exam['exam_date'] . ' ' . $exam['end_time'], 'h:i A');
                                            $user_tz = get_user_timezone();
                                            
                                            echo "$ist_start - $ist_end (IST)";
                                            
                                            if ($user_tz != 'Asia/Kolkata') {
                                                echo "<br>" . $user_start . " - " . $user_end . " (Your local time)";
                                            }
                                            ?>
                                        </span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-hourglass-half me-2"></i>Duration:</span>
                                        <span class="fw-bold"><?php echo $exam['duration_minutes']; ?> minutes</span>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-question-circle me-2"></i>Questions:</span>
                                        <span class="fw-bold"><?php echo $exam['question_count']; ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-percentage me-2"></i>Pass Percentage:</span>
                                        <span class="fw-bold"><?php echo $exam['passing_percentage']; ?>%</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span><i class="fas fa-redo me-2"></i>Attempts Allowed:</span>
                                        <span class="fw-bold"><?php echo $exam['attempts_allowed'] ? $exam['attempts_allowed'] : 'Unlimited'; ?></span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Attempts History -->
                    <?php if ($attempts->num_rows > 0): ?>
                    <div class="mb-4">
                        <h5>Your Previous Attempts</h5>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>#</th>
                                        <th>Date & Time</th>
                                        <th>Score</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $attempt_number = 1; while ($attempt = $attempts->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo $attempt_number++; ?></td>
                                        <td><?php echo $attempt['formatted_date']; ?></td>
                                        <td><?php echo $attempt['percentage']; ?>%</td>
                                        <td>
                                            <?php if ($attempt['status'] == 'passed'): ?>
                                                <span class="badge bg-success">Passed</span>
                                            <?php elseif ($attempt['status'] == 'failed'): ?>
                                                <span class="badge bg-danger">Failed</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary"><?php echo ucfirst($attempt['status']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="exam-results.php?id=<?php echo $exam_id; ?>" class="btn btn-sm btn-primary">
                                                <i class="fas fa-eye me-1"></i> View Results
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-4">
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Course Information</h5>
                        </div>
                        <div class="card-body">
                            <div class="text-center mb-3">
                                <?php if (!empty($exam['course_image'])): ?>
                                    <img src="../<?php echo htmlspecialchars($exam['course_image']); ?>" alt="Course Image" class="img-fluid rounded mb-2" style="max-height: 150px;">
                                <?php else: ?>
                                    <div class="bg-light rounded d-flex align-items-center justify-content-center mb-2" style="height: 150px;">
                                        <i class="fas fa-book fa-4x text-primary"></i>
                                    </div>
                                <?php endif; ?>
                                <h6><?php echo htmlspecialchars($exam['course_title']); ?></h6>
                            </div>
                            
                            <div class="d-flex align-items-center mb-3">
                                <?php if (!empty($exam['instructor_image'])): ?>
                                    <img src="../<?php echo htmlspecialchars($exam['instructor_image']); ?>" alt="Instructor" class="rounded-circle me-2" style="width: 40px; height: 40px; object-fit: cover;">
                                <?php else: ?>
                                    <div class="bg-light rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                                        <i class="fas fa-user text-primary"></i>
                                    </div>
                                <?php endif; ?>
                                <div>
                                    <p class="mb-0 small">Instructor</p>
                                    <p class="mb-0 fw-bold"><?php echo htmlspecialchars($exam['instructor_name']); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header <?php echo $time_status == 'in_progress' ? 'bg-success' : ($time_status == 'upcoming' ? 'bg-warning' : 'bg-secondary'); ?> text-white">
                            <h5 class="mb-0">
                                <?php echo $time_status == 'in_progress' ? 'Exam In Progress' : ($time_status == 'upcoming' ? 'Upcoming Exam' : 'Exam Ended'); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <p class="mb-3"><?php echo $time_message; ?></p>
                            
                            <div class="d-grid gap-2">
                                <?php if ($can_take_exam): ?>
                                    <a href="take_exam.php?id=<?php echo $exam_id; ?>" class="btn btn-primary">
                                        <i class="fas fa-edit me-1"></i> Start Exam
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary" disabled>
                                        <i class="fas fa-edit me-1"></i> Start Exam
                                    </button>
                                <?php endif; ?>
                                
                                <?php if ($attempts->num_rows > 0): ?>
                                    <a href="exam-results.php?id=<?php echo $exam_id; ?>" class="btn btn-outline-primary">
                                        <i class="fas fa-chart-bar me-1"></i> View Results
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php if ($time_status == 'upcoming'): ?>
                        <div class="card-footer bg-light">
                            <div class="small">
                                <p class="mb-1"><strong>Starts in:</strong></p>
                                <p class="mb-0 text-primary fw-bold" id="countdown">Calculating...</p>
                            </div>
                            <script>
                                // Add countdown timer script
                                document.addEventListener('DOMContentLoaded', function() {
                                    <?php
                                    // Convert exam datetime to user's timezone
                                    $user_exam_datetime = convert_to_user_timezone($exam_datetime, 'Y-m-d H:i:s');
                                    ?>
                                    const examDate = new Date('<?php echo $user_exam_datetime; ?>');
                                    const countdownEl = document.getElementById('countdown');
                                    let hasReloaded = false;
                                    
                                    function updateCountdown() {
                                        const now = new Date();
                                        const diff = examDate - now;
                                        
                                        if (diff <= 0) {
                                            countdownEl.innerHTML = 'Exam has started!';
                                            
                                            // Only reload once when exam starts
                                            if (!hasReloaded) {
                                                hasReloaded = true;
                                                // Use sessionStorage to prevent infinite reloads
                                                if (!sessionStorage.getItem('examStartReloaded_<?php echo $exam_id; ?>')) {
                                                    sessionStorage.setItem('examStartReloaded_<?php echo $exam_id; ?>', 'true');
                                                    setTimeout(function() {
                                                        location.reload();
                                                    }, 2000);
                                                }
                                            }
                                            return;
                                        }
                                        
                                        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                                        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                                        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                                        const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                                        
                                        countdownEl.innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
                                    }
                                    
                                    // Clear the reload flag when we're showing countdown again
                                    if (examDate > new Date()) {
                                        sessionStorage.removeItem('examStartReloaded_<?php echo $exam_id; ?>');
                                    }
                                    
                                    updateCountdown();
                                    setInterval(updateCountdown, 1000);
                                });
                            </script>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include_once('includes/footer.php'); ?>