<?php
session_start();
require_once(__DIR__ . "/../config/db.php");
require_once(__DIR__ . "/../api/AuraGaming-API.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "CSRF Token Tidak Valid.";
        header("Location: /mobile/register");
        exit();
    }

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $phone = trim($_POST['phone']);
    $whatsapp = trim($_POST['whatsapp']);
    $bank_name = trim($_POST['BankName']);
    $bank_holder = trim($_POST['BankHolder']);
    $bank_number = trim($_POST['BankNumber']);
    
    // Basic device detection
    $isMobile = false;
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $isMobile = preg_match('/mobile|android|iphone|ipad/i', $userAgent);
    }

    function generateExtPlayer($username)
    {
        $prefix = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 2);
        $suffix = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 2);
        return $prefix . $username . $suffix;
    }

    if ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } elseif (!empty($username) && !empty($password) && !empty($phone) && !empty($whatsapp) && !empty($bank_name) && !empty($bank_holder) && !empty($bank_number)) {
        $checkUser = "SELECT id FROM user WHERE username = :username OR phone = :phone LIMIT 1";
        $stmt = $db->prepare($checkUser);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
        $stmt->execute();

        if ($stmt->rowCount() === 0) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $fullname = $bank_holder;
            $extplayer = generateExtPlayer($username);

            $act = $AG->create($agent_code, $agent_token, $extplayer);
            $insertUser = "INSERT INTO user (username, password, phone, whatsapp, fullname, extplayer) VALUES (:username, :password, :phone, :whatsapp, :fullname, :extplayer)";
            $stmt = $db->prepare($insertUser);
            $stmt->bindParam(':username', $username, PDO::PARAM_STR);
            $stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);
            $stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
            $stmt->bindParam(':whatsapp', $whatsapp, PDO::PARAM_STR);
            $stmt->bindParam(':fullname', $fullname, PDO::PARAM_STR);
            $stmt->bindParam(':extplayer', $extplayer, PDO::PARAM_STR);
            $stmt->execute();

            $user_id = $db->lastInsertId();

            $insertBank = "INSERT INTO bank_user (user_id, BankName, BankHolder, BankNumber) VALUES (:user_id, :BankName, :BankHolder, :BankNumber)";
            $stmt = $db->prepare($insertBank);
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindParam(':BankName', $bank_name, PDO::PARAM_STR);
            $stmt->bindParam(':BankHolder', $bank_holder, PDO::PARAM_STR);
            $stmt->bindParam(':BankNumber', $bank_number, PDO::PARAM_STR);
            $stmt->execute();

            $insertBalance = "INSERT INTO balance (user_id, total_balance, total_turnover, total_win) VALUES (:user_id, 0.00, 0.00, 0.00)";
            $stmt = $db->prepare($insertBalance);
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->execute();

            $_SESSION['user_id'] = $user_id;
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

            // Redirect based on device type
            if ($isMobile) {
                header("Location: /mobile/register-done");
            } else {
                header("Location: /mobile/register-done");
            }
            exit();
        } else {
            $_SESSION['error'] = "Username or Nomor Telepon Sudah Digunakan.";
            header("Location: /");
            exit();
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}
