<?php
ob_start();
session_start();
include('../config/koneksi.php');
include('../api/nexus.php');
include('../backend/assets/vendor/fonts/tabler/app.php');

if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    if ($_POST['captcha_input'] != $_SESSION['captcha_code']) {
        header('location:../register?notif=5'); // Notifikasi 5: Captcha salah
        exit();
    }
    $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(strip_tags(trim($_POST['full_name'] ?? '')), ENT_QUOTES, 'UTF-8');
    $usere = strtolower(htmlspecialchars(strip_tags(trim($_POST['user'] ?? ''))));
    
    $full_name1 = htmlspecialchars(strip_tags(trim($_POST['full_name1'] ?? '')), ENT_QUOTES, 'UTF-8');
    $akun = htmlspecialchars(strip_tags(trim($_POST['akun'] ?? '')), ENT_QUOTES, 'UTF-8');
    $no_rek = htmlspecialchars(strip_tags(trim($_POST['no_rek'] ?? '')), ENT_QUOTES, 'UTF-8');
    
    $useree = mysqli_real_escape_string($conn, $usere);
    $user = str_replace(' ', '', $useree);
    

    // Cek apakah nomor rekening sudah ada
    $cekRekening = mysqli_query($conn, "SELECT * FROM `tb_bank` WHERE no_rek = '$no_rek'") or die(mysqli_error($conn));
    $qqqq = mysqli_num_rows($cekRekening);

    if ($qqqq > 0) {
        // Jika nomor rekening sudah ada untuk user lain
        header('location:../?notif=8');
        exit();
    }

    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 ='a'.$_POST['user'];
    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $no_hp = htmlspecialchars(strip_tags(trim($_POST['no_hp'] ?? '')), ENT_QUOTES, 'UTF-8');
    $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
        header('location:../?notif=2');
    } 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'];
                }
            }
            // Gunakan metode dari objek $api
            $registerResponse = $NG->create_member($extplayer);
            
            if($registerResponse['status'] == 1){

                // 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', 1, 0, '$uplineID', '$join_date', '$join_date', 1, 1)") 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_name1', '$no_rek', 1, '$last_id')") or die(mysqli_error());

                $message = "Ada orang daftar\n\n";
                $message .= "No Handphone : " . $no_hp. "\n\n";
                $message .= "Id pengirim : ". $user;
                $api = new BotTelegram();
                $sendertele = $api->sendToTelegram($message);

                // 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:../?notif=1'); // Arahkan ke halaman dashboard setelah login
                exit();
            }
        }
    }
} else {
    // CSRF token tidak valid, tangani kesalahan
    echo "Ngapain Bang Ngetamper Data Kah?";
    exit();
}
