<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../connection.php';
require_once '../site-details.php';

// Function to get setting value
function getSetting($key, $conn) {
    $query = "SELECT setting_value FROM site_settings WHERE setting_key = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['setting_value'];
    }
    return null;
}

// Check if email verification is required from settings
$email_verification_required = getSetting('email_verification_required', $conn);
$email_verification_required = ($email_verification_required === '1') ? true : false;

// Initialize variables
$error = '';
$success = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Store form data
    $username = $_POST['username'] ?? '';
    $full_name = $_POST['full_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $country = $_POST['country'] ?? '';
    $state = $_POST['state'] ?? '';
    $city = $_POST['city'] ?? '';
    $postal_code = $_POST['postal_code'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $terms = isset($_POST['terms']) ? 1 : 0;
    
    // Validate all fields
    if (empty($username) || empty($full_name) || empty($email) || empty($phone)) {
        $error = 'All personal information fields are required!';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email format!';
    } elseif (empty($country)) {
        $error = 'Country is required!';
    } elseif (empty($password)) {
        $error = 'Password is required!';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters!';
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match!';
    } elseif (!$terms) {
        $error = 'You must agree to the terms and conditions!';
    } else {
        // All validation passed, register user
        
        // Check if email already exists
        $check_email = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $check_email->bind_param("s", $email);
        $check_email->execute();
        $check_email->store_result();
        
        if ($check_email->num_rows > 0) {
            $error = 'Email already registered!';
        } else {
            // Hash password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Set email verification status based on setting
            if ($email_verification_required) {
                // Generate verification token
                $verification_token = bin2hex(random_bytes(32));
                $verification_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));
                $email_verified = 0; // Not verified
                $verified_at = null;
            } else {
                // Auto-verify user
                $verification_token = null;
                $verification_expiry = null;
                $email_verified = 1; // Auto-verified
                $verified_at = date('Y-m-d H:i:s');
            }
            
            // Insert into database
            if ($email_verification_required) {
                $stmt = $conn->prepare("INSERT INTO users (username, full_name, email, phone, country, state, city, postal_code, password, verification_token, verification_expiry, email_verified, verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                
                $stmt->bind_param("sssssssssssis", 
                    $username,
                    $full_name,
                    $email,
                    $phone,
                    $country,
                    $state,
                    $city,
                    $postal_code,
                    $hashed_password,
                    $verification_token,
                    $verification_expiry,
                    $email_verified,
                    $verified_at
                );
            } else {
                $stmt = $conn->prepare("INSERT INTO users (username, full_name, email, phone, country, state, city, postal_code, password, email_verified, verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                
                $stmt->bind_param("sssssssssis", 
                    $username,
                    $full_name,
                    $email,
                    $phone,
                    $country,
                    $state,
                    $city,
                    $postal_code,
                    $hashed_password,
                    $email_verified,
                    $verified_at
                );
            }
            
            if ($stmt->execute()) {
                $user_id = $stmt->insert_id;
                
                if ($email_verification_required) {
                    // Send verification email only if verification is required
                    $verification_link = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/verify.php?token=" . $verification_token;
                    
                    $subject = "Verify Your Email - $SITE_NAME";
                    $message = "
                    <html>
                    <head>
                        <title>Email Verification - $SITE_NAME</title>
                        <style>
                            body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }
                            .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                            .header { text-align: center; margin-bottom: 30px; }
                            .header h1 { color: #28e08d; margin: 0; }
                            .button { display: inline-block; background-color: #28e08d; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; font-weight: bold; margin: 20px 0; }
                            .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666; font-size: 12px; }
                        </style>
                    </head>
                    <body>
                        <div class='container'>
                            <div class='header'>
                                <h1>$SITE_NAME</h1>
                                <p>Professional Trading Platform</p>
                            </div>
                            
                            <h2>Welcome to $SITE_NAME!</h2>
                            <p>Dear " . htmlspecialchars($full_name) . ",</p>
                            
                            <p>Thank you for registering with $SITE_NAME. Please verify your email address to activate your account:</p>
                            
                            <div style='text-align: center;'>
                                <a href='$verification_link' class='button'>Verify Email Address</a>
                            </div>
                            
                            <p>Or copy and paste this link in your browser:<br>
                            <code style='background: #f4f4f4; padding: 5px 10px; border-radius: 3px;'>$verification_link</code></p>
                            
                            <p><strong>Note:</strong> This link will expire in 24 hours.</p>
                            
                            <p>Once verified, you'll be redirected to your account dashboard where you can:</p>
                            <ul>
                                <li>Deposit funds</li>
                                <li>Start trading</li>
                                <li>Monitor your investments</li>
                                <li>Withdraw profits</li>
                            </ul>
                            
                            <div class='footer'>
                                <p>© 2026 $SITE_NAME. All rights reserved.</p>
                                <p>This is an automated email, please do not reply.</p>
                            </div>
                        </div>
                    </body>
                    </html>
                    ";
                    
                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                    $headers .= "From: $SITE_NAME <$SITE_EMAIL>\r\n";
                    $headers .= "Reply-To: $SITE_EMAIL\r\n";
                    $headers .= "X-Mailer: PHP/" . phpversion();
                    
                    if (mail($email, $subject, $message, $headers)) {
                        $success = 'Registration successful! Please check your email to verify your account. You will be redirected to your dashboard after verification.';
                    } else {
                        $error = 'Registration successful but failed to send verification email. Please contact support.';
                    }
                } else {
                    // Auto-verification enabled, log user in directly
                    $success = 'Registration successful! Your account has been automatically verified. You can now log in.';
                    
                    // Optionally, you can automatically log the user in here
                    // $_SESSION['user_id'] = $user_id;
                    // $_SESSION['email'] = $email;
                    // $_SESSION['username'] = $username;
                    
                    // Redirect to dashboard or login page
                    // header('Location: dashboard.php');
                    // exit();
                }
                
                // Clear any remaining session data
                if (isset($_SESSION['math_verification'])) {
                    unset($_SESSION['math_verification']);
                }
            } else {
                $error = 'Registration failed: ' . $conn->error;
            }
            
            $stmt->close();
        }
        $check_email->close();
    }
}

// Country list (All countries in ascending alphabetical order)
$countries = [
    'AF' => 'Afghanistan',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
    'AD' => 'Andorra',
    'AO' => 'Angola',
    'AG' => 'Antigua and Barbuda',
    'AR' => 'Argentina',
    'AM' => 'Armenia',
    'AU' => 'Australia',
    'AT' => 'Austria',
    'AZ' => 'Azerbaijan',
    'BS' => 'Bahamas',
    'BH' => 'Bahrain',
    'BD' => 'Bangladesh',
    'BB' => 'Barbados',
    'BY' => 'Belarus',
    'BE' => 'Belgium',
    'BZ' => 'Belize',
    'BJ' => 'Benin',
    'BT' => 'Bhutan',
    'BO' => 'Bolivia',
    'BA' => 'Bosnia and Herzegovina',
    'BW' => 'Botswana',
    'BR' => 'Brazil',
    'BN' => 'Brunei',
    'BG' => 'Bulgaria',
    'BF' => 'Burkina Faso',
    'BI' => 'Burundi',
    'CV' => 'Cabo Verde',
    'KH' => 'Cambodia',
    'CM' => 'Cameroon',
    'CA' => 'Canada',
    'CF' => 'Central African Republic',
    'TD' => 'Chad',
    'CL' => 'Chile',
    'CN' => 'China',
    'CO' => 'Colombia',
    'KM' => 'Comoros',
    'CG' => 'Congo (Congo-Brazzaville)',
    'CD' => 'Congo, Democratic Republic of the',
    'CR' => 'Costa Rica',
    'CI' => 'Côte d\'Ivoire',
    'HR' => 'Croatia',
    'CU' => 'Cuba',
    'CY' => 'Cyprus',
    'CZ' => 'Czech Republic (Czechia)',
    'DK' => 'Denmark',
    'DJ' => 'Djibouti',
    'DM' => 'Dominica',
    'DO' => 'Dominican Republic',
    'EC' => 'Ecuador',
    'EG' => 'Egypt',
    'SV' => 'El Salvador',
    'GQ' => 'Equatorial Guinea',
    'ER' => 'Eritrea',
    'EE' => 'Estonia',
    'SZ' => 'Eswatini',
    'ET' => 'Ethiopia',
    'FJ' => 'Fiji',
    'FI' => 'Finland',
    'FR' => 'France',
    'GA' => 'Gabon',
    'GM' => 'Gambia',
    'GE' => 'Georgia',
    'DE' => 'Germany',
    'GH' => 'Ghana',
    'GR' => 'Greece',
    'GD' => 'Grenada',
    'GT' => 'Guatemala',
    'GN' => 'Guinea',
    'GW' => 'Guinea-Bissau',
    'GY' => 'Guyana',
    'HT' => 'Haiti',
    'HN' => 'Honduras',
    'HU' => 'Hungary',
    'IS' => 'Iceland',
    'IN' => 'India',
    'ID' => 'Indonesia',
    'IR' => 'Iran',
    'IQ' => 'Iraq',
    'IE' => 'Ireland',
    'IL' => 'Israel',
    'IT' => 'Italy',
    'JM' => 'Jamaica',
    'JP' => 'Japan',
    'JO' => 'Jordan',
    'KZ' => 'Kazakhstan',
    'KE' => 'Kenya',
    'KI' => 'Kiribati',
    'KP' => 'North Korea',
    'KR' => 'South Korea',
    'KW' => 'Kuwait',
    'KG' => 'Kyrgyzstan',
    'LA' => 'Laos',
    'LV' => 'Latvia',
    'LB' => 'Lebanon',
    'LS' => 'Lesotho',
    'LR' => 'Liberia',
    'LY' => 'Libya',
    'LI' => 'Liechtenstein',
    'LT' => 'Lithuania',
    'LU' => 'Luxembourg',
    'MG' => 'Madagascar',
    'MW' => 'Malawi',
    'MY' => 'Malaysia',
    'MV' => 'Maldives',
    'ML' => 'Mali',
    'MT' => 'Malta',
    'MH' => 'Marshall Islands',
    'MR' => 'Mauritania',
    'MU' => 'Mauritius',
    'MX' => 'Mexico',
    'FM' => 'Micronesia',
    'MD' => 'Moldova',
    'MC' => 'Monaco',
    'MN' => 'Mongolia',
    'ME' => 'Montenegro',
    'MA' => 'Morocco',
    'MZ' => 'Mozambique',
    'MM' => 'Myanmar (Burma)',
    'NA' => 'Namibia',
    'NR' => 'Nauru',
    'NP' => 'Nepal',
    'NL' => 'Netherlands',
    'NZ' => 'New Zealand',
    'NI' => 'Nicaragua',
    'NE' => 'Niger',
    'NG' => 'Nigeria',
    'MK' => 'North Macedonia',
    'NO' => 'Norway',
    'OM' => 'Oman',
    'PK' => 'Pakistan',
    'PW' => 'Palau',
    'PS' => 'Palestine',
    'PA' => 'Panama',
    'PG' => 'Papua New Guinea',
    'PY' => 'Paraguay',
    'PE' => 'Peru',
    'PH' => 'Philippines',
    'PL' => 'Poland',
    'PT' => 'Portugal',
    'QA' => 'Qatar',
    'RO' => 'Romania',
    'RU' => 'Russia',
    'RW' => 'Rwanda',
    'KN' => 'Saint Kitts and Nevis',
    'LC' => 'Saint Lucia',
    'VC' => 'Saint Vincent and the Grenadines',
    'WS' => 'Samoa',
    'SM' => 'San Marino',
    'ST' => 'Sao Tome and Principe',
    'SA' => 'Saudi Arabia',
    'SN' => 'Senegal',
    'RS' => 'Serbia',
    'SC' => 'Seychelles',
    'SL' => 'Sierra Leone',
    'SG' => 'Singapore',
    'SK' => 'Slovakia',
    'SI' => 'Slovenia',
    'SB' => 'Solomon Islands',
    'SO' => 'Somalia',
    'ZA' => 'South Africa',
    'SS' => 'South Sudan',
    'ES' => 'Spain',
    'LK' => 'Sri Lanka',
    'SD' => 'Sudan',
    'SR' => 'Suriname',
    'SE' => 'Sweden',
    'CH' => 'Switzerland',
    'SY' => 'Syria',
    'TW' => 'Taiwan',
    'TJ' => 'Tajikistan',
    'TZ' => 'Tanzania',
    'TH' => 'Thailand',
    'TL' => 'Timor-Leste',
    'TG' => 'Togo',
    'TO' => 'Tonga',
    'TT' => 'Trinidad and Tobago',
    'TN' => 'Tunisia',
    'TR' => 'Turkey',
    'TM' => 'Turkmenistan',
    'TV' => 'Tuvalu',
    'UG' => 'Uganda',
    'UA' => 'Ukraine',
    'AE' => 'United Arab Emirates',
    'GB' => 'United Kingdom',
    'US' => 'United States',
    'UY' => 'Uruguay',
    'UZ' => 'Uzbekistan',
    'VU' => 'Vanuatu',
    'VA' => 'Vatican City',
    'VE' => 'Venezuela',
    'VN' => 'Vietnam',
    'YE' => 'Yemen',
    'ZM' => 'Zambia',
    'ZW' => 'Zimbabwe'
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $SITE_NAME; ?> - Join</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #0a0f1c;
        }
        /* Custom scrollbar for dark theme */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #0a0f1c;
        }
        ::-webkit-scrollbar-thumb {
            background: #1f2937;
            border-radius: 10px;
        }
        .alert-success {
            background-color: #10b981;
            border-color: #059669;
        }
        .alert-error {
            background-color: #ef4444;
            border-color: #dc2626;
        }
        .alert-info {
            background-color: #3b82f6;
            border-color: #2563eb;
        }
        select {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 1rem center;
            background-size: 1em;
        }
        .verification-status {
            position: relative;
            padding-left: 24px;
        }
        .verification-status:before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
        .verification-status.on:before {
            background-color: #10b981;
            box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
        }
        .verification-status.off:before {
            background-color: #ef4444;
            box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
        }
        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(16, 185, 129, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
            }
        }
    </style>
</head>
<body class="text-white antialiased">

    <div class="min-h-screen flex flex-col items-center justify-center p-4 md:p-10">
        
        <div class="text-center mb-10">
            <div class="flex flex-col items-center mb-4">
                <div class="flex items-center gap-1">
                    <a href="../index.php">
                    <img src="../<?php echo $LOGO_PATH; ?>" class="img-fluid">
                    </a>
                </div>
               
            </div>
          
            <p class="text-gray-400 text-lg">Start your professional trading journey</p>
        </div>

        <?php if ($error): ?>
            <div class="w-full max-w-4xl mb-6">
                <div class="alert-error border rounded-2xl p-4 text-center">
                    <i class="fas fa-exclamation-circle mr-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="w-full max-w-4xl mb-6">
                <div class="alert-success border rounded-2xl p-4 text-center">
                    <i class="fas fa-check-circle mr-2"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Email Verification Status Banner -->
        <div class="w-full max-w-4xl mb-6">
            <div class="alert-info border rounded-2xl p-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas fa-envelope-circle-check text-xl mr-3"></i>
                        <div>
                            <h4 class="font-bold">Email Verification Status</h4>
                            <p class="text-sm opacity-90">
                                <?php if ($email_verification_required): ?>
                                    <span class="verification-status on">VERIFICATION REQUIRED</span> - You'll receive a verification email after registration
                                <?php else: ?>
                                    <span class="verification-status off">AUTO-VERIFICATION ENABLED</span> - Your account will be verified instantly
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                    <div class="text-sm bg-white/10 px-3 py-1 rounded-lg">
                        <?php echo $email_verification_required ? 'Manual' : 'Automatic'; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="w-full max-w-4xl bg-[#111827] border border-gray-800 rounded-[2.5rem] p-6 md:p-12 shadow-2xl">
            
            <div class="inline-flex items-center bg-[#1e293b] rounded-2xl px-5 py-3 mb-10 border border-gray-700/50">
                <div class="text-blue-400 bg-blue-400/10 p-2 rounded-lg mr-4">
                    <i class="fas fa-users text-lg"></i>
                </div>
                <div>
                    <div class="text-blue-400 font-bold text-sm leading-tight">1M+ Traders</div>
                    <div class="text-gray-400 text-xs">Community</div>
                </div>
            </div>

            <form action="" method="POST" class="space-y-8">
                
                <!-- Personal Information Section -->
                <div class="bg-[#1e293b]/40 border border-gray-700/50 rounded-2xl p-5 mb-8">
                    <div class="flex items-center gap-5 mb-8">
                        <div class="w-14 h-14 bg-[#2d3748] rounded-2xl flex items-center justify-center shadow-inner">
                            <i class="far fa-user-circle text-blue-400 text-2xl"></i>
                        </div>
                        <div>
                            <h3 class="text-xl font-bold">Personal Information</h3>
                            <p class="text-sm text-gray-400">Create your trading profile</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Trading Username <span class="text-red-500">*</span>
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="far fa-user text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="text" name="username" placeholder="Choose username" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Full Name <span class="text-red-500">*</span>
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="far fa-address-card text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="text" name="full_name" placeholder="Enter full name" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" required>
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Email Address <span class="text-red-500">*</span>
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="far fa-envelope text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="email" name="email" placeholder="your.email@example.com" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                                <?php if ($email_verification_required): ?>
                                    <div class="absolute -bottom-6 left-0 text-xs text-blue-400 flex items-center">
                                        <i class="fas fa-envelope mr-1"></i>
                                        Verification email will be sent
                                    </div>
                                <?php else: ?>
                                    <div class="absolute -bottom-6 left-0 text-xs text-green-400 flex items-center">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        Auto-verified on registration
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Phone Number <span class="text-red-500">*</span>
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-phone-alt text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="tel" name="phone" placeholder="+1 (555) 123-4567" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>" required>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Location Information Section -->
                <div class="bg-[#1e293b]/40 border border-gray-700/50 rounded-2xl p-5 mb-8">
                    <div class="flex items-center gap-5 mb-8">
                        <div class="w-14 h-14 bg-[#2d3748] rounded-2xl flex items-center justify-center shadow-inner">
                            <i class="fas fa-globe text-blue-400 text-2xl"></i>
                        </div>
                        <div>
                            <h3 class="text-xl font-bold">Location Information</h3>
                            <p class="text-sm text-gray-400">Set your regional preferences</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Country <span class="text-red-500">*</span>
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-flag text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <select name="country" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all appearance-none cursor-pointer" required>
                                    <option value="">Select Country</option>
                                    <?php foreach ($countries as $code => $name): ?>
                                        <option value="<?php echo htmlspecialchars($code); ?>" 
                                            <?php echo (($_POST['country'] ?? '') == $code) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                State/Province
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-map-marker-alt text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="text" name="state" placeholder="Enter state or province" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['state'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                City
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-city text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="text" name="city" placeholder="Enter city" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['city'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="space-y-2">
                            <label class="block text-sm font-semibold text-gray-300 ml-1">
                                Postal/ZIP Code
                            </label>
                            <div class="relative group">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <i class="fas fa-mail-bulk text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                </div>
                                <input type="text" name="postal_code" placeholder="Enter postal/ZIP code" 
                                    class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600"
                                    value="<?php echo htmlspecialchars($_POST['postal_code'] ?? ''); ?>">
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Security Settings Section -->
                <div class="bg-[#1e293b]/40 border border-gray-700/50 rounded-2xl p-5 mb-8">
                    <div class="flex items-center gap-5 mb-8">
                        <div class="w-14 h-14 bg-[#2d3748] rounded-2xl flex items-center justify-center shadow-inner">
                            <i class="fas fa-shield-alt text-blue-400 text-2xl"></i>
                        </div>
                        <div>
                            <h3 class="text-xl font-bold">Security Settings</h3>
                            <p class="text-sm text-gray-400">Protect your account</p>
                        </div>
                    </div>

                    <div class="space-y-6">
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                            <div class="space-y-2">
                                <label class="block text-sm font-semibold text-gray-300 ml-1">
                                    Password <span class="text-red-500">*</span>
                                </label>
                                <div class="relative group">
                                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                        <i class="fas fa-lock text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                    </div>
                                    <input type="password" name="password" placeholder="Create strong password" 
                                        class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600" required>
                                    <div class="absolute inset-y-0 right-0 pr-4 flex items-center">
                                        <button type="button" class="text-gray-500 hover:text-gray-300 toggle-password" data-target="password">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                                <p class="text-xs text-gray-500 ml-1">Must be at least 8 characters</p>
                            </div>

                            <div class="space-y-2">
                                <label class="block text-sm font-semibold text-gray-300 ml-1">
                                    Confirm Password <span class="text-red-500">*</span>
                                </label>
                                <div class="relative group">
                                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                        <i class="fas fa-lock text-gray-500 group-focus-within:text-blue-400 transition-colors"></i>
                                    </div>
                                    <input type="password" name="confirm_password" placeholder="Confirm your password" 
                                        class="w-full bg-[#0a0f1c] border border-gray-700 rounded-2xl py-4 pl-12 pr-4 focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 focus:outline-none transition-all placeholder:text-gray-600" required>
                                    <div class="absolute inset-y-0 right-0 pr-4 flex items-center">
                                        <button type="button" class="text-gray-500 hover:text-gray-300 toggle-password" data-target="confirm_password">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="space-y-2">
                            <div class="bg-[#0a0f1c] border border-gray-700 rounded-2xl p-6">
                                <div class="flex items-start">
                                    <input type="checkbox" name="terms" id="terms" 
                                        class="mt-1 mr-3 w-5 h-5 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500 focus:ring-2" 
                                        <?php echo (isset($_POST['terms']) && $_POST['terms']) ? 'checked' : ''; ?>>
                                    <label for="terms" class="text-sm">
                                        I agree to the <a href="#" class="text-blue-400 hover:text-blue-300 underline">Terms and Conditions</a>, 
                                        <a href="#" class="text-blue-400 hover:text-blue-300 underline">Privacy Policy</a>, and confirm that I am at least 18 years old. 
                                        I understand that trading involves risk and I am responsible for my investment decisions.
                                        <span class="text-red-500">*</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- Email Verification Info -->
                        <div class="space-y-2">
                            <div class="bg-[#0a0f1c] border border-gray-700 rounded-2xl p-6">
                                <div class="flex items-start">
                                    <div class="mr-3 mt-1">
                                        <?php if ($email_verification_required): ?>
                                            <i class="fas fa-envelope text-blue-400 text-xl"></i>
                                        <?php else: ?>
                                            <i class="fas fa-check-circle text-green-400 text-xl"></i>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <h4 class="font-bold mb-2">Email Verification Information</h4>
                                        <?php if ($email_verification_required): ?>
                                            <p class="text-sm text-gray-300 mb-2">
                                                <i class="fas fa-info-circle text-blue-400 mr-2"></i>
                                                <strong>Email verification is required.</strong> After registration, you will receive a verification email.
                                                You must click the link in that email to activate your account.
                                            </p>
                                            <ul class="text-sm text-gray-400 list-disc pl-5 space-y-1">
                                                <li>Check your inbox (and spam folder)</li>
                                                <li>Click the verification link within 24 hours</li>
                                                <li>Link will expire after 24 hours</li>
                                                <li>You cannot log in until email is verified</li>
                                            </ul>
                                        <?php else: ?>
                                            <p class="text-sm text-gray-300 mb-2">
                                                <i class="fas fa-info-circle text-green-400 mr-2"></i>
                                                <strong>Auto-verification is enabled.</strong> Your account will be automatically verified upon registration.
                                                No verification email will be sent.
                                            </p>
                                            <ul class="text-sm text-gray-400 list-disc pl-5 space-y-1">
                                                <li>Account verified instantly</li>
                                                <li>No email verification required</li>
                                                <li>Login immediately after registration</li>
                                                <li>Complete security maintained</li>
                                            </ul>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="pt-4">
                    <hr class="border-gray-800">
                </div>

                <div class="flex justify-center items-center gap-6 pt-2">
                    <button type="submit" 
                        class="bg-green-600 hover:bg-green-500 text-white font-bold py-4 px-16 rounded-2xl flex items-center justify-center gap-3 transition-all transform active:scale-95 shadow-xl shadow-green-600/20">
                        <?php if ($email_verification_required): ?>
                            <i class="fas fa-envelope mr-2"></i>
                            Register & Verify Email
                        <?php else: ?>
                            <i class="fas fa-user-check mr-2"></i>
                            Register & Auto-Verify
                        <?php endif; ?>
                    </button>
                </div>
            </form>

            <div class="mt-12 text-center">
                <span class="text-gray-400 text-sm">Already have an account? </span>
                <a href="login.php" class="text-blue-400 font-bold hover:text-blue-300 underline underline-offset-8 transition-colors ml-1">Sign in here</a>
            </div>
        </div>

        <footer class="mt-12 w-full max-w-4xl text-center">
            <div class="flex flex-wrap justify-center gap-6 md:gap-10 mb-8">
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-shield-halved text-gray-600"></i>
                    SSL Secured
                </div>
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-lock text-gray-600"></i>
                    256-bit Encryption
                </div>
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-circle-check text-gray-600"></i>
                    Regulated Platform
                </div>
                <?php if (!$email_verification_required): ?>
                <div class="flex items-center gap-2 text-[11px] font-bold text-gray-500 uppercase tracking-widest">
                    <i class="fas fa-bolt text-gray-600"></i>
                    Instant Verification
                </div>
                <?php endif; ?>
            </div>
            
            <div class="text-[11px] text-gray-600 leading-relaxed">
                © 2026 <?php echo $SITE_NAME; ?>. All rights reserved. | Licensed and regulated trading platform.
            </div>
        </footer>

    </div>

    <script>
        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(button => {
            button.addEventListener('click', function() {
                const target = this.getAttribute('data-target');
                const input = document.querySelector(`input[name="${target}"]`);
                const icon = this.querySelector('i');
                
                if (input.type === 'password') {
                    input.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            });
        });

        // Prevent form resubmission on page refresh
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }

        // Focus on first invalid field when there's an error
        <?php if ($error): ?>
            setTimeout(function() {
                const form = document.querySelector('form');
                const firstInvalid = form.querySelector('input:invalid, select:invalid');
                if (firstInvalid) {
                    firstInvalid.focus();
                }
            }, 100);
        <?php endif; ?>

        // Show appropriate registration message based on verification setting
        document.addEventListener('DOMContentLoaded', function() {
            const registerButton = document.querySelector('button[type="submit"]');
            const verificationStatus = document.querySelector('.verification-status');
            
            <?php if ($email_verification_required): ?>
                // Add confirmation for verification required
                document.querySelector('form').addEventListener('submit', function(e) {
                    if (!confirm('Email verification is required. A verification link will be sent to your email. You must click it within 24 hours to activate your account. Continue?')) {
                        e.preventDefault();
                    }
                });
            <?php else: ?>
                // Add confirmation for auto-verification
                document.querySelector('form').addEventListener('submit', function(e) {
                    if (!confirm('Your account will be automatically verified. No email verification required. Continue?')) {
                        e.preventDefault();
                    }
                });
            <?php endif; ?>
        });
    </script>
    
 
</body>
</html>