<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once "../config.php";

header("Content-Type: application/json");

// Read JSON input
$raw = file_get_contents("php://input");
$input = json_decode($raw, true);

if (!$input || empty($input['username']) || empty($input['password'])) {
    echo json_encode(["status" => "error", "message" => "Missing username or password."]);
    exit;
}

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

// Fetch user (SQLite uses PDO)
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
    exit;
}

if (!password_verify($password, $user['password_hash'])) {
    echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
    exit;
}

// Set session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['is_admin'] = $user['is_admin'];

echo json_encode([
    "status" => "success",
    "redirect" => "/desktop.php"
]);
exit;
?>