<?php
require_once __DIR__ . '/../config.php';

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

$db = get_db();

// Self-seed demo users on first run so there's no manual password-hash
// step to get wrong when setting this up on cPanel.
$count = $db->query('SELECT COUNT(*) AS c FROM users')->fetch()['c'];
if ((int)$count === 0) {
    $hash = password_hash('Medicus2026', PASSWORD_BCRYPT);
    $stmt = $db->prepare('INSERT INTO users (username, password_hash, name, role) VALUES (?, ?, ?, ?)');
    $stmt->execute(['admin', $hash, 'Zahed Rassool', 'admin']);
    $stmt->execute(['user1', $hash, 'User One', 'user']);
}

$input = json_input();
$username = trim($input['username'] ?? '');
$password = (string)($input['password'] ?? '');

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

$stmt = $db->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$username]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
    respond(['error' => 'Invalid username or password'], 401);
}

$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['name'] = $user['name'];
$_SESSION['role'] = $user['role'];

respond([
    'id' => $user['id'],
    'username' => $user['username'],
    'name' => $user['name'],
    'role' => $user['role'],
]);
