<?php
require_once __DIR__ . '/inc/bootstrap.php';
include 'config.php';   // DB connection


$user  = current_user();
$flash = flash_get();
$error = null;   // ✅ Initialize error variable

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$user) { 
        header('Location: login.php'); 
        exit; 
    }

    try { 
        [$questions, $has_correct] = load_questions_from_file(DATA_PATH); 
    } catch (Exception $e) { 
        $error = $e->getMessage(); 
    }

    if (empty($error)) {
        $_SESSION['questions']  = $questions; 
        $_SESSION['has_correct'] = $has_correct; 
        $_SESSION['responses']  = []; 
        $_SESSION['started_at'] = date('c');

        $cfg  = read_config(); 
        $mins = max(1, intval($cfg['duration_minutes'] ?? 15)); 
        $_SESSION['exam_end_ts'] = time() + ($mins * 60);

        header('Location: question.php?q=1'); 
        exit;
    }
}
?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Exam Portal (PHP)</title>
  <link rel="stylesheet" href="assets/style.css">
</head>

<body>
  <nav class="nav">
    <div class="container">
      <div class="brand">📝 Exam Portal (PHP)</div>
      <div>
        <?php if($user): ?>
          <span>Hi, <?=htmlspecialchars($user['name'])?> (<?=htmlspecialchars($user['role'])?>)</span>
          <?php if($user['role'] === 'admin'): ?>
            | <a href="admin.php">Admin</a>
          <?php endif; ?>
          | <a href="logout.php">Logout</a>
        <?php else: ?>
          <a href="login.php">Login</a> | <a href="register.php">Register</a>
        <?php endif; ?>
      </div>
    </div>
  </nav>

  <main class="container">
    <?php if(!empty($flash)): ?>
    <div class="flash">
      <div class="flash-item"><?=htmlspecialchars($flash)?></div>
    </div>
    <?php endif; ?>

    <?php if(!empty($error)): ?>
    <section class="card">
      <h2>Oops!</h2>
      <p><?=htmlspecialchars($error)?></p>
    </section>
    <?php endif; ?>

    <section class="card">
      <h1>Start Exam</h1>
      <p>Questions are loaded from <code>data/questions.xlsx</code> (or <code>.csv</code>). Login required.</p>

      <?php if($user): ?>
        <form method="post">
          <button class="primary" type="submit">Start</button>
        </form>
      <?php else: ?>
        <p>Please <a href="login.php">login</a> or <a href="register.php">register</a> to take the exam.</p>
      <?php endif; ?>
    </section>
  </main>

  <footer class="footer">
    <div class="container">&nbsp;</div>
  </footer>
</body>
</html>
