<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
/** 
 * db.php provides:
 * - $conn (MySQLi Connection)
 * - generateReferralCode($conn)
 * - Session safety (prevents Guest data collisions)
 */
require_once 'account/include/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    
    // 1. Verify Captcha
    $user_captcha = strtoupper(trim($_POST['captcha'] ?? ''));
    $session_captcha = $_SESSION['captcha_code'] ?? '';
    
    if ($user_captcha !== $session_captcha || empty($session_captcha)) {
        unset($_SESSION['captcha_code']);
        showAlert("Verification Failed", "Incorrect security code. Please try again.", "warning", "register.php");
        exit;
    }

    // 2. Sanitize and Prepare Inputs
    $username  = mysqli_real_escape_string($conn, $_POST['username']);
    $full_name = mysqli_real_escape_string($conn, $_POST['full_name']);
    $email     = mysqli_real_escape_string($conn, $_POST['email']);
    $phone     = mysqli_real_escape_string($conn, $_POST['phone']);
    $country   = mysqli_real_escape_string($conn, $_POST['country']);
    $password  = $_POST['password']; // Will be hashed below
    $referralCodeInput = mysqli_real_escape_string($conn, $_POST['referral_code'] ?? '');
    
    // 3. Check for existing User or Email
    $check_sql = "SELECT id FROM users WHERE email = '$email' OR username = '$username' LIMIT 1";
    $check_res = mysqli_query($conn, $check_sql);
    
    if ($check_res && mysqli_num_rows($check_res) > 0) {
        unset($_SESSION['captcha_code']);
        showAlert("Registration Error", "Username or Email is already registered.", "error", "register.php");
        exit;
    }

    // 4. Secure Password Hashing
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // 5. Generate unique code for the new user (Function from db.php)
    $newReferralCode = generateReferralCode($conn);
    
    // System Defaults
    $balance = 0.00;
    $default_theme = '#0ea5e9';
    $created_at = date('Y-m-d H:i:s');

    // 6. Database Insertion
    $insert_sql = "INSERT INTO `users` 
        (`username`, `full_name`, `email`, `phone`, `country`, `password`, `balance`, `theme`, `created_at`, `referral_code`) 
        VALUES 
        ('$username', '$full_name', '$email', '$phone', '$country', '$password', '$balance', '$default_theme', '$created_at', '$newReferralCode')";
                   
    if (mysqli_query($conn, $insert_sql)) {
        $newUserId = mysqli_insert_id($conn);
        
        // 7. Process Referral (If user signed up with a link)
        if (!empty($referralCodeInput)) {
            processReferral($conn, $newUserId, $referralCodeInput);
        }
        
        // Cleanup session and cookies
        unset($_SESSION['captcha_code']);
        unset($_SESSION['pending_referral']);
        setcookie('referral_code', '', time() - 3600, '/');
        
        showAlert("Registration Successful!", "Welcome! You can now log in to your dashboard.", "success", "login.php");
        exit;
    } else {
        $db_error = addslashes(mysqli_error($conn));
        showAlert("Registration Failed", "System Error: " . $db_error, "error", "register.php");
        exit;
    }
}

/**
 * Helper: SweetAlert Display
 */
function showAlert($title, $text, $icon, $location) {
    echo '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <style>body { background-color: #0b111a; }</style>
    </head>
    <body>
        <script>
            Swal.fire({
                title: "' . $title . '",
                text: "' . $text . '",
                icon: "' . $icon . '",
                background: "#121a24",
                color: "#ffffff",
                confirmButtonColor: "' . ($icon === 'success' ? '#0ea5e9' : '#ef4444') . '"
            }).then(() => {
                window.location.href = "' . $location . '";
            });
        </script>
    </body>
    </html>';
}

/**
 * Referral Tracking & Bonus Logic
 */
function processReferral($conn, $newUserId, $referralCode) {
    $code = mysqli_real_escape_string($conn, $referralCode);
    $referrerSql = "SELECT id FROM users WHERE referral_code = '$code' LIMIT 1";
    $referrerResult = mysqli_query($conn, $referrerSql);
    
    if ($referrerResult && mysqli_num_rows($referrerResult) > 0) {
        $referrer = mysqli_fetch_assoc($referrerResult);
        $referrerId = intval($referrer['id']);
        
        // Prevent self-referral loop
        if ($referrerId === $newUserId) return;
        
        ensureReferralTables($conn);
        
        // 1. Record the relationship
        mysqli_query($conn, "INSERT INTO referral_tracking (referrer_id, referred_id, status, created_at) 
                             VALUES ($referrerId, $newUserId, 'active', NOW())
                             ON DUPLICATE KEY UPDATE status = 'active'");
        
        // 2. Bonus & Statistics Update ($5.00 Signup Reward)
        $bonus = 5.00;
        mysqli_query($conn, "UPDATE users SET total_referrals = total_referrals + 1, 
                             referral_earnings = referral_earnings + $bonus WHERE id = $referrerId");
        
        // 3. Log the Earning
        mysqli_query($conn, "INSERT INTO referral_earnings (referrer_id, referred_id, amount, type, description, status, paid_at) 
                             VALUES ($referrerId, $newUserId, $bonus, 'signup_bonus', 'Referral signup reward', 'paid', NOW())");
        
        // 4. Map the 'referred_by' ID to the new user
        mysqli_query($conn, "UPDATE users SET referred_by = $referrerId WHERE id = $newUserId");
    }
}

/**
 * Maintenance: Ensure Database Schema is Up-to-Date
 */
function ensureReferralTables($conn) {
    // Tracking Table
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `referral_tracking` (
        `id` INT(11) NOT NULL AUTO_INCREMENT,
        `referrer_id` INT(11) NOT NULL,
        `referred_id` INT(11) NOT NULL,
        `status` ENUM('pending','active','inactive') DEFAULT 'pending',
        `earnings` DECIMAL(15,2) DEFAULT 0.00,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `activated_at` TIMESTAMP NULL DEFAULT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `unique_referral` (`referrer_id`, `referred_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    // Earnings Table
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `referral_earnings` (
        `id` INT(11) NOT NULL AUTO_INCREMENT,
        `referrer_id` INT(11) NOT NULL,
        `referred_id` INT(11) NOT NULL,
        `amount` DECIMAL(15,2) NOT NULL,
        `type` ENUM('signup_bonus','deposit_bonus','trade_commission','withdrawal') DEFAULT 'signup_bonus',
        `description` VARCHAR(255) DEFAULT NULL,
        `status` ENUM('pending','paid','cancelled') DEFAULT 'pending',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `paid_at` TIMESTAMP NULL DEFAULT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // Add necessary columns to users table
    $alterations = [
        "ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `referred_by` INT(11) DEFAULT NULL",
        "ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `total_referrals` INT(11) DEFAULT 0",
        "ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `referral_earnings` DECIMAL(15,2) DEFAULT 0.00"
    ];
    foreach($alterations as $sql) mysqli_query($conn, $sql);
}
?>