<?php
session_start();
require_once __DIR__ . '/inc/connect.php';

// Handle login if it's a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $response = ['success' => false, 'message' => 'Invalid request.'];
    header('Content-Type: application/json');

    $token = trim($_POST['token'] ?? '');
    $school_id = trim($_POST['student_id'] ?? '');

    if (!$token || !$school_id) {
        $response['message'] = "Please enter your token and school ID.";
        echo json_encode($response);
        exit;
    }

    // Get student using alphanumeric school_id
    $student_stmt = $mysqli->prepare("SELECT * FROM student_table WHERE school_id = ? AND status = 'active' LIMIT 1");
    $student_stmt->bind_param('s', $school_id);
    $student_stmt->execute();
    $student_result = $student_stmt->get_result();
    $student = $student_result->fetch_assoc();

    if (!$student) {
        $response['message'] = "Invalid or inactive School ID.";
        echo json_encode($response);
        exit;
    }

    $student_serial = $student['serial'];
	
	
	// AND status = 'unused'

    // Validate token against this student
    $stmt = $mysqli->prepare("SELECT * FROM token_management WHERE token_id = ? AND student_id = ? LIMIT 1");
    $stmt->bind_param('si', $token, $student_serial);
    $stmt->execute();
    $result = $stmt->get_result();
	
	
	
	

    if ($row = $result->fetch_assoc()) {
        // Mark token used
        $update = $mysqli->prepare("UPDATE token_management SET status = 'used', login_time = NOW(), last_activity = NOW() WHERE serial = ?");
        $update->bind_param('i', $row['serial']);
        $update->execute();

        $_SESSION['role'] = 'student';
        $_SESSION['student_id'] = $student_serial;
        $_SESSION['student_name'] = $student['surname'] . ' ' . $student['lastname'];
        $_SESSION['token'] = $token;
        $_SESSION['token_id'] = $token;
        $_SESSION['exam_id'] = $row['examination_id'];

        echo json_encode(['success' => true, 'redirect' => 'exam.php']);
        exit;
    } else {
        $response['message'] = "Invalid or used token.";
    }

    echo json_encode($response);
    exit;
}
?>

<!-- HTML below for student token login -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Application Login | Exam System</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
</head>
<body class="hold-transition login-page">

<div class="login-box">
  <div class="login-logo"><b>Examination</b> Login</div>
  <div class="card">
    <div class="card-body login-card-body">
      <p class="login-box-msg">Enter your token and School ID</p>

      <div id="alert-box"></div>

      <form id="loginForm">
        <div class="input-group mb-3">
          <input type="text" name="student_id" class="form-control" placeholder="School ID (e.g., SCH/2025/001)" required>
          <div class="input-group-append"><div class="input-group-text"><span class="fas fa-id-card"></span></div></div>
        </div>
        <div class="input-group mb-3">
          <input type="text" name="token" class="form-control" placeholder="Token" required>
          <div class="input-group-append"><div class="input-group-text"><span class="fas fa-key"></span></div></div>
        </div>
        <div class="row">
          <div class="col-12"><button type="submit" class="btn btn-primary btn-block">Login</button></div>
        </div>
      </form>

    </div>
  </div>
</div>

<script>
document.getElementById('loginForm').addEventListener('submit', async function (e) {
  e.preventDefault();
  const form = e.target;
  const formData = new FormData(form);
  const alertBox = document.getElementById('alert-box');

  // Show processing sign
  alertBox.innerHTML = `<div class="alert alert-info">Processing login...</div>`;

  try {
    const response = await fetch('index.php', {
      method: 'POST',
      body: formData
    });

    const result = await response.json();

    if (result.success) {
      alertBox.innerHTML = `<div class="alert alert-success">Login successful. Redirecting...</div>`;
      setTimeout(() => {
        window.location.href = result.redirect;
      }, 1000);
    } else {
      alertBox.innerHTML = `<div class="alert alert-danger">${result.message}</div>`;
    }
  } catch (error) {
    alertBox.innerHTML = `<div class="alert alert-danger">Network error. Please try again.</div>`;
  }

  // Fade out alert after 6 seconds
  setTimeout(() => {
    alertBox.innerHTML = '';
  }, 6000);
});
</script>


<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>
</body>
</html>
