<?php session_start();

?>
<!DOCTYPE html>
<html lang="en">


<?php include("includes/head.php")?>

<?php 

// Check if user is already logged in
if(isset($_SESSION['user_id'])) {
    //header("Location: dashboard.php");
}

$referrer_id = '';


if(isset($_GET['ref'])) {
$referrer_id = $_GET['ref'];
    
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account - AI Trading Platform</title>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Select2 CSS for searchable dropdown -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <style>
        .error-message {
            color: #dc3545;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }
        .is-invalid {
            border-color: #dc3545 !important;
        }
        .is-valid {
            border-color: #28a745 !important;
        }
        #btnSpinner {
            display: none;
        }
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1055;
        }
        .toast {
            min-width: 300px;
        }
        .input-group-text {
            cursor: pointer;
        }
        .text--base {
            color: #0d6efd !important;
        }
        .btn--base {
            background-color: #0d6efd;
            color: white;
            border: none;
        }
        .btn--base:hover {
            background-color: #0b5ed7;
            color: white;
        }
        
        /* Select2 custom styles */
        .select2-container--default .select2-selection--single {
            height: 45px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 8px;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 28px;
            padding-left: 0;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 43px;
        }
        .select2-container--default .select2-search--dropdown .select2-search__field {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 6px;
        }
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #0d6efd;
        }
        .select2-container--default .select2-results__option[aria-selected=true] {
            background-color: #e9ecef;
        }
        .country-option {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .country-name {
            flex-grow: 1;
        }
        .country-code {
            background-color: #e9ecef;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: #495057;
        }
        .phone-input-group {
            display: flex;
        }
        .country-code-display {
            min-width: 80px;
            background-color: #e9ecef;
            border: 1px solid #ced4da;
            border-right: none;
            border-radius: 4px 0 0 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 10px;
            font-weight: 500;
            color: #000;
        }
        .loading-spinner {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
        }
        .select2-results__options{
            background-color: #000 !important;
        }

        .selection {
            width: 100%;
        }
        
    </style>
</head>
<body>

    <!--==========================   Preloader Start  ==========================-->
    
    <!--==========================  Preloader End  ==========================-->

    <div class="wrapper">
        <!--==========================   Header Start  ==========================-->
            <?php include("includes/header.php") ?>

        <!--==========================  Header End  ==========================-->
       
       <main>
            <div class="login-section bg--black-two">
                <div class="container">
                    <div class="row justify-content-center">
                        <div class="col-lg-12 col-xl-10">
                            <div class="login-content-box">
                                <div class="login-img-box order-lg-1">
                                    <div class="text-center">
                                        <span>Start AI Trading</span>
                                        <h3>Create Your Account</h3>
                                        <p class="mt-3">No trading knowledge needed. Our AI bots handle everything automatically.</p>
                                        <a href="index.php" class="btn btn--base mt-4">
                                            Back To Home
                                            <i class="flaticon-arrow-upper-right"></i>
                                        </a>
                                    </div>
                                </div>
                                
                                <form id="registrationForm" method="POST">
                                    <div id="responseMessage"></div>
                                    <div id="result"></div>
                                    
                                    <div class="row row-gap-4">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" name="first_name" placeholder="First Name*" required>
                                            <div class="error-message" id="error_first_name"></div>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" name="last_name" placeholder="Last Name*" required>
                                            <div class="error-message" id="error_last_name"></div>
                                        </div>
                                        
                                        <div class="col-12 position-relative">
                                            <input type="email" class="form-control" name="email" id="email" placeholder="Email Address*" required>
                                            <div class="loading-spinner" id="emailSpinner">
                                                <i class="fas fa-spinner fa-spin text-primary"></i>
                                            </div>
                                            <div class="error-message" id="error_email"></div>
                                        </div>
                                        
                                        <!-- Country Selection with Search -->
                                        <div class="col-md-6 form-control">
                                            <select class=" select2-country form-control"  name="country" id="country" required>
                                                <option value="">Select Country*</option>
                                                <?php
                                                if(isset($conn)) {
                                                    $countries_query = mysqli_query($conn, "SELECT * FROM country ORDER BY name ASC");
                                                    if($countries_query) {
                                                        while($country = mysqli_fetch_assoc($countries_query)) {
                                                            echo '<option value="' . $country['id'] . '" data-phonecode="' . $country['phonecode'] . '">' 
                                                                . htmlspecialchars($country['name']) . ' (+' . $country['phonecode'] . ')</option>';
                                                        }
                                                    }
                                                }
                                                ?>
                                            </select>
                                            <div class="error-message" id="error_country"></div>
                                        </div>
                                        
                                        <!-- Phone Number with Country Code -->
                                        <div class="col-12">
                                            <div class="phone-input-group">
                                                <div class="country-code-display" id="countryCodeDisplay">+</div>
                                                <input type="tel" class="form-control" name="phone" id="phone" placeholder="Phone Number*" required style="border-radius: 0 4px 4px 0;">
                                            </div>
                                            <div class="error-message" id="error_phone"></div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <input type="date" class="form-control" name="date_of_birth" placeholder="Date of Birth*" required>
                                            <div class="error-message" id="error_date_of_birth"></div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <div class="input-group">
                                                <input type="password" class="form-control" name="password" id="password" placeholder="Password*" required>
                                                <button class="btn btn-outline--base" type="button" id="togglePassword">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                            <div class="error-message" id="error_password"></div>
                                            <small class="text-muted">Minimum 8 characters with letters and numbers</small>
                                        </div>
                                        <div class="col-12">
                                            <div class="input-group">
                                                <input type="password" class="form-control" name="confirm_password" id="confirm_password" placeholder="Confirm Password*" required>
                                                <button class="btn btn-outline--base" type="button" id="toggleConfirmPassword">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                            <div class="error-message" id="error_confirm_password"></div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <input type="text" class="form-control" name="referral_code" placeholder="Referral Code (Optional)" value="<?php echo $referrer_id ?>">
                                            <div class="error-message" id="error_referral_code"></div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                                                <label class="form-check-label" for="terms">
                                                    I agree to the <a href="terms.php" class="text--base">Terms & Conditions</a> and <a href="privacy.php" class="text--base">Privacy Policy</a>
                                                </label>
                                                <div class="error-message" id="error_terms"></div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-12">
                                            <div class="submit-button">
                                                <button type="submit" class="btn btn--base-two w-100" id="submitBtn">
                                                    <span id="btnText">Create Account</span>
                                                    <span id="btnSpinner">
                                                        <i class="fas fa-spinner fa-spin"></i> Processing...
                                                    </span>
                                                    <i class="flaticon-arrow-upper-right"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="or-form py-4">
                                        <span>Already have an account?</span>
                                    </div>
                                    
                                    <div class="text-center pb-4">
                                        <a href="login.php" class="btn btn-outline--base">
                                            <i class="fas fa-sign-in-alt me-2"></i>
                                            Login to Your Account
                                        </a>
                                    </div>
                                    
                                    <p class="text-center small mt-3">
                                        By registering, you confirm you're 18+ and agree to our AI trading platform terms. 
                                        All trading is automated by AI bots.
                                    </p>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        
        <?php include("includes/footer.php") ?>
    </div>
    
    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container"></div>
    
   <!-- Jquery js -->
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   
   <!-- Select2 JS -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
   
   <!-- Bootstrap Bundle JS -->
   <script src="assets/js/boostrap.bundle.min.js"></script>
   
   <!-- gsap Js -->
   <script src="assets/js/gsap.min.js"></script>
   <script src="assets/js/ScrollTrigger.js"></script>
   <!-- Scroll Reveal Js -->
   <script src="assets/js/scrollreveal.min.js"></script>
   <!-- Swiper Bundle Js -->
   <script src="assets/js/swiper-bundle.min.js"></script>
   <!-- Fancy Box js -->
   <script src="assets/js/fancybox.umd.js"></script>
   <!-- Odometer js -->
   <script src="assets/js/odometer.min.js"></script>

   <!-- main js -->
   <script src="assets/js/main.js"></script>

    
    <script>
    $(document).ready(function(){
        $("#registrationForm").submit(function(event){
            // Stop form from submitting normally
            event.preventDefault();
            $("#pageloader").show();
            
            // Clear previous errors
            $('.error-message').hide().text('');
            $('.is-invalid').removeClass('is-invalid');
            $('.is-valid').removeClass('is-valid');
            
            /* Serialize the submitted form control values to be sent to the web server with the request */
            var formValues = $(this).serialize();
            
            // Send the form data using post
            $.post("proccess/register.php", formValues, function(data){
                // Display the returned data in browser
                $("#result").html(data);
                $("#pageloader").hide();
            });
        });
    });
</script>
    <script>
        $(document).ready(function(){
            // Initialize Select2 for country dropdown
            $('.select2-country').select2({
                placeholder: "Select Country*",
                allowClear: true,
                width: '100%',
                templateResult: formatCountryOption,
                templateSelection: formatCountrySelection
            });
            
            // Function to format country option in dropdown
            function formatCountryOption(country) {
                if (!country.id) { return country.text; }
                
                // Extract country name and code
                var text = country.text;
                var countryName = text.replace(/\(\+\d+\)/, '').trim();
                var phoneCode = text.match(/\((\+\d+)\)/);
                phoneCode = phoneCode ? phoneCode[1] : '';
                
                var $option = $(
                    '<div class="country-option">' +
                        '<span class="country-name">' + countryName + '</span>' +
                        '<span class="country-code">' + phoneCode + '</span>' +
                    '</div>'
                );
                return $option;
            }
            
            // Function to format selected country
            function formatCountrySelection(country) {
                if (!country.id) { return country.text; }
                return country.text.replace(/\(\+\d+\)/, '').trim();
            }
            
            // Update country code display when country is selected
            $('#country').on('change', function() {
                var selectedOption = $(this).find('option:selected');
                var phoneCode = selectedOption.data('phonecode') || '';
                
                if (phoneCode) {
                    $('#countryCodeDisplay').text('+' + phoneCode);
                } else {
                    $('#countryCodeDisplay').text('+');
                }
            });
            
            // Email existence check with debounce
            var emailCheckTimeout;
            $('#email').on('keyup', function() {
                clearTimeout(emailCheckTimeout);
                var email = $(this).val().trim();
                
                if (email && validateEmailFormat(email)) {
                    $('#emailSpinner').show();
                    
                    emailCheckTimeout = setTimeout(function() {
                        checkEmailExists(email);
                    }, 800); // 800ms debounce
                } else {
                    $('#emailSpinner').hide();
                }
            });
            
            
            
            // Real-time validations
            $('input[required]').on('blur', function() {
                validateRequiredField($(this));
            });
            
            // Email validation
            $('input[name="email"]').on('blur', function() {
                validateEmailField($(this));
            });
            
            // Password validation
            $('input[name="password"], input[name="confirm_password"]').on('keyup', function() {
                validatePasswordMatch();
            });
            
            // Terms checkbox validation
            $('#terms').on('change', function() {
                validateTermsCheckbox($(this));
            });
            
            // Password visibility toggle
            $('#togglePassword').on('click', function() {
                togglePasswordVisibility('password', $(this));
            });
            
            $('#toggleConfirmPassword').on('click', function() {
                togglePasswordVisibility('confirm_password', $(this));
            });
        });
        
        // Function to check if email already exists
        function checkEmailExists(email) {
            $.ajax({
                url: 'proccess/check-email.php',
                type: 'POST',
                data: { email: email },
                dataType: 'json',
                success: function(response) {
                    $('#emailSpinner').hide();
                    
                    if (response.exists) {
                        $('#email').addClass('is-invalid');
                        $('#error_email').text('Email address is already registered').show();
                    } else {
                        $('#email').removeClass('is-invalid');
                        $('#error_email').hide();
                        if ($('#email').val().trim()) {
                            $('#email').addClass('is-valid');
                        }
                    }
                },
                error: function() {
                    $('#emailSpinner').hide();
                }
            });
        }
        
        function validateForm() {
            let isValid = true;
            
            // Clear previous errors
            $('.error-message').hide().text('');
            $('.is-invalid').removeClass('is-invalid');
            $('.is-valid').removeClass('is-valid');
            
            // Check required fields
            $('input[required], select[required]').each(function() {
                if (!validateRequiredField($(this))) {
                    isValid = false;
                }
            });
            
            // Validate email
            const emailField = $('#email');
            if (!validateEmailField(emailField)) {
                isValid = false;
            }
            
            // Validate password
            const passwordField = $('input[name="password"]');
            if (!validatePasswordStrength(passwordField)) {
                isValid = false;
            }
            
            // Validate password match
            if (!validatePasswordMatch()) {
                isValid = false;
            }
            
            // Validate phone number
            if (!validatePhoneNumber()) {
                isValid = false;
            }
            
            // Check terms agreement
            const termsCheckbox = $('#terms');
            if (!validateTermsCheckbox(termsCheckbox)) {
                isValid = false;
            }
            
            return isValid;
        }
        
        function validateRequiredField(field) {
            const value = field.val() ? field.val().trim() : '';
            if (!value) {
                const fieldName = field.attr('name');
                field.addClass('is-invalid');
                $('#error_' + fieldName).text('This field is required').show();
                return false;
            }
            return true;
        }
        
        function validateEmailFormat(email) {
            const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        }
        
        function validateEmailField(field) {
            const email = field.val().trim();
            
            if (!email) {
                field.addClass('is-invalid');
                $('#error_email').text('Email is required').show();
                return false;
            } else if (!validateEmailFormat(email)) {
                field.addClass('is-invalid');
                $('#error_email').text('Please enter a valid email address').show();
                return false;
            }
            return true;
        }
        
        function validatePhoneNumber() {
            const phone = $('#phone').val().trim();
            const countryCode = $('#countryCodeDisplay').text().replace('+', '');
            
            if (!phone) {
                $('#phone').addClass('is-invalid');
                $('#error_phone').text('Phone number is required').show();
                return false;
            }
            
            // Basic phone validation
            const phoneRegex = /^[0-9]{6,15}$/;
            if (!phoneRegex.test(phone)) {
                $('#phone').addClass('is-invalid');
                $('#error_phone').text('Please enter a valid phone number (6-15 digits)').show();
                return false;
            }
            
            return true;
        }
        
        function validatePasswordStrength(field) {
            const password = field.val();
            const minLength = 8;
            const hasLetter = /[a-zA-Z]/.test(password);
            const hasNumber = /\d/.test(password);
            
            if (password.length < minLength) {
                field.addClass('is-invalid');
                $('#error_password').text('Password must be at least 8 characters').show();
                return false;
            } else if (!hasLetter || !hasNumber) {
                field.addClass('is-invalid');
                $('#error_password').text('Password must contain both letters and numbers').show();
                return false;
            }
            return true;
        }
        
        function validatePasswordMatch() {
            const password = $('input[name="password"]').val();
            const confirmPassword = $('input[name="confirm_password"]').val();
            const confirmField = $('input[name="confirm_password"]');
            
            if (password && confirmPassword && password !== confirmPassword) {
                confirmField.addClass('is-invalid');
                $('#error_confirm_password').text('Passwords do not match').show();
                return false;
            } else if (password && confirmPassword && password === confirmPassword) {
                confirmField.removeClass('is-invalid');
                confirmField.addClass('is-valid');
                return true;
            }
            return true;
        }
        
        function validateTermsCheckbox(checkbox) {
            if (!checkbox.is(':checked')) {
                $('#error_terms').text('You must agree to the terms and conditions').show();
                return false;
            }
            return true;
        }
        
        function togglePasswordVisibility(fieldName, button) {
            const field = $('input[name="' + fieldName + '"]');
            const icon = button.find('i');
            
            if (field.attr('type') === 'password') {
                field.attr('type', 'text');
                icon.removeClass('fa-eye');
                icon.addClass('fa-eye-slash');
            } else {
                field.attr('type', 'password');
                icon.removeClass('fa-eye-slash');
                icon.addClass('fa-eye');
            }
        }
        
        function showToast(title, message, type = 'info') {
            // Remove existing toasts
            $('.toast').remove();
            
            const toastEl = document.createElement('div');
            toastEl.className = `toast align-items-center text-bg-${type} border-0`;
            toastEl.setAttribute('role', 'alert');
            toastEl.setAttribute('aria-live', 'assertive');
            toastEl.setAttribute('aria-atomic', 'true');

            toastEl.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <strong>${title}</strong><br>${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            `;

            document.getElementById('toastContainer').appendChild(toastEl);
            const toast = new bootstrap.Toast(toastEl, { delay: 5000 });
            toast.show();
            toastEl.addEventListener('hidden.bs.toast', () => toastEl.remove());
        }
    </script>
</body>
</html>