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

// Initialize variables
$error_messages = [];
$success_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get and sanitize form data
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = $_POST['password'];
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
    $last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
    $confirm_password = $_POST['confirm_password'];
    $hashed_password = md5($password); 

    // Validate passwords match
    if ($password !== $confirm_password) {
        $error_messages[] = "Passwords do not match";
    }
    
    // Validate password length
    if (strlen($password) < 6) {
        $error_messages[] = "Password must be at least 6 characters long";
    }
    
    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_messages[] = "Invalid email format";
    }
    
    // Validate required fields
    $required_fields = [
        'email' => 'Email', 
        'first_name' => 'First Name',
        'last_name' => 'Last Name',
    ];
    
    foreach ($required_fields as $field => $name) {
        if (empty($_POST[$field])) {
            $error_messages[] = "$name is required";
        }
    }

    // If no validation errors, check for existing user
    if (empty($error_messages)) {
        $check_sql = "SELECT id FROM users WHERE email = '$email' OR phone = '$phone'";
        $result = mysqli_query($conn, $check_sql);
        
        if (mysqli_num_rows($result) > 0) {
            $error_messages[] = "User already exists with this Email or Phone Number";
        }
    }

    // If still no errors, proceed with registration
    if (empty($error_messages)) {
        // Handle referral code - if empty, set to NULL
        $referral_code_value = (!empty($referral_code)) ? "'$referral_code'" : "NULL";
        
        // Generate verification token
        $new_token = bin2hex(random_bytes(32)); // Generate secure token
        $verificationToken = $new_token;
        $tokenExpires = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $verificationLink = $myUrl."/verify-email.php?token=" . $verificationToken;

        // Insert new user
        $sql = "INSERT INTO users (email, password, first_name, last_name, phone, referral_code, verification_completed, verification_token, verification_token_expires, email_verified, registration_complete, status) 
                VALUES ('$email', '$hashed_password', '$first_name', '$last_name', '$phone', $referral_code_value, 0, '$verificationToken', '$tokenExpires', 0, 'false','pending')";
        $query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
        
        if ($query) {
            $user_id = mysqli_insert_id($conn);

            // 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 - New User Registration
            $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> " . $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");

            $success_message = "Registration successful! Please check your email to verify your account. You will be redirected to login shortly.";
            
            // Set session variable for success message
            $_SESSION['registration_success'] = $success_message;
            
            // Redirect to verification page
            echo '<script>
                setTimeout(function() {
                    window.location.href = "verify-email.php?reg=done";
                }, 3000);
            </script>';
            
        } else {
            $error_messages[] = "Registration failed: " . mysqli_error($conn);
        }
    }

    mysqli_close($conn);
}

// Display errors and success messages
if (!empty($error_messages)) {
    foreach ($error_messages as $error) {
        echo '<script>
            showToast("Error!", "' . addslashes($error) . '", "danger");
        </script>';
    }
}

if (!empty($success_message)) {
    echo '<script>
        showToast("Success!", "' . addslashes($success_message) . '", "success");
    </script>';
}
?>