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

$response = [
    'available' => false,
    'message' => 'Permintaan tidak valid.'
];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode($response);
    exit;
}

if (isset($_POST['username'])) {
    $username = trim($_POST['username']);

    if (empty($username)) {
        $response['message'] = 'Username tidak boleh kosong.';
        echo json_encode($response);
        exit;
    }

    $query = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE username = '$username'");
    if (mysqli_num_rows($query) > 0) {
        $response['available'] = false;
        $response['message'] = 'Username sudah digunakan.';
    } else {
        $response['available'] = true;
        $response['message'] = 'Username tersedia.';
    }

    echo json_encode($response);
    exit;
}

if (isset($_POST['email'])) {
    $email = trim($_POST['email']);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response['message'] = 'Format email tidak valid.';
        echo json_encode($response);
        exit;
    }

    $query = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE email = '$email'");
    if (mysqli_num_rows($query) > 0) {
        $response['available'] = false;
        $response['message'] = 'Email sudah digunakan.';
    } else {
        $response['available'] = true;
        $response['message'] = 'Email tersedia.';
    }

    echo json_encode($response);
    exit;
}

if (isset($_POST['phone'])) {
    $phone = preg_replace('/\D/', '', $_POST['phone']);
    if (strlen($phone) < 9) {
        $response['message'] = 'Nomor handphone terlalu pendek.';
        echo json_encode($response);
        exit;
    }

    $query = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE nomor = '$phone'");
    if (mysqli_num_rows($query) > 0) {
        $response['available'] = false;
        $response['message'] = 'Nomor handphone sudah digunakan.';
    } else {
        $response['available'] = true;
        $response['message'] = 'Nomor handphone tersedia.';
    }

    echo json_encode($response);
    exit;
}

// Cek Nomor Rekening
if (isset($_POST['bank_account_number']) && isset($_POST['bank_name'])) {
    $rekening = trim($_POST['bank_account_number']);
    $bank = trim($_POST['bank_name']);

    if (empty($rekening) || empty($bank)) {
        $response['message'] = 'Bank dan nomor rekening wajib diisi.';
        echo json_encode($response);
        exit;
    }

    $query = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE nomor_rekening = '$rekening' AND bank = '$bank'");
    if (mysqli_num_rows($query) > 0) {
        $response['available'] = false;
        $response['message'] = 'Nomor rekening sudah terdaftar.';
    } else {
        $response['available'] = true;
        $response['message'] = 'Nomor rekening tersedia.';
    }

    echo json_encode($response);
    exit;
}

echo json_encode($response);
exit;
?>
