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

if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    
    $sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error($conn));
    $s0 = mysqli_fetch_array($sql_0);
    $urlweb = $s0['urlweb'];
    $token = session_id();
    $full_name = htmlspecialchars($_POST['full_name']);
    $usere = strtolower($_POST['user']);
    $useree = mysqli_real_escape_string($conn, $usere);
    $user = str_replace(' ', '', $useree);

    function generateRandomString($length = 20) {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    $randomString = generateRandomString();
    $safeOutput = $randomString;
    $extplayer = htmlspecialchars($safeOutput, ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars($_POST['email']); // Email masih diambil dari input tetapi tidak digunakan
    $no_hp = htmlspecialchars($_POST['no_hp']);
    $akun = htmlspecialchars($_POST['akun']);
    $no_rek = htmlspecialchars($_POST['no_rek']);
    $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT);
    $level = 'user';
    $join_date = date('Y-m-d H:i:s');

    // Dapatkan cuid terakhir dan tambahkan 1 untuk cuid baru
    $cekusere = mysqli_query($conn, "SELECT * FROM `tb_user` ORDER BY cuid DESC LIMIT 1") or die(mysqli_error($conn));
    $cus = mysqli_fetch_array($cekusere);
    $cuid = $cus['cuid'] + 1;
    $useridd = '1' . date('dmy') . $cuid;

    // Cek apakah username sudah digunakan
    $cekUser = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE user = '$user'") or die(mysqli_error($conn));
    $q = mysqli_num_rows($cekUser);
    if ($q > 0) {
        // Notifikasi jika username sudah digunakan
        $_SESSION['notifr'] = ['type' => 'warning', 'message' => 'Username Sudah Digunakan!'];
        header('Location: ' . $_SERVER['HTTP_REFERER']);
    } else {
        // Cek apakah nomor HP sudah digunakan
        $cekHp = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE no_hp = '$no_hp'") or die(mysqli_error($conn));
        $qqq = mysqli_num_rows($cekHp);
        if ($qqq > 0) {
            // Notifikasi jika nomor HP sudah digunakan (tidak ada header redirect, bisa tambahkan jika perlu)
            // header('location:../?notif=4');
        } else {
            // Verifikasi sponsor/upline
            if ($_POST['sponsor'] == '') {
                $uplineID = 1;
            } else {
                $upline = $_POST['sponsor'];
                $cekUpline = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE user = '$upline'") or die(mysqli_error($conn));
                $cu = mysqli_num_rows($cekUpline);
                if ($cu == 0) {
                    $uplineID = 1;
                } else {
                    $cuu = mysqli_fetch_array($cekUpline);
                    $uplineID = $cuu['cuid'];
                }
            }

            $sql_255 = mysqli_query($conn, "SELECT * FROM `tb_apigames` WHERE cuid = 1") or die(mysqli_error($conn));
            $s255 = mysqli_fetch_array($sql_255);
            
            // Panggil API untuk register user eksternal
            $token = $s255['token'];
            $owner = $s255['owner'];
            $endpoint = $s255['endpoint'];
            $kingisback->registerGame($extplayer);

            // Masukkan data user baru ke database
            $query = mysqli_query($conn, "INSERT INTO `tb_user` (`userid`, `extplayer`, `user`, `pass`, `token_id`, `image`, `full_name`, `email`, `no_hp`, `level`, `pinTrx`, `reff`, `uplineID`, `join_date`, `last_login`, `status`, `statusGame`) VALUES ('0','$extplayer','$user', '$pass', '0', 'avatar5.png', '$full_name', '$email', '$no_hp', 'user', '', 0, '$uplineID', '$join_date', '$join_date', 1, 0)") or die(mysqli_error($conn));

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

            // Perbarui jumlah referensi upline
            $update = mysqli_query($conn, "UPDATE `tb_user` SET reff = reff + 1 WHERE cuid = '$uplineID'") or die(mysqli_error($conn));

			//bank
            $query3 = mysqli_query($conn,"INSERT INTO `tb_bank` (`image`, `akun`, `pemilik`, `no_rek`, `status`, `userID`) VALUES ('', '$akun', '$full_name', '$no_rek', 1, '$last_id')") or die(mysqli_error());

            // Login otomatis pengguna setelah pendaftaran
            $_SESSION['user'] = $user;
            $_SESSION['pass'] = $pass; // Pastikan password disimpan sebagai hash atau perbarui jika diperlukan

            // Notifikasi sukses pendaftaran dan langsung login
            header('location:../secure/home'); // Arahkan ke halaman dashboard setelah login
            exit();
        }
    }
} else {
    // CSRF token tidak valid, tangani kesalahan
    $_SESSION['notifr'] = ['type' => 'warning', 'message' => 'Error!'];
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit();
}
?>
