<?php
/**
 * POST /api/auth/login — JSON login for Clerk PWA (session-based).
 */
$root = defined('NAZARETH_ROOT') ? NAZARETH_ROOT : dirname(__DIR__, 2);
require_once $root . '/config/app.php';
require_once $root . '/includes/session-bootstrap.php';
nazareth_bootstrap_session_cookie();
require_once $root . '/config/database.php';
// Session usually started by index.php before routing to this API
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/auth.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

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

if ($username === '' || $password === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Username and password required']);
    exit;
}

$result = attemptLogin($pdo, $username, $password);
if (!$result['success']) {
    http_response_code(401);
    echo json_encode(['error' => $result['error'] ?? 'Login failed']);
    exit;
}

echo json_encode(['ok' => true]);
