<?php
require_once "../config.php";

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

// session already started in config.php

$data = json_decode(file_get_contents("php://input"), true);

$email    = trim($data["email"] ?? "");
$password = trim($data["password"] ?? "");

if ($email === "" || $password === "") {
    echo json_encode([
        "success" => false,
        "error"   => "MISSING_FIELDS"
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| MATCH login_process.php EXACTLY
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT id, email, password_hash, status
    FROM fxh_users
    WHERE email = ?
    LIMIT 1
");

$stmt->bind_param("s", $email);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "error"   => "INVALID_CREDENTIALS"
    ]);
    exit;
}

$user = $res->fetch_assoc();

if (!password_verify($password, $user["password_hash"])) {
    echo json_encode([
        "success" => false,
        "error"   => "INVALID_CREDENTIALS"
    ]);
    exit;
}

if ($user["status"] !== "active") {
    echo json_encode([
        "success" => false,
        "error"   => "ACCOUNT_DISABLED"
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| DESKTOP SESSION TOKEN
|--------------------------------------------------------------------------
*/
$token = bin2hex(random_bytes(32));

$_SESSION["fxh_desktop_token"] = $token;
$_SESSION["fxh_desktop_user"]  = (int)$user["id"];
$_SESSION["email"] = $user["email"];


echo json_encode([
    "success" => true,
    "token"   => $token,
    "user"    => [
        "id"    => (int)$user["id"],
        "email" => $user["email"]
    ]
]);
exit;
