<?php
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();              // Mulai session (login state)
include 'Connection.php';     // Koneksi database

// Ambil Data Login dari Client
$input = json_decode(file_get_contents('php://input'), true); // Ambil body JSON
$username = $input['username'] ?? ''; // Username dari client
$password = $input['password'] ?? ''; // Password dari client

// Cek Username di Database
$stmt = $conn->prepare(
    "SELECT id, password FROM users WHERE username = ?"
);                          
$stmt->bind_param("s", $username);
$stmt->execute();                 
$stmt->store_result();           

// Jika Username Tidak Ada
if ($stmt->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "message" => "Username Not Found"
    ]);
    $stmt->close();
    $conn->close();
    exit;
}

// Ambil Data User
$stmt->bind_result($userId, $hashedPassword); // Ambil id & password hash
$stmt->fetch();

// Cek Password
if (password_verify($password, $hashedPassword)) {

    // Simpan data login ke session
    $_SESSION['user_id'] = $userId;
    $_SESSION['username'] = $username;

    // Kirim respon login sukses
    echo json_encode([
        "success" => true,
        "message" => "Login successful",
        "username" => $username,
        "token" => bin2hex(random_bytes(32)) // Token acak (bukan JWT)
    ]);

} else {

    // Password salah
    echo json_encode([
        "success" => false,
        "message" => "Incorrect password"
    ]);
}

$stmt->close(); // Tutup statement
$conn->close(); // Tutup koneksi DB
?>
