<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include("config.php");

// ✅ Force MySQL to use Asia/Kolkata timezone
$conn->query("SET time_zone = '+05:30'");

// ✅ Set PHP timezone also
date_default_timezone_set('Asia/Kolkata');

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

// ✅ Only allow students
if ($_SESSION['user']['role'] !== 'student') {
    header("Location: admin_dashboard.php");
    exit();
}

$user_id = $_SESSION['user']['id'];

// Fetch user info securely
$stmt = $conn->prepare("SELECT id, name, email, role FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// ✅ Handle "Start Exam"
if (isset($_POST['start_exam'])) {
    $exam_id = (int)$_POST['exam_id'];

    // Get exam details
    $stmt = $conn->prepare("SELECT id, title, duration_minutes FROM exams WHERE id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $exam = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($exam) {
        // ❌ Delete any unfinished attempts for same exam
        $stmt = $conn->prepare("DELETE FROM attempts WHERE user_id = ? AND exam_id = ? AND completed_at IS NULL");
        $stmt->bind_param("ii", $user_id, $exam_id);
        $stmt->execute();
        $stmt->close();

        // ✅ Insert attempt (DB handles IST because of SET time_zone)
        $stmt = $conn->prepare("
            INSERT INTO attempts (user_id, exam_id, started_at, end_at)
            VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ? MINUTE))
        ");
        $stmt->bind_param("iii", $user_id, $exam_id, $exam['duration_minutes']);
        $stmt->execute();
        $attempt_id = $stmt->insert_id;
        $stmt->close();

        // ✅ Fetch back DB times for session timer
        $stmt = $conn->prepare("SELECT started_at, end_at FROM attempts WHERE id = ?");
        $stmt->bind_param("i", $attempt_id);
        $stmt->execute();
        $attempt = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // Store in session
        $_SESSION['exam_id'] = $exam_id;
        $_SESSION['attempt_id'] = $attempt_id;
        $_SESSION['exam_start_ts'] = strtotime($attempt['started_at']);
        $_SESSION['exam_end_ts'] = strtotime($attempt['end_at']);

        // Redirect to exam page
        header("Location: question.php?id=" . $exam_id);
        exit();
    }
}

// ✅ Fetch previous completed exams
$prevExams = $conn->prepare("
    SELECT e.title, a.score, a.total, a.started_at, a.end_at, a.completed_at
    FROM attempts a
    JOIN exams e ON a.exam_id = e.id
    WHERE a.user_id = ? AND a.completed_at IS NOT NULL
    ORDER BY a.completed_at DESC
");
$prevExams->bind_param("i", $user_id);
$prevExams->execute();
$prevResults = $prevExams->get_result();
$prevExams->close();

// ✅ Fetch available exams
$examList = $conn->query("SELECT id, title, duration_minutes FROM exams WHERE is_active = 1");
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Student Profile</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .container {
            width: 80%;
            margin: 30px auto;
        }

        .card {
            background: #fff;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        h2,
        h3 {
            color: #333;
        }

        .exam-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .exam-item:last-child {
            border: none;
        }

        .logout-btn {
            display: inline-block;
            padding: 10px 20px;
            background: #e74c3c;
            color: #fff;
            border-radius: 8px;
            text-decoration: none;
            margin-top: 10px;
        }

        .logout-btn:hover {
            background: #c0392b;
        }

        .start-btn {
            padding: 8px 16px;
            background: #3498db;
            color: #fff;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }

        .start-btn:hover {
            background: #2980b9;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- Profile Card -->
        <div class="card">
            <h2>Welcome,
                <?= htmlspecialchars($user['name']) ?> 👋
            </h2>
            <p><b>Email:</b>
                <?= htmlspecialchars($user['email']) ?>
            </p>
            <a href="logout.php" class="logout-btn">Logout</a>
        </div>

        <!-- Available Exams -->
        <div class="card">
            <h3>📝 Available Exams</h3>
            <?php if ($examList->num_rows > 0): ?>
            <?php while($exam = $examList->fetch_assoc()): ?>
            <div class="exam-item">
                <b><?= htmlspecialchars($exam['title']) ?></b><br>
                Duration: <?= $exam['duration_minutes'] ?> minutes
                <form method="post" style="margin-top: 10px;">
                    <input type="hidden" name="exam_id" value="<?= $exam['id'] ?>">
                    <button type="submit" name="start_exam" class="start-btn">Start Exam</button>
                </form>
            </div>
            <?php endwhile; ?>
            <?php else: ?>
            <p>No exams available right now.</p>
            <?php endif; ?>
        </div>

        <!-- Previous Exams -->
        <div class="card">
            <h3>📘 Previous Exams</h3>
            <?php if ($prevResults->num_rows > 0): ?>
            <?php while($row = $prevResults->fetch_assoc()): ?>
            <div class="exam-item">
                <b><?= htmlspecialchars($row['title']) ?></b><br>
                Score: <?= $row['score']." / ".$row['total'] ?><br>
                Started: <?= date('d-m-Y H:i:s', strtotime($row['started_at'])) ?><br>
                End (Deadline): <?= date('d-m-Y H:i:s', strtotime($row['end_at'])) ?><br>
                Completed On: <?= date('d-m-Y H:i:s', strtotime($row['completed_at'])) ?>
            </div>
            <?php endwhile; ?>
            <?php else: ?>
            <p>No exams taken yet.</p>
            <?php endif; ?>
        </div>

    </div>
</body>
</html>
