<?php
// Izinkan aplikasi dari luar mengakses file ini (CORS)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

// Matikan error HTML sementara agar tidak merusak format JSON jika ada peringatan kecil
error_reporting(0); 

require_once '../config/database.php';

// Tangkap data yang dikirim dari Aplikasi HP (JSON Format)
$data = json_decode(file_get_contents("php://input"));

if (!empty($data->username) && !empty($data->password)) {
    
    $stmt = $pdo->prepare("SELECT id, username, password, role FROM users WHERE username = ?");
    $stmt->execute([$data->username]);
    $user = $stmt->fetch();

    // RUMUS CEK PASSWORD GANDA (Teks Biasa ATAU Hash)
    $is_password_valid = false;
    
    if ($user) {
        if ($data->password === $user['password']) {
            $is_password_valid = true; // Lolos jika pakai teks biasa
        } elseif (password_verify($data->password, $user['password'])) {
            $is_password_valid = true; // Lolos jika pakai sistem keamanan Hash
        }
    }

    if ($is_password_valid) {
        // Jika login sukses
        echo json_encode([
            "status" => "success",
            "message" => "Login Berhasil",
            "data" => [
                "user_id" => $user['id'],
                "username" => $user['username'],
                "role" => $user['role']
            ]
        ]);
    } else {
        // Jika password salah
        http_response_code(401);
        echo json_encode(["status" => "error", "message" => "Username atau Password salah!"]);
    }
} else {
    // Jika ada form yang kosong
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Data tidak lengkap!"]);
}
?>