<?php
// ✅ CORS Headers HARUS di paling atas sebelum apapun
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Max-Age: 86400');
header('Content-Type: application/json');

// ✅ Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

session_start();
include 'Connection.php';

// Ambil data dari JSON body
$input = json_decode(file_get_contents('php://input'), true);
$username = $input['username'] ?? '';
$password = $input['password'] ?? '';

if (empty($username) || empty($password)) {
    echo json_encode(["success" => false, "message" => "Username dan password wajib diisi"]);
    exit;
}

$stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Username tidak ditemukan"]);
    $stmt->close();
    $conn->close();
    exit;
}

$stmt->bind_result($hashedPassword);
$stmt->fetch();

if (password_verify($password, $hashedPassword)) {
    $_SESSION['username'] = $username;
    echo json_encode([
        "success" => true, 
        "message" => "Login berhasil",
        "username" => $username,
        "token" => bin2hex(random_bytes(32))
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Password salah"]);
}

$stmt->close();
$conn->close();
?>