<?php
require __DIR__ . '/db.php';
session_start();

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

$email = trim($_POST['email'] ?? '');
$pass  = $_POST['password'] ?? '';

$stmt = $pdo->prepare("SELECT * FROM students WHERE email = ? LIMIT 1");
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user && password_verify($pass, $user['password_hash'])) {
    // Save student in session
    $_SESSION['student'] = [
        'id'    => $user['id'],
        'email' => $user['email'],
        'name'  => $user['first_name'] . ' ' . $user['last_name']
    ];

    // Redirect to dashboard
    header("Location: student_dashboard.php");
    exit;
}

// If failed
header("Location: index.php?e=" . urlencode("Invalid email or password"));
exit;
