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

// Check registration status
checkRegisterStatus();

$R = '';
if (!empty($_GET['ref'])) {
    $R = base64_decode(mysqli_real_escape_string($tng_conn, $_GET['ref']));
}

$domain = $_SERVER['SERVER_NAME'];

function processRegistration($P, $tng_conn, $R, $domain) {
    $N   = mysqli_real_escape_string($tng_conn, $P['name']);
    $E   = mysqli_real_escape_string($tng_conn, $P['email']);
    $M   = mysqli_real_escape_string($tng_conn, $P['phone']);
    $T   = mysqli_real_escape_string($tng_conn, $P['usertype']);
    $PW  = $P['password'];
    $CPW = $P['cpassword'];

    // Phone number validation
    $normalizedPhone = preg_replace('/\D+/', '', $M);
    if (!preg_match('/^[6-9][0-9]{9}$/', $normalizedPhone)) {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Invalid Mobile", "Please enter a valid 10-digit mobile number", "error");
            });
        </script>';
        return false;
    }
    $M = $normalizedPhone;

    // Prevent admin registration
    if (strtolower($T) == "admin") {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Oops!", "You cannot register as ADMIN!", "error");
            });
        </script>';
        return false;
    }

    // Check if user already exists
    if (mysqli_num_rows(mysqli_query($tng_conn, "SELECT id FROM users WHERE phone='$M' OR email='$E'")) > 0) {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Oops!", "Email or Phone already exists!", "error");
            });
        </script>';
        return false;
    }

    // Password match check
    if ($PW !== $CPW) {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Oops!", "Password and Confirm Password do not match!", "error");
            });
        </script>';
        return false;
    }

    // Check OTP system setting from database
    $otp_system_setting = XyZ_val('otp_option');
    
    // If OTP system is enabled in admin panel
    if (strtolower($otp_system_setting) == "yes") {
        // Generate OTP
        $O = rand(100000, 999999);
        $_SESSION['s_otp']  = $O;
        $_SESSION['s_data'] = [
            'n' => $N, 
            'e' => $E, 
            'p' => $M, 
            't' => $T, 
            'r' => $R, 
            'pw' => $PW
        ];
        $_SESSION['otp_time'] = time();

        $msg = "🔑 Hello $N!\n\nYour OTP for registration is: $O\n\n⏱️ It is valid for 5 minutes only.\n\n🌐 Login at: $domain";
        $ftr = strtoupper($_SERVER['SERVER_NAME']);
        
        // Send WhatsApp message
        if(function_exists('sendWhatsAppMessage')) {
            sendWhatsAppMessage($M, $msg, $ftr);
        }
        
        // Send email
        if(function_exists('sendregisterOtpEmail')) {
            sendregisterOtpEmail($E, $N, $O, $domain);
        }

        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire({
                    title: "OTP Sent!",
                    html: "Enter OTP sent to your phone and email:",
                    input: "text",
                    inputLabel: "6-digit OTP",
                    inputPlaceholder: "Enter OTP",
                    confirmButtonText: "Verify",
                    showCancelButton: true,
                    allowOutsideClick: false,
                    inputValidator: (value) => {
                        if (!value) {
                            return "Please enter OTP";
                        }
                        if (value.length !== 6) {
                            return "OTP must be 6 digits";
                        }
                    }
                }).then((result) => {
                    if (result.isConfirmed) {
                        const form = document.createElement("form");
                        form.method = "POST";
                        form.action = "";
                        
                        const otpInput = document.createElement("input");
                        otpInput.type = "hidden";
                        otpInput.name = "v_otp";
                        otpInput.value = result.value;
                        
                        form.appendChild(otpInput);
                        document.body.appendChild(form);
                        form.submit();
                    }
                });
            });
        </script>';
        return true;
        
    } else {
        // OTP system disabled - Direct registration
        return directRegistration($N, $E, $M, $T, $PW, $R, $domain, $tng_conn);
    }
}

function directRegistration($N, $E, $M, $T, $PW, $R, $domain, $tng_conn) {
    $VP = password_hash($PW, PASSWORD_DEFAULT);
    $oid = "TNG_" . rand(100000, 999999);
    $dt  = date("Y-m-d H:i:s");
    $payment_status = XyZ_val('payment_status');

    $q = "INSERT INTO `users` (`name`, `phone`, `email`, `password`, `type`, `status`, `referred_by`, `order_id`, `date`, `otp_system`) 
          VALUES ('$N', '$M', '$E', '$VP', '$T', '$payment_status', '$R', '$oid', '$dt', 'no')";
    $res = mysqli_query($tng_conn, $q);

    // Handle referral
    if ($R != '') {
        $ref_bal = "0";
        mysqli_query($tng_conn, "INSERT INTO referal (`phone`, `referred_by`, `txn_no`, `referral_balance`, `status`) 
            VALUES ('$M', '$R', 'REF" . rand(10000, 99999) . "', '$ref_bal', '1')");
    }

    if ($res) {
        $msg2 = "🎉 Welcome, $N! ✅ Your account has been successfully created.\n\n"
               . "👤 Name: $N\n"
               . "🆔 ID/Phone: $M\n"
               . "🔑 Password: $PW\n"
               . "🌐 Login here: $domain\n\n"
               . "🚀 Enjoy our services!";

        $ftr = strtoupper($_SERVER['SERVER_NAME']);
        
        if(function_exists('sendWhatsAppMessage')) {
            sendWhatsAppMessage($M, $msg2, $ftr);
        }
        
        if(function_exists('sendRegistrationEmail')) {
            sendRegistrationEmail($E, $N, $M, $PW, $domain);
        }

        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire({
                    title: "Success!",
                    html: "Account created successfully!<br><br>Phone/ID: <b>' . $M . '</b><br>Password: <b>' . $PW . '</b>",
                    icon: "success",
                    confirmButtonText: "Login Now"
                }).then(() => {
                    window.location.href = "login.php";
                });
            });
        </script>';
        return true;
    } else {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Error!", "Something went wrong! Please try again.", "error");
            });
        </script>';
        return false;
    }
}

// Handle form submission
if (!empty($_POST['phone']) && !isset($_POST['v_otp'])) {
    processRegistration($_POST, $tng_conn, $R, $domain);
}

// Handle OTP verification
if (!empty($_POST['v_otp'])) {
    $V = mysqli_real_escape_string($tng_conn, $_POST['v_otp']);
    
    // Check if OTP is valid and not expired (5 minutes)
    if (isset($_SESSION['s_otp']) && $V == $_SESSION['s_otp'] && (time() - $_SESSION['otp_time']) < 300) {
        $D = $_SESSION['s_data'];
        
        $VP = password_hash($D['pw'], PASSWORD_DEFAULT);
        $oid = "TNG_" . rand(100000, 999999);
        $dt = date("Y-m-d H:i:s");
        $payment_status = XyZ_val('payment_status');

        // Insert user with OTP system enabled
        $res = mysqli_query($tng_conn, "INSERT INTO `users` (`name`, `phone`, `email`, `password`, `type`, `status`, `referred_by`, `order_id`, `date`, `otp_system`) 
                 VALUES ('" . $D['n'] . "', '" . $D['p'] . "', '" . $D['e'] . "', '$VP', '" . $D['t'] . "', '$payment_status', '" . $D['r'] . "', '$oid', '$dt', 'yes')");

        // Handle referral
        if ($D['r'] != '') {
            $ref_bal = "0";
            mysqli_query($tng_conn, "INSERT INTO referal (`phone`, `referred_by`, `txn_no`, `referral_balance`, `status`) 
                VALUES ('" . $D['p'] . "', '" . $D['r'] . "', 'REF" . rand(10000, 99999) . "', '$ref_bal', '1')");
        }

        if ($res) {
            $msg2 = "🥳 Hey " . $D['n'] . "! Your account is ready to use.\n\n"
                   . "📲 ID: " . $D['p'] . "\n"
                   . "🔐 Password: " . $D['pw'] . "\n"
                   . "🌍 Login at: $domain\n\n"
                   . "💡 Keep your credentials safe!";
            
            $ftr = strtoupper($_SERVER['SERVER_NAME']);
            
            if(function_exists('sendWhatsAppMessage')) {
                sendWhatsAppMessage($D['p'], $msg2, $ftr);
            }
            
            if(function_exists('sendRegistrationEmail')) {
                sendRegistrationEmail($D['e'], $D['n'], $D['p'], $D['pw'], $domain);
            }

            echo '<script>
                document.addEventListener("DOMContentLoaded", function(){
                    Swal.fire({
                        title: "Success!",
                        text: "Account created successfully!",
                        icon: "success",
                        confirmButtonText: "Login Now"
                    }).then(() => {
                        window.location.href = "login.php";
                    });
                });
            </script>';
        } else {
            echo '<script>
                document.addEventListener("DOMContentLoaded", function(){
                    Swal.fire("Error!", "Something went wrong! Please try again.", "error");
                });
            </script>';
        }
        
        // Clear session data
        unset($_SESSION['s_otp'], $_SESSION['s_data'], $_SESSION['otp_time']);
    } else {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function(){
                Swal.fire("Invalid OTP", "Entered OTP is incorrect or expired.", "error");
            });
        </script>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="./template/tngweb/assets/images/favicon-32x32.png" type="image/png" />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.14/dist/sweetalert2.all.min.js"></script>
    <script disable-devtool-auto src='https://cdn.jsdelivr.net/npm/disable-devtool@latest'></script>
    <title><?php echo XyZ_val('brand'); ?> | <?php echo XyZ_val('title'); ?></title>
    <link href="./template/tngweb/assets/css/register-style.css" rel="stylesheet">
    
</head>

<body>
    <!-- Alert Container for PHP messages -->
    <?php if (isset($show_alert) && $show_alert): ?>
    <div class="alert-container">
        <div class="alert alert-<?php echo $alert_type; ?>">
            <?php echo $alert_message; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Navigation -->
    <nav class="navbar">
        <div class="nav-container">
            <a href="index.php" class="logo">
                <img src="<?php echo XyZ_val('logo'); ?>" alt="Logo">
                <?php echo XyZ_val('brand'); ?>
            </a>
            
            <button class="mobile-toggle" id="mobileToggle">
                <i class='bx bx-menu'></i>
            </button>
            
            <ul class="nav-links" id="navLinks">
                <li><a href="index.php">Home</a></li>
                <li><a href="register.php" class="active">Register</a></li>
                <li><a href="Forgot-password.php">Forgot Password</a></li>
                <li><a href="contact.php">Contact</a></li>
            </ul>
        </div>
    </nav>

    <!-- Registration Content -->
    <div class="register-container">
        <div class="register-card">
            <div class="register-header">
                <h1>Create Account</h1>
                <p>Join us and start your journey</p>
            </div>
            
            <div class="register-body">
                <form method="POST" action="" id="registerForm">
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label for="inputFirstName" class="form-label">Full Name *</label>
                                <input required name="name" type="text" class="form-control" id="inputFirstName" placeholder="Enter Your Name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label for="inputLastName" class="form-label">Phone *</label>
                                <input required maxlength="10" name="phone" type="text" class="form-control" id="inputLastName" placeholder="Phone Number" value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="inputEmailAddress" class="form-label">Email Address *</label>
                        <input required name="email" type="email" class="form-control" id="inputEmailAddress" placeholder="example@user.com" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="inputSelectCountry" class="form-label">User Type *</label>
                        <select required name="usertype" class="form-select" id="inputSelectCountry">
                            <option value="">Please Select</option>
                            <option value="retailer" <?php echo (isset($_POST['usertype']) && $_POST['usertype'] == 'retailer') ? 'selected' : ''; ?>>Retailer</option>
                            <option value="distributor" <?php echo (isset($_POST['usertype']) && $_POST['usertype'] == 'distributor') ? 'selected' : ''; ?>>Distributor</option>
                        </select>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label for="inputChoosePassword" class="form-label">Password *</label>
                                <div class="password-input">
                                    <input required name="password" type="password" class="form-control" id="inputChoosePassword" placeholder="Enter Password">
                                    <button type="button" class="toggle-password" data-target="inputChoosePassword">
                                        <i class='bx bx-hide'></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label for="inputConfirmPassword" class="form-label">Confirm Password *</label>
                                <div class="password-input">
                                    <input required name="cpassword" type="password" class="form-control" id="inputConfirmPassword" placeholder="Confirm Password">
                                    <button type="button" class="toggle-password" data-target="inputConfirmPassword">
                                        <i class='bx bx-hide'></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="register-btn" id="submitBtn">
                        <i class='bx bx-user'></i> Create Account
                    </button>
                    
                    <div class="login-link">
                        Already have an account? <a href="login.php">Login Here</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> <?php echo strtoupper($_SERVER['SERVER_NAME']); ?>. All rights reserved.</p>
        </div>
    </footer>

    <script>
        // Mobile menu toggle
        document.getElementById('mobileToggle').addEventListener('click', function() {
            document.getElementById('navLinks').classList.toggle('active');
        });
        
        // Password visibility toggle
        document.querySelectorAll('.toggle-password').forEach(button => {
            button.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const passwordInput = document.getElementById(targetId);
                const icon = this.querySelector('i');
                
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    icon.classList.remove('bx-hide');
                    icon.classList.add('bx-show');
                } else {
                    passwordInput.type = 'password';
                    icon.classList.remove('bx-show');
                    icon.classList.add('bx-hide');
                }
            });
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(event) {
            const navLinks = document.getElementById('navLinks');
            const mobileToggle = document.getElementById('mobileToggle');
            
            if (!mobileToggle.contains(event.target) && !navLinks.contains(event.target)) {
                navLinks.classList.remove('active');
            }
        });
        
        // Phone number validation (only numbers)
        document.getElementById('inputLastName').addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        
        // Form submission handling
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i> Creating Account...';
            submitBtn.disabled = true;
            
            // Allow form to submit normally
        });
        
        // Auto-hide alerts after 5 seconds
        window.addEventListener('load', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.animation = 'slideIn 0.3s ease reverse';
                    setTimeout(() => {
                        alert.style.display = 'none';
                    }, 300);
                }, 5000);
            });
        });
    </script>
</body>
</html>