<?php
require_once __DIR__ . '/../includes/auth.php';
send_cors_headers();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['error' => 'Method not allowed'], 405);
}

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$username = trim($body['username'] ?? '');
$password = (string) ($body['password'] ?? '');

if ($username === '' || $password === '') {
    json_response(['error' => 'Username and password are required'], 400);
}

try {
    $token = attempt_login($username, $password);
} catch (Throwable $e) {
    json_response(['error' => 'Server error — check your MySQL connection in config.php'], 500);
}

if (!$token) {
    json_response(['error' => 'Invalid username or password'], 401);
}

json_response(['token' => $token]);
