<?php session_start();
include '../dashboard/includes/config.php';


// Secure token generation function for all PHP versions
function generateSecureToken($length = 32) {
    if (function_exists('random_bytes')) {
        return bin2hex(random_bytes($length));
    } elseif (function_exists('openssl_random_pseudo_bytes')) {
        $token = openssl_random_pseudo_bytes($length, $strong);
        if ($strong === TRUE) {
            return bin2hex($token);
        }
    }
    
    // Fallback method (less secure but works)
    $token = '';
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $chars_len = strlen($chars);
    for ($i = 0; $i < $length * 2; $i++) { // Multiply by 2 for hex representation
        $token .= $chars[mt_rand(0, $chars_len - 1)];
    }
    return $token;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get and sanitize form data
    $email = mysqli_real_escape_string($conn, trim($_POST['email']));
    $password = $_POST['password'];
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $first_name = mysqli_real_escape_string($conn, trim($_POST['first_name']));
    $last_name = mysqli_real_escape_string($conn, trim($_POST['last_name']));
    $confirm_password = $_POST['confirm_password'];
    $date_of_birth = $_POST['date_of_birth'] ?: '';
    $country = isset($_POST['country']) ? intval($_POST['country']) : 0;
    $referral_code = isset($_POST['referral_code']) ? mysqli_real_escape_string($conn, trim($_POST['referral_code'])) : '';
    $terms = isset($_POST['terms']) ? $_POST['terms'] : '';
    
    // Validate required fields
    $required_fields = [
        'email' => 'Email Address',
        'first_name' => 'First Name',
        'last_name' => 'Last Name',
        'phone' => 'Phone Number',
        'password' => 'Password',
        'confirm_password' => 'Confirm Password',
        'country' => 'Country',
        'date_of_birth' => 'Date of Birth'
    ];
    
    foreach ($required_fields as $field => $name) {
        if (empty($_POST[$field])) {
            echo '<script>
                showToast("Error!", "' . $name . ' is required", "danger");
                $("[name=\'' . $field . '\']").addClass("is-invalid");
            </script>';
            exit();
        }
    }
    
    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo '<script>
            showToast("Error!", "Please enter a valid email address", "danger");
            $("[name=\'email\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Validate password strength
    if (strlen($password) < 8) {
        echo '<script>
            showToast("Error!", "Password must be at least 8 characters long", "danger");
            $("[name=\'password\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
        echo '<script>
            showToast("Error!", "Password must contain both letters and numbers", "danger");
            $("[name=\'password\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Validate passwords match
    if ($password !== $confirm_password) {
        echo '<script>
            showToast("Error!", "Passwords do not match", "danger");
            $("[name=\'confirm_password\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Validate phone number format
    if (!preg_match('/^[0-9]{6,15}$/', $phone)) {
        echo '<script>
            showToast("Error!", "Please enter a valid phone number (6-15 digits)", "danger");
            $("[name=\'phone\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Validate date of birth (must be at least 18 years old)
    if (!empty($date_of_birth)) {
        $dob = new DateTime($date_of_birth);
        $today = new DateTime();
        $age = $today->diff($dob)->y;
        
        if ($age < 18) {
            echo '<script>
                showToast("Error!", "You must be at least 18 years old", "danger");
                $("[name=\'date_of_birth\']").addClass("is-invalid");
            </script>';
            exit();
        }
    }
    
    // Validate country exists
    if ($country > 0) {
        $country_check = mysqli_query($conn, "SELECT id FROM country WHERE id = '$country'");
        if (!$country_check || mysqli_num_rows($country_check) == 0) {
            echo '<script>
                showToast("Error!", "Please select a valid country", "danger");
                $("#country").addClass("is-invalid");
            </script>';
            exit();
        }
    }
    
    // Check if terms are accepted
    if ($terms != 'on') {
        echo '<script>
            showToast("Error!", "You must agree to the terms and conditions", "danger");
            $("#error_terms").show();
        </script>';
        exit();
    }
    
    // Check if email already exists
    $check_email_sql = "SELECT id FROM users WHERE email = '$email' LIMIT 1";
    $email_result = mysqli_query($conn, $check_email_sql);
    
    if ($email_result && mysqli_num_rows($email_result) > 0) {
        echo '<script>
            showToast("Error!", "Email address is already registered", "danger");
            $("[name=\'email\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Get country phonecode
    $country_code = '';
    if ($country > 0) {
        $country_query = mysqli_query($conn, "SELECT phonecode FROM country WHERE id = '$country'");
        if ($country_query && $country_row = mysqli_fetch_assoc($country_query)) {
            $country_code = $country_row['phonecode'];
        }
    }
    
    // Prepare full phone number with country code
    $full_phone = '+' . $country_code . $phone;
    
    // Check if phone already exists
    $check_phone_sql = "SELECT id FROM users WHERE phone = '$full_phone' LIMIT 1";
    $phone_result = mysqli_query($conn, $check_phone_sql);
    
    if ($phone_result && mysqli_num_rows($phone_result) > 0) {
        echo '<script>
            showToast("Error!", "Phone number is already registered", "danger");
            $("[name=\'phone\']").addClass("is-invalid");
        </script>';
        exit();
    }
    
    // Hash password (using md5 to match your login system)
    $hashed_password = md5($password);
    
    // Generate verification token - USING FALLBACK FUNCTION
    $verificationToken = generateSecureToken(32);
    $tokenExpires = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    // Handle referral code validation if provided
    $referrer_id = 0;
    if (!empty($referral_code)) {
        $ref_check_sql = "SELECT id FROM users WHERE referral_code = '$referral_code' AND status = 'active' LIMIT 1";
        $ref_result = mysqli_query($conn, $ref_check_sql);
        
        if ($ref_result && mysqli_num_rows($ref_result) > 0) {
            $ref_row = mysqli_fetch_assoc($ref_result);
            $referrer_id = $ref_row['id'];
        }
    }
    
    // Generate user's own referral code
    $user_referral_code = strtoupper(substr(md5(uniqid($email, true)), 0, 8));
    
    // Insert new user
    $current_time = date('Y-m-d H:i:s');
    $sql = "INSERT INTO users (
                email, 
                password, 
                first_name, 
                last_name, 
                phone, 
                country_code,
                country_id,
                date_of_birth,
                referral_code,
                referred_by,
                verification_token, 
                verification_token_expires, 
                email_verified,
                registration_date,
                status
            ) VALUES (
                '$email', 
                '$hashed_password', 
                '$first_name', 
                '$last_name', 
                '$full_phone',
                '$country_code',
                '$country',
                '$date_of_birth',
                '$user_referral_code',
                '$referrer_id',
                '$verificationToken', 
                '$tokenExpires', 
                0,
                '$current_time',
                'pending'
            )";
    
    $query = mysqli_query($conn, $sql);
    
    if ($query) {
        $user_id = mysqli_insert_id($conn);
        
        // Create verification link
        $verificationLink = $myUrl . "/verify-email.php?token=" . $verificationToken;
        
        // USER VERIFICATION EMAIL
        $mail_subject = "Verify Your Account - " . $sitename;
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . " " . $last_name . "</span>,</h2>
                            
                            <p class='message'>
                                Thank you for choosing <strong>" . $sitename . "</strong>. To activate your account and access all features, 
                                please verify your email address by clicking the button below.
                            </p>

                            <!-- Verification Section -->
                            <div class='verification-section'>
                                <div style='text-align: center;'>
                                    <a href='" . $verificationLink . "' class='verification-button'>
                                        Verify Email Address
                                    </a>
                                </div>
                            </div>

                            <!-- Alternative Link -->
                            <div class='link-alternative'>
                                <p style='margin-bottom: 10px; color: #6c757d; font-size: 13px;'>Or copy and paste this link in your browser:</p>
                                <a href='" . $verificationLink . "' class='verification-link'>" . $verificationLink . "</a>
                            </div>

                            <!-- Security Notice -->
                            <div class='security-notice'>
                                <div class='security-title'>🔒 Security Notice</div>
                                <div class='security-text'>
                                    For your security, please verify your email within the next hour. 
                                    This ensures your account remains secure and active.
                                </div>
                            </div>

                            <!-- Expiry Notice -->
                            <div class='expiry-notice'>
                                <div class='expiry-text'>⏰ This verification link expires in 1 hour</div>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Need assistance with your account?</p>
                                <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Our Support Team</a>
                            </div>

                            <p class='message' style='margin-bottom: 0; color: #6c757d; font-size: 14px;'>
                                If you didn't create an account with " . $sitename . ", please ignore this email. 
                                Your account will not be activated until you complete the verification process.
                            </p>
                        </div>"; 

        // Send user verification email
        require_once("../proccess/mail_sender.php");

        // ADMIN NOTIFICATION
        $admin_mail_subject = "New User Registration - " . $first_name . " " . $last_name;
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>New User Registration</h2>
                                
                                <p class='message'>
                                    A new user has registered on " . $sitename . " and requires verification.
                                </p>

                                <!-- User Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>User ID:</strong> #" . $user_id . "<br>
                                        <strong>Full Name:</strong> " . $first_name . " " . $last_name . "<br>
                                        <strong>Email:</strong> " . $email . "<br>
                                        <strong>Phone:</strong> " . $full_phone . "<br>
                                        <strong>Registration Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Status:</strong> <span style='color: #ffc107;'>Pending Verification</span>
                                    </div>
                                </div>

                                <!-- Action Required -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>Verification Required</h3>
                                    <p style='color: #6c757d;'>This user needs to:</p>
                                    <ul style='color: #6c757d;'>
                                        <li>Verify their email address</li>
                                        <li>Complete KYC verification</li>
                                        <li>Be approved by admin</li>
                                    </ul>
                                </div>

                                <!-- Admin Links -->
                                <div class='support-section'>
                                    <p class='support-text'>Manage this user:</p>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='support-link'>View User in Admin Panel</a>
                                </div>
                            </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");

        echo '<script>
            showToast("Success!", "Registration successful! Please check your email to verify your account.", "success");
            setTimeout(function() {
                window.location.href = "verify-email.php?reg=done";
            }, 3000);
        </script>';
        
    } else {
        echo '<script>
            showToast("Error!", "Registration failed: ' . mysqli_error($conn) . '", "danger");
        </script>';
    }
    
} else {
    echo '<script>
        showToast("Error!", "Invalid request method.", "danger");
    </script>';
}

mysqli_close($conn);
?>