<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';

require_method('POST');
$data = read_json();

$email = strtolower(trim((string) ($data['email'] ?? '')));
$password = (string) ($data['password'] ?? '');

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
    json_response(['error' => 'Provide a valid email and password.'], 422);
}

$stmt = db()->prepare(
    'SELECT id, password_hash
     FROM users
     WHERE email = :email
     LIMIT 1'
);
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
    json_response(['error' => 'Incorrect email or password.'], 401);
}

$_SESSION['user_id'] = (int) $user['id'];
$course = active_course();
ensure_enrollment((int) $user['id'], (int) $course['id']);

json_response([
    'user' => current_user(),
    'course' => $course,
]);
