<?php
session_start();

require("../includes/db_connect.php");

$email = "";
$accountId = "";
$token = "";
$fullname = "";

function send_vcode()
{
    global $accountId, $email, $token, $fullname;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&email=$email&token=$token&name=$fullname");
    curl_setopt($ch, CURLOPT_URL, 'https://rocketta.io/email/send_verification_mail');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_exec($ch);
    curl_close($ch);

    die("success");
}

$recaptcha_secret = "6LdYt34pAAAAANJ3BPmbvqFPPFb9YdEzB6ln-rMz";
$response_token = $_POST['g-recaptcha-response'] ?? '';

$verify_url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
    'secret' => $recaptcha_secret,
    'response' => $response_token
);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);

$context  = stream_context_create($options);
$verify_result = file_get_contents($verify_url, false, $context);
$verify_response = json_decode($verify_result);

if (!$verify_response->success) {
    
   
    die("reCAPTCHA verification failed. Please try again.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((!empty($_POST['firstname'])) && !empty($_POST['lastname']) && (!empty($_POST['email'])) && (!empty($_POST['password'])) && (!empty($_POST['country'])) && (!empty($_POST['mobile']))) {
        if ($conn) {
            try {
                $fullname = trim(str_replace(' ','',$_POST['firstname']))." ".trim(str_replace(' ','',$_POST['lastname']));
                $email = $_POST['email'];
                $password = $_POST['password'];
                $country = $_POST['country'];
                $mobile = $_POST['mobile'];
                $referral_code = trim($_POST['referral_code']) ?? null;

                $token = 'qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM0123456789!$*';
                $token = str_shuffle($token);
                $token = substr($token, 0, 100);

                $usr_sql = "SELECT email FROM users WHERE email =? LIMIT 1";
                $usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $usr_sth->execute([$email]);
                $users = $usr_sth->fetchAll();

                if (count($users) > 0) {
                    die("Email is already assigned to an existing account.");
                } else {
                    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

                    $randnb = '0123456789';
                    $randnb = str_shuffle($randnb);
                    $randnb = substr($randnb, 0, 6);

                    $accountId = strtolower(substr(@$_POST['firstname'], 0, 1)).strtolower(substr(@$_POST['lastname'], 0, 1)).$randnb;
                    // var_dump($accountId);die;
                    $user_sql = "INSERT INTO users (accountId, fullname, email, password, phone_number, country, referrer, status, email_confirmation, access_token) VALUES (?,?,?,?,?,?,?,?,?,?)";
                    $create_user = $conn->prepare($user_sql)->execute([$accountId, $fullname, $email, $hashedPassword, $mobile, $country, $referral_code, 1, 0, $token]);

                    if ($create_user) {

                        $demo_trading_balances_sql = "INSERT INTO demo_trading_balances (accountId, profit, trade_amount) VALUES (?,?,?)";

                        $month_trading_balances_sql = "INSERT INTO monthly_trading_balances (accountId, profit, trade_amount) VALUES (?,?,?)"; 
                        
                      $quarter_trading_balance_sql = "INSERT INTO quarterly_trading_balances (accountId, profit, trade_amount) VALUES (?,?,?)"; 

                        $annual_trading_balances_sql = "INSERT INTO annual_trading_balances (accountId, profit, trade_amount, withdrawn) VALUES (?,?,?,?)"; 
                        
                        $bot_trading_balances_sql = "INSERT INTO bot_trading_balances (accountId, profit, trade_amount, withdrawn) VALUES (?,?,?,?)";

                        $bonus_account_balances_sql = "INSERT INTO bonus_account_balances (accountId, total_bonus, withdrawn, date) VALUES (?,?,?,?)";

                        $wallet_sql = "INSERT INTO wallet (accountId, balance, withdrawn) VALUES (?,?,?)"; 
                        
                        $bot_account_balances_sql = "INSERT INTO bot_account_balances (accountId, total_bonus, profit, withdrawn, date) VALUES (?,?,?,?,?)";

                        $create_balance1 = $conn->prepare($demo_trading_balances_sql)->execute([$accountId, 0.00, 0.00]);
                        $create_balance2 = $conn->prepare($month_trading_balances_sql)->execute([$accountId, 0.00, 0.00]); 
                      $create_balance3 = $conn->prepare($quarter_trading_balance_sql)->execute([$accountId, 0.00, 0.00]);
                        $create_balance4 = $conn->prepare($annual_trading_balances_sql)->execute([$accountId, 0.00, 0.00, 0.00]);
                        $create_balance5 = $conn->prepare($wallet_sql)->execute([$accountId, 0.00, 0.00]);
                        $create_balance6 = $conn->prepare($bot_trading_balances_sql)->execute([$accountId, 0.00, 0.00]);
                        $create_balance7 = $conn->prepare($bonus_account_balances_sql)->execute([$accountId, 0.00, 0.00, date('Y-m-d H:i:s')]);
                        $create_balance8 = $conn->prepare($bot_account_balances_sql)->execute([$accountId, 0.00, 0.00, 0.00, date('Y-m-d H:i:s')]);

                        if ($create_balance1 && $create_balance2 && $create_balance3 && $create_balance4 && $create_balance5 && $create_balance6 && $create_balance7 && $create_balance8) {
                            send_vcode();
                        } else {
                            die('An unexpected error occurred. Please try again.');
                        }
                    } else {
                        die('An unexpected error occurred. Please try again.');
                    }
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}