<?php
declare(strict_types=1);
require_once __DIR__ . '/helpers.php';
require_post();

$username = get_post('username');
$password = get_post('password');

$conn = db();
$stmt = $conn->prepare('SELECT id, full_name, username, password_hash, role, created_at FROM users WHERE username = ? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

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

log_activity((int)$user['id'], 'LOGIN', 'User logged in');
unset($user['password_hash']);
respond(['success' => true, 'message' => 'Login successful', 'user' => $user]);
