<?php
session_start();
include '../db/koneksi.php';
include '../api/nexus.php';
include '../api/sgx.php';

header('Content-Type: application/json');

$response = [
    'success' => false,
    'message' => '',
    'errors' => []
];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode tidak diizinkan.';
    echo json_encode($response);
    exit;
}

function getUserIP() {
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : 'Unknown';
}

$user_ip = getUserIP();

$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');
$password_confirm = trim($_POST['password_confirm'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$bank_name= trim($_POST['bank_name'] ?? '');
$bank_account_number = trim($_POST['bank_account_number'] ?? '');
$bank_account_name = trim($_POST['bank_account_name'] ?? '');
$reffallea = isset($_POST['reffallea']) ? trim($_POST['reffallea']) : '';
$captcha_input = trim($_POST['captcha'] ?? '');

if ($captcha_input != ($_SESSION['captcha_code'] ?? '')) {
    http_response_code(422);
    $response['errors']['captcha'][] = 'Kode verifikasi salah.';
    echo json_encode($response);
    exit;
}

if (empty($username)) $response['errors']['username'][] = 'Username wajib diisi.';
if (empty($password)) $response['errors']['password'][] = 'Password wajib diisi.';
if (empty($password_confirm)) $response['errors']['password_confirm'][] = 'Konfirmasi password wajib diisi.';
if (empty($email)) $response['errors']['email'][] = 'Email wajib diisi.';
if (empty($phone)) $response['errors']['phone'][] = 'Nomor HP wajib diisi.';
if (empty($bank_name)) $response['errors']['bank_name'][] = 'Nama bank wajib diisi.';
if (empty($bank_account_number)) $response['errors']['bank_account_number'][] = 'Nomor rekening wajib diisi.';
if (empty($bank_account_name)) $response['errors']['bank_account_name'][] = 'Nama rekening wajib diisi.';

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

if ($password !== $password_confirm) {
    http_response_code(422);
    $response['errors']['password_confirm'][] = 'Konfirmasi password tidak cocok.';
    echo json_encode($response);
    exit;
}

$stmt = $koneksi->prepare("SELECT username FROM tb_user WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    http_response_code(422);
    $response['errors']['username'][] = 'Username sudah terdaftar.';
    echo json_encode($response);
    exit;
}
$stmt->close();

$referral = '';
if (!empty($reffallea)) {
    $stmt = $koneksi->prepare("SELECT username FROM tb_user WHERE username = ?");
    $stmt->bind_param("s", $reffallea);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        $referral = $reffallea;
    } else {
        $response['errors']['referral_username'][] = 'Referral tidak ditemukan.';
        http_response_code(422);
        echo json_encode($response);
        exit;
    }
    $stmt->close();
}

$hashed_password = password_hash($password, PASSWORD_BCRYPT);

$extplayer = "uvgaming" . strtoupper(bin2hex(random_bytes(3)));
$user_saldo = 0;
$stmt = $koneksi->prepare("
    INSERT INTO tb_user 
    (extplayer, username, password, email, ip, saldo, nomor, bank, nomor_rekening, nama_rekening, referral)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$stmt->bind_param(
    "ssssissssss",
    $extplayer,
    $username,
    $hashed_password,
    $email,
    $user_ip,
    $user_saldo,
    $phone,
    $bank_name,
    $bank_account_number,
    $bank_account_name,
    $referral
);

$nx->create_member($extplayer);
$SGX->create_member($extplayer);

if ($stmt->execute()) {
    $_SESSION['id'] = $stmt->insert_id;
    $_SESSION['username'] = $username;
    $_SESSION['extplayer'] = $extplayer;
    $_SESSION['email'] = $email;
    $_SESSION['nomor']= $phone;
    $_SESSION['bank'] = $bank_name;
    $_SESSION['no_rek'] = $bank_account_number;
    $_SESSION['nama_rek']= $bank_account_name;

    $response['success'] = true;
    $response['message'] = 'Registrasi berhasil! Selamat datang, ' . htmlspecialchars($username);
    $response['redirect'] = '/';
    echo json_encode($response);
} else {
    http_response_code(500);
    $response['message'] = 'Terjadi kesalahan saat menyimpan data.';
    echo json_encode($response);
}

$stmt->close();
?>