<?php
session_start();
include '../db/koneksi.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    $errors = [];

    if (empty($username)) {
        $errors['username'][] = 'Username wajib diisi.';
    }
    if (empty($password)) {
        $errors['password'][] = 'Password wajib diisi.';
    }

    if (!empty($errors)) {
        http_response_code(422);
        echo json_encode(['errors' => $errors]);
        exit;
    }

    // Cek user di database
    $query = $koneksi->prepare("SELECT * FROM tb_user WHERE username = ? LIMIT 1");
    $query->bind_param("s", $username);
    $query->execute();
    $result = $query->get_result();

    if ($result->num_rows === 0) {
        http_response_code(401);
        echo json_encode(['message' => 'Username tidak ditemukan.']);
        exit;
    }

    $user = $result->fetch_assoc();

    // Verifikasi password
    if (!password_verify($password, $user['password'])) {
        http_response_code(401);
        echo json_encode(['message' => 'Password salah.']);
        exit;
    }

    $_SESSION['id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['extplayer'] = $user['extplayer'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['nomor'] = $user['nomor'];
    $_SESSION['bank'] = $user['bank'];
    $_SESSION['no_rek'] = $user['nomor_rekening'];
    $_SESSION['nama_rek'] = $user['nama_rekening'];

    echo json_encode([
        'success' => true,
        'message' => 'Login berhasil! Mengarahkan...',
        'redirect' => '/'
    ]);
    exit;

} else {
    http_response_code(405);
    echo json_encode(['message' => 'Metode tidak diizinkan.']);
    exit;
}
?>
