<?php
// ... (Header CORS tetap sama) ...
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');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

session_start();
include 'Connection.php';

$input = json_decode(file_get_contents('php://input'), true);
$username = $input['username'] ?? '';
$password = $input['password'] ?? '';

// ... (Validasi input kosong tetap sama) ...

// 🔴 PERBAIKAN 1: Tambahkan 'id' di dalam SELECT
$stmt = $conn->prepare("SELECT id, 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 Not Found"]);
    $stmt->close();
    $conn->close();
    exit;
}

// 🔴 PERBAIKAN 2: Bind result untuk menangkap 'id' dan 'password'
$stmt->bind_result($userId, $hashedPassword);
$stmt->fetch();

if (password_verify($password, $hashedPassword)) {
    // 🔴 PERBAIKAN 3: Simpan 'user_id' ke dalam SESSION
    $_SESSION['user_id'] = $userId;
    $_SESSION['username'] = $username;
    
    echo json_encode([
        "success" => true, 
        "message" => "Login successful",
        "username" => $username,
        "token" => bin2hex(random_bytes(32))
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Incorrect password"]);
}

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