<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require_once "config/database.php";

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

$username = $input["username"] ?? "";
$password = $input["password"] ?? "";

if ($username === "" || $password === "") {

    echo json_encode([
        "success" => false,
        "message" => "Username dan password wajib diisi",
        "data" => null
    ]);

    exit;
}

$stmt = $conn->prepare(
    "SELECT id, username, password, role 
     FROM users 
     WHERE username = ? 
     LIMIT 1"
);

$stmt->bind_param("s", $username);

$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows === 0) {

    echo json_encode([
        "success" => false,
        "message" => "Username tidak ditemukan",
        "data" => null
    ]);

    exit;
}

$userData = $result->fetch_assoc();

if ($password !== $userData["password"]) {

    echo json_encode([
        "success" => false,
        "message" => "Password salah",
        "data" => null
    ]);

    exit;
}

$token = bin2hex(random_bytes(32));

echo json_encode([
    "success" => true,
    "message" => "Login berhasil",
    "data" => [
        "id" => $userData["id"],
        "username" => $userData["username"],
        "role" => $userData["role"],
        "token" => $token
    ]
]);

$conn->close();