<?php
ob_start();
session_start();
include('../config/koneksi.php');
include('../config/class_softgaming.php');

// Fungsi untuk menghasilkan kode referral secara acak
function generateReferralCode() {
    return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), 0, 8); // Generate kode referral acak dengan 8 karakter huruf
}

// Ambil informasi dari form registrasi dan escape untuk keamanan
$username = mysqli_real_escape_string($conn, strtolower(trim($_POST['user'])));
$email_input = trim($_POST['email']);
$email = filter_var($email_input, FILTER_VALIDATE_EMAIL);
$phone_number = mysqli_real_escape_string($conn, trim($_POST['no_hp']));
$bank_name = mysqli_real_escape_string($conn, trim($_POST['akun']));
$bank_account_number = mysqli_real_escape_string($conn, trim($_POST['no_rek']));
$full_name = mysqli_real_escape_string($conn, trim($_POST['full_name']));
$password_input = $_POST['pass'];
$sponsor = mysqli_real_escape_string($conn, trim($_POST['sponsor'] ?? ''));

// Validasi input kosong
if (empty($username) || !$email || empty($phone_number) || empty($bank_name) || empty($bank_account_number) || empty($full_name) || empty($password_input)) {
    // Jika ada input yang kosong, arahkan kembali ke halaman register dengan notifikasi
    header('location:../desktop/register/?notif=6');
    exit();
}

// Hash password
$password = password_hash($password_input, PASSWORD_DEFAULT);
$level = 'user';
$join_date = date('Y-m-d H:i:s');
// Tentukan default upline ID
$default_uplineID = 0;

// Tentukan kode referral secara acak untuk pengguna baru
$otomatis = generateReferralCode();

// Cari pengguna yang mereferensikan jika kode referensi diberikan
$referral_user_id = $default_uplineID;
if (!empty($sponsor)) {
    $referral_query = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE referral_code = '$sponsor'");
    if (mysqli_num_rows($referral_query) > 0) {
        $referral_data = mysqli_fetch_assoc($referral_query);
        $referral_user_id = $referral_data['cuid']; // Ambil ID pengguna yang mereferensikan
    }
}

// Cek apakah username sudah terdaftar
$username_check = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE username = '$username'");
if (mysqli_num_rows($username_check) > 0) {
    // Jika username sudah terdaftar, arahkan kembali ke halaman register dengan notifikasi
    header('location:../desktop/register/?notif=2');
    exit();
}

// Cek apakah email sudah terdaftar
$email_check = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE email = '$email'");
if (mysqli_num_rows($email_check) > 0) {
    // Jika email sudah terdaftar, arahkan kembali ke halaman register dengan notifikasi
    header('location:../desktop/register/?notif=3');
    exit();
}

// Cek apakah nomor HP sudah terdaftar
$phone_check = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE phone_number = '$phone_number'");
if (mysqli_num_rows($phone_check) > 0) {
    header('location:../desktop/register/?notif=4');
    exit();
}

// Cek apakah nomor rekening sudah terdaftar
$bank_check = mysqli_query($conn, "SELECT * FROM `tb_bank` WHERE no_rek = '$bank_account_number'");
if (mysqli_num_rows($bank_check) > 0) {
    header('location:../desktop/register/?notif=5');
    exit();
}

$WL = new fiver();
$apiResponse = $WL->create($username);

if (!$apiResponse || (isset($apiResponse['status']) && $apiResponse['status'] != 1)) {
    header('location:../desktop/register/?notif=6');
    exit();
}

$query = mysqli_query($conn, "INSERT INTO `tb_user` (`username`, `password`, `email`, `full_name`, `phone_number`, `level`, `join_date`, `last_login`, `status`, `referral_code`, `referral_user_id`) VALUES ('$username', '$password', '$email', '$full_name', '$phone_number', '$level', '$join_date', '$join_date', 1, '$otomatis', '$referral_user_id')") or die(mysqli_error($conn));

if (!$query) {
    header('location:../desktop/register/?notif=6');
    exit();
}

$last_user_id = mysqli_insert_id($conn);
$query2 = mysqli_query($conn, "INSERT INTO `tb_bank` (`image`, `akun`, `pemilik`, `no_rek`, `status`, `userID`) VALUES ('', '$bank_name', '$full_name', '$bank_account_number', 1, '$last_user_id')") or die(mysqli_error($conn));

if (!$query2) {
    // Rollback: hapus user yang sudah dibuat jika bank gagal
    mysqli_query($conn, "DELETE FROM `tb_user` WHERE cuid = '$last_user_id'");
    header('location:../desktop/register/?notif=6');
    exit();
}

$query3 = mysqli_query($conn, "INSERT INTO `tb_balance` (`userID`, `active`, `pending`, `transfer`, `payout`, `created_date`) VALUES ('$last_user_id', 0, 0, 0, 0, '$join_date')") or die(mysqli_error($conn));

if (!$query3) {
    // Rollback: hapus user dan bank yang sudah dibuat jika balance gagal
    mysqli_query($conn, "DELETE FROM `tb_bank` WHERE userID = '$last_user_id'");
    mysqli_query($conn, "DELETE FROM `tb_user` WHERE cuid = '$last_user_id'");
    header('location:../desktop/register/?notif=6');
    exit();
}

if ($referral_user_id != $default_uplineID) {
    $update = mysqli_query($conn, "UPDATE `tb_user` SET referral_count = referral_count + 1 WHERE cuid = '$referral_user_id'") or die(mysqli_error($conn));
}

// Auto-login: Set Session dan redirect ke halaman utama
$_SESSION['user'] = $username;
header('location:../desktop/?notif=4');
exit();
?>
