<?php
// register.php
// Complete registration page — single-file. Replace your existing file with this.

include "auth/config.php"; // expects $conn (mysqli)
include 'auth/function.php'; // expects sendNotification(), generateReferralCode() optional

// ---------------------------------------------
// Helper: generateRandomInstanceId (PHP 7.x compatible)
// ---------------------------------------------
function generateRandomInstanceId($length = 16) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = 'I'; // Fixed 'I' as first character

    if ($length < 10) $length = 16;

    for ($i = 1; $i < $length - 6; $i++) {
        $randomString .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    $currentTime = time();
    $lastSixDigits = substr(strval($currentTime), -6);
    $randint = mt_rand(100, 900);

    return $randomString . $randint . $lastSixDigits;
}

// ---------------------------------------------
// reCAPTCHA verify with curl fallback
// ---------------------------------------------
function verifyRecaptcha($secretKey, $responseKey, $remoteip = null) {
    $verifyURL = "https://www.google.com/recaptcha/api/siteverify";
    $data = array(
        'secret' => $secretKey,
        'response' => $responseKey
    );
    if ($remoteip) $data['remoteip'] = $remoteip;

    // Try curl
    if (function_exists('curl_version')) {
        $ch = curl_init($verifyURL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $response = curl_exec($ch);
        curl_close($ch);
    } else {
        // fallback to file_get_contents
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
                'timeout' => 10
            )
        );
        $context  = stream_context_create($options);
        $response = @file_get_contents($verifyURL, false, $context);
    }

    if (!$response) return false;
    $responseData = json_decode($response);
    return ($responseData && isset($responseData->success) && $responseData->success === true);
}

// ---------------------------------------------
// Validate DB connection
// ---------------------------------------------
if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection error. Please check auth/config.php");
}

// ---------------------------------------------
// Handle AJAX & FORM POSTS
// ---------------------------------------------
if ($_SERVER["REQUEST_METHOD"] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    // Utility to check a single column
    function check_exists($conn, $col, $value) {
        $sql = "SELECT COUNT(*) AS cnt FROM users WHERE {$col} = ?";
        $stmt = $conn->prepare($sql);
        if (!$stmt) return array('error' => true, 'msg' => $conn->error);
        $stmt->bind_param("s", $value);
        $stmt->execute();
        $stmt->bind_result($cnt);
        $stmt->fetch();
        $stmt->close();
        return array('error' => false, 'exists' => ($cnt > 0));
    }

    if (isset($_POST['checkMobile'])) {
        $mobile = trim($_POST['mobile']);
        $res = check_exists($conn, 'mobile', $mobile);
        echo json_encode(array('exists' => !$res['error'] && $res['exists']));
        exit;
    }

    if (isset($_POST['checkEmail'])) {
        $email = trim($_POST['email']);
        $res = check_exists($conn, 'email', $email);
        echo json_encode(array('exists' => !$res['error'] && $res['exists']));
        exit;
    }

    if (isset($_POST['checkAadhaar'])) {
        $aadhaar = trim($_POST['aadhaar']);
        $res = check_exists($conn, 'aadhaar', $aadhaar);
        echo json_encode(array('exists' => !$res['error'] && $res['exists']));
        exit;
    }

    if (isset($_POST['checkPAN'])) {
        $pan = trim($_POST['pan']);
        $res = check_exists($conn, 'pan', $pan);
        echo json_encode(array('exists' => !$res['error'] && $res['exists']));
        exit;
    }

    // Registration flow
    if (isset($_POST['create'])) {
        // basic sanitization
        $name = isset($_POST['name']) ? trim($_POST['name']) : '';
        $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        $company = isset($_POST['company']) ? trim($_POST['company']) : '';
        $pin = isset($_POST['pin']) ? trim($_POST['pin']) : '';
        $pan = isset($_POST['pan']) ? strtoupper(trim($_POST['pan'])) : '';
        $aadhaar = isset($_POST['aadhaar']) ? trim($_POST['aadhaar']) : '';
        $location = isset($_POST['location']) ? trim($_POST['location']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $use_referral = isset($_POST['use_referral']) ? true : false;
        $referralCodeInput = isset($_POST['referral_code']) ? trim($_POST['referral_code']) : '';

        // server-side minimal validation
        if (empty($name) || empty($mobile) || empty($email) || empty($password)) {
            echo json_encode(array('status' => 'error', 'msg' => 'Required fields missing'));
            exit;
        }

        // reCAPTCHA verify
        $secretKey = "6Lc6OuwrAAAAAKAm3OOToQquhdnSfN94NzgO6y74";
        $responseKey = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : '';
        $userIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;

        if (!verifyRecaptcha($secretKey, $responseKey, $userIP)) {
            echo json_encode(array('status' => 'error', 'msg' => 'reCAPTCHA verification failed'));
            exit;
        }

        // check duplicates server-side
        $checks = array(
            'mobile' => $mobile,
            'email'  => $email,
            'pan'    => $pan,
            'aadhaar'=> $aadhaar
        );
        foreach ($checks as $col => $val) {
            if ($val === '') continue;
            $r = check_exists($conn, $col, $val);
            if (!$r['error'] && $r['exists']) {
                echo json_encode(array('status' => 'error', 'msg' => ucfirst($col) . ' already exists'));
                exit;
            }
        }

        // referral validation (if used)
        $referred_by_user = null;
        $valid_referral = false;
        if ($use_referral && $referralCodeInput !== '') {
            $sql_check = "SELECT id FROM users WHERE referral_code = ?";
            $stmt_check = $conn->prepare($sql_check);
            if ($stmt_check) {
                $stmt_check->bind_param("s", $referralCodeInput);
                $stmt_check->execute();
                $res = $stmt_check->get_result();
                if ($res && $res->num_rows > 0) {
                    $valid_referral = true;
                    $row = $res->fetch_assoc();
                    $referred_by_user = $row['id'];
                }
                $stmt_check->close();
            }
        }

        // create user
        $referralCode = function_exists('generateReferralCode') ? generateReferralCode() : substr(md5(uniqid('', true)), 0, 8);
        $instanceId = generateRandomInstanceId();
        $user_token = md5(mt_rand(10000000, 99999999));
        $pass_hashed = password_hash($password, PASSWORD_BCRYPT);
        $today = date("Y-m-d", strtotime("+1 days"));

        $sql_insert = "INSERT INTO users (`name`,`mobile`,`role`,`balance`,`password`,`email`,`company`,`pin`,`pan`,`aadhaar`,`location`,`user_token`,`expiry`,`vip_expiry`,`instance_id`, `referral_code`, `referred_by`, `planId`) VALUES (?, ?, 'User', '0.00', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '5')";

        $stmt = $conn->prepare($sql_insert);
        if (!$stmt) {
            echo json_encode(array('status' => 'error', 'msg' => 'DB prepare error: '.$conn->error));
            exit;
        }

        $referred_by_param = $valid_referral && $referred_by_user ? $referred_by_user : null;

        // bind params (15 strings)
        $stmt->bind_param(
            "sssssssssssssss",
            $name,
            $mobile,
            $pass_hashed,
            $email,
            $company,
            $pin,
            $pan,
            $aadhaar,
            $location,
            $user_token,
            $today,
            $today,
            $instanceId,
            $referralCode,
            $referred_by_param
        );

        $executed = $stmt->execute();
        if ($executed) {
            $newUserId = $stmt->insert_id;

            // send notification
            $msg = "Dear {$name} thanks For Registering Us\nYour Username = {$mobile}\nYour Password = {$password}\nThanks & Regards\n*UpiGateway™*";
            if (function_exists('sendNotification')) {
                sendNotification($mobile, $email, $msg, "Well-Come To UpiGateway Family");
            }

            // if referral applied and valid: fetch plans and return for modal
            if ($valid_referral) {
                $plans = array();
                $sql = "SELECT id, plan_name, amount, expiry FROM subscription_plan";
                $res = $conn->query($sql);
                if ($res && $res->num_rows > 0) {
                    while ($row = $res->fetch_assoc()) $plans[] = $row;
                }
                echo json_encode(array('status' => 'ok', 'msg' => 'registered_referred', 'mobile' => $mobile, 'plans' => $plans));
                $stmt->close();
                exit;
            }

            // normal success -> redirect
            echo json_encode(array('status' => 'ok', 'msg' => 'registered', 'redirect' => 'auth/index'));
            $stmt->close();
            exit;
        } else {
            echo json_encode(array('status' => 'error', 'msg' => 'Registration failed: '.$stmt->error));
            $stmt->close();
            exit;
        }
    }

    echo json_encode(array('status' => 'error', 'msg' => 'Invalid request'));
    exit;
}

// If GET -> render HTML form (client-side JS will use fetch to call same file)
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
<title><?php echo isset($site_settings['brand_name']) ? $site_settings['brand_name'] : 'Registration'; ?> | Registration</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<?php echo "<link rel=\"icon\" href=\"https://".(isset($server)?$server:'')."/common/img/logoshild.png\">"; ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
<link rel="stylesheet" href="../common/assets/vendor/css/pages/page-auth.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <div class="auth-container">
        <div class="auth-image">
            <div class="left-logo">
                <img src="../common/img/logoshild.png" alt="logo">
            </div>
        </div>

        <div class="auth-form">
            <div class="reg-form-div">
                <img src="<?php echo isset($site_settings['logo_url']) ? $site_settings['logo_url'] : '../common/img/logoshild.png'; ?>" alt="Logo" class="logo img-fluid">
                <h4 class="mb-1">Register <?php echo isset($site_settings['brand_name']) ? $site_settings['brand_name'] : ''; ?> 🚀</h4>
                <p class="mb-5">Start Your Journey To Advanced Payments!</p>
                <div id="toast-container" class="toast-container"></div>

                <form id="regForm" class="mb-5" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

                    <div class="form-floating form-floating-outline mb-5">
                        <input type="text" class="form-control" id="username" name="name" placeholder="Enter your Name" pattern="[A-Za-z\s]+" title="Only letters and spaces allowed" required autofocus>
                        <label for="username">Name</label>
                        <div id="name-warning" class="text-danger mt-1"></div>
                    </div>

                    <div class="form-floating form-floating-outline mb-5">
                        <input type="number" class="form-control" id="Number" name="mobile" placeholder="Enter your Number" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" required>
                        <label for="Number">Mobile Number</label>
                        <div id="mobile-warning" class="text-danger mt-1"></div>
                    </div>

                    <div id="hiddenFields" style="display: none;">
                        <div class="form-floating form-floating-outline mb-5">
                            <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required>
                            <label for="email">Email Id</label>
                            <div id="email-warning" class="text-danger mt-1"></div>
                        </div>

                        <div class="form-floating form-floating-outline mb-5">
                            <input type="text" class="form-control" id="company" name="company" placeholder="Enter your Company Name" required>
                            <label for="company">Company Name</label>
                        </div>

                        <div class="form-floating form-floating-outline mb-5">
                            <input type="number" class="form-control" id="aadhar" name="aadhaar" placeholder="Enter your Aadhaar Number" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12);" required>
                            <label for="aadhar">Aadhaar Number</label>
                            <div id="aadhaar-warning" class="text-danger mt-1"></div>
                        </div>

                        <div class="form-floating form-floating-outline mb-5">
                            <input type="text" class="form-control" id="pan" name="pan" placeholder="Enter your Pan Number" maxlength="10" oninput="this.value = this.value.toUpperCase();" required>
                            <label for="pan">Pan Number</label>
                            <div id="pan-warning" class="text-danger mt-1"></div>
                        </div>

                        <div class="form-floating form-floating-outline mb-5">
                            <input type="text" class="form-control" id="location" name="location" placeholder="Enter your Location" required>
                            <label for="location">Location</label>
                        </div>

                        <div class="form-floating form-floating-outline mb-5">
                            <input type="number" class="form-control" id="pin" name="pin" placeholder="Enter your Pincode" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);" required>
                            <label for="pin">Pincode</label>
                            <div id="pin-warning" class="text-danger mt-1"></div>
                        </div>

                        <div class="mb-5 form-password-toggle">
                            <div class="input-group input-group-merge">
                                <div class="form-floating form-floating-outline">
                                    <input type="password" id="password" class="form-control" name="password" placeholder="••••••••••••" required />
                                    <label for="password">Password</label>
                                </div>
                                <span class="input-group-text cursor-pointer" id="togglePassword">
                                    <i class="ri-eye-off-line ri-20px"></i>
                                </span>
                            </div>
                            <div id="password-strength" class="mt-2"></div>
                        </div>

                        <div class="mb-5 form-check">
                            <input class="form-check-input" type="checkbox" id="use_referral" name="use_referral" onchange="toggleReferralInput(this)">
                            <label class="form-check-label" for="use_referral">Apply Referral Code</label>
                        </div>

                        <div id="referralCodeContainer" style="display: none;">
                            <div class="form-floating form-floating-outline mb-5">
                                <input type="text" id="referral_code" class="form-control" name="referral_code" placeholder="Referral Code (Optional)">
                                <label for="referral_code">Referral Code</label>
                                <div id="referral-warning" class="text-danger mt-1"></div>
                            </div>
                        </div>

                        <div class="g-recaptcha" data-sitekey="6Lc6OuwrAAAAANEMTp_Efl-J0B2DfINtO-XoyENE"></div>

                        <div class="mb-5 py-2">
                            <div class="form-check mb-0">
                                <input class="form-check-input" type="checkbox" id="terms-conditions" name="terms" required>
                                <label class="form-check-label" for="terms-conditions">
                                    I agree to <a href="javascript:void(0);">privacy policy & terms</a>
                                </label>
                            </div>
                        </div>

                        <button type="submit" id="submitBtn" class="btn btn-primary d-grid w-100">Sign up</button>
                    </div>
                </form>

            </div>
            <p class="text-center mb-5">
                <span>Already have an account?</span>
                <a href="auth/index"><span>Sign in instead</span></a>
            </p>
        </div>
    </div>

    <!-- Theme Toggle Button -->
    <button class="theme-toggle" id="themeToggle" title="Toggle Theme"><i class="ri-sun-line"></i></button>

<script>
// Helper: show toast
function showToast(message, type = 'info') {
    Swal.fire({text: message, icon: type, toast: true, position: 'top-end', showConfirmButton: false, timer: 2500});
}

// Extract referral from URL param named 'referred_by' or 'referral_code'
function getReferralCode() {
    const urlParams = new URLSearchParams(window.location.search);
    const referralCode = urlParams.get('referred_by') || urlParams.get('referral_code') || urlParams.get('referral');
    if (referralCode) {
        const referralInput = document.getElementById('referral_code');
        const applyReferralCheckbox = document.getElementById('use_referral');
        const referralCodeContainer = document.getElementById('referralCodeContainer');

        if (referralInput) {
            referralInput.value = referralCode;
            referralInput.readOnly = true;
        }
        if (referralCodeContainer) referralCodeContainer.style.display = 'block';
        if (applyReferralCheckbox) { applyReferralCheckbox.checked = true; applyReferralCheckbox.disabled = true; }
        // ensure hiddenFields visible if initial validations passed earlier
        document.getElementById('hiddenFields').style.display = 'block';
    }
}
window.onload = getReferralCode;

// ---------- Field validators & realtime uniqueness checks ----------
function validateName() {
    const name = document.getElementById('username').value;
    const namePattern = /^[A-Za-z\s]+$/;
    const warningDiv = document.getElementById('name-warning');
    warningDiv.textContent = (name.length>0 && !namePattern.test(name)) ? 'Only letters and spaces are allowed' : '';
}

function validateMobileFormat() {
    const mobile = document.getElementById('Number').value;
    const warningDiv = document.getElementById('mobile-warning');
    warningDiv.textContent = (mobile.length>0 && mobile.length !== 10) ? 'Mobile number must be exactly 10 digits' : '';
}

function validateEmailFormat() {
    const email = document.getElementById('email').value;
    const warningDiv = document.getElementById('email-warning');
    const emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
    warningDiv.textContent = (email.length>0 && !emailPattern.test(email)) ? 'Please enter a valid email address' : '';
}

function validateAadhaarFormat() {
    const aadhaar = document.getElementById('aadhar').value;
    const warningDiv = document.getElementById('aadhaar-warning');
    warningDiv.textContent = (aadhaar.length>0 && aadhaar.length !== 12) ? 'Aadhaar must be exactly 12 digits' : '';
}

function validatePANFormat() {
    const pan = document.getElementById('pan').value;
    const warningDiv = document.getElementById('pan-warning');
    const panPattern = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
    warningDiv.textContent = (pan.length>0 && !panPattern.test(pan)) ? 'PAN must be in format ABCDE1234F' : '';
}

function validatePinFormat() {
    const pin = document.getElementById('pin').value;
    const warningDiv = document.getElementById('pin-warning');
    warningDiv.textContent = (pin.length>0 && pin.length !== 6) ? 'Pincode must be exactly 6 digits' : '';
}

function toggleReferralInput(checkbox) {
    const referralContainer = document.getElementById('referralCodeContainer');
    if (checkbox.checked) referralContainer.style.display = 'block'; else { referralContainer.style.display = 'none'; document.getElementById('referral_code').value = ''; document.getElementById('referral-warning').textContent = ''; }
}

// show hidden fields after mobile & name valid and mobile uniqueness check
function checkInitialFields() {
    const name = document.getElementById('username').value.trim();
    const mobile = document.getElementById('Number').value.trim();
    const namePattern = /^[A-Za-z\s]+$/;
    const mobilePattern = /^[0-9]{10}$/;

    if (!namePattern.test(name)) { document.getElementById('name-warning').textContent = 'Name should contain only letters and spaces'; document.getElementById('hiddenFields').style.display = 'none'; return; }
    if (!mobilePattern.test(mobile)) { document.getElementById('mobile-warning').textContent = 'Please enter a valid 10-digit mobile number'; document.getElementById('hiddenFields').style.display = 'none'; return; }

    // check uniqueness via AJAX
    const body = `checkMobile=true&mobile=${encodeURIComponent(mobile)}`;
    fetch(window.location.href, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body })
    .then(r => r.json())
    .then(data => {
        if (data.exists) {
            document.getElementById('mobile-warning').textContent = 'This mobile number is already registered. Please Sign in';
            document.getElementById('hiddenFields').style.display = 'none';
        } else {
            document.getElementById('hiddenFields').style.display = 'block';
            document.getElementById('name-warning').textContent = '';
            document.getElementById('mobile-warning').textContent = '';
            const emailField = document.getElementById('email'); if (emailField) emailField.focus();
            showToast('Mobile available — continue filling the form.', 'success');
        }
    })
    .catch(err => { console.error(err); document.getElementById('mobile-warning').textContent = 'Error checking mobile number'; });
}

// Attach keyup handlers for initial checks
document.getElementById('username').addEventListener('keyup', checkInitialFields);
document.getElementById('Number').addEventListener('keyup', checkInitialFields);

// realtime checks for email, aadhaar, pan
document.getElementById('email').addEventListener('keyup', function(){ validateEmailFormat(); const email = this.value.trim(); const pattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/; if (pattern.test(email)) { fetch(window.location.href, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `checkEmail=true&email=${encodeURIComponent(email)}` }).then(r=>r.json()).then(d=>{ if (d.exists) document.getElementById('email-warning').textContent = 'This email is already registered.'; else document.getElementById('email-warning').textContent = ''; }).catch(e=>{ document.getElementById('email-warning').textContent = 'Error checking email'; }); } });

document.getElementById('aadhar').addEventListener('keyup', function(){ validateAadhaarFormat(); const aad = this.value.trim(); if (aad.length===12) { fetch(window.location.href, { method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded' }, body:`checkAadhaar=true&aadhaar=${encodeURIComponent(aad)}` }).then(r=>r.json()).then(d=>{ if (d.exists) document.getElementById('aadhaar-warning').textContent='This Aadhaar number is already registered.'; else document.getElementById('aadhaar-warning').textContent=''; }).catch(e=>{ document.getElementById('aadhaar-warning').textContent='Error checking Aadhaar'; }); }});

document.getElementById('pan').addEventListener('keyup', function(){ validatePANFormat(); const pan = this.value.trim(); const patt = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/; if (patt.test(pan)) { fetch(window.location.href, { method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded' }, body:`checkPAN=true&pan=${encodeURIComponent(pan)}` }).then(r=>r.json()).then(d=>{ if (d.exists) document.getElementById('pan-warning').textContent='This PAN is already registered.'; else document.getElementById('pan-warning').textContent=''; }).catch(e=>{ document.getElementById('pan-warning').textContent='Error checking PAN'; }); }});

// password toggle
document.getElementById('togglePassword').addEventListener('click', function(){ const password = document.getElementById('password'); const icon = this.querySelector('i'); if (password.type==='password') { password.type='text'; icon.classList.replace('ri-eye-off-line', 'ri-eye-line'); } else { password.type='password'; icon.classList.replace('ri-eye-line', 'ri-eye-off-line'); } });

// form submit via fetch to get JSON response
const regForm = document.getElementById('regForm');
regForm.addEventListener('submit', function(e){
    e.preventDefault();

    // client-side validation before submit
    const name = document.getElementById('username').value.trim();
    const mobile = document.getElementById('Number').value.trim();
    const email = document.getElementById('email').value.trim();
    const aadhaar = document.getElementById('aadhar').value.trim();
    const pan = document.getElementById('pan').value.trim();
    const pin = document.getElementById('pin').value.trim();
    const password = document.getElementById('password').value;

    const namePattern = /^[A-Za-z\s]+$/;
    const mobilePattern = /^[0-9]{10}$/;
    const emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
    const aadhaarPattern = /^[0-9]{12}$/;
    const panPattern = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
    const pinPattern = /^[0-9]{6}$/;

    const warnings = [document.getElementById('name-warning').textContent, document.getElementById('mobile-warning').textContent, document.getElementById('email-warning').textContent, document.getElementById('aadhaar-warning').textContent, document.getElementById('pan-warning').textContent, document.getElementById('pin-warning').textContent, document.getElementById('referral-warning')?document.getElementById('referral-warning').textContent:'' ];
    if (warnings.some(w=>w!=='')) { showToast('Please fix the errors before submitting.','error'); return; }

    if (!namePattern.test(name)) { showToast('Invalid name format.','error'); return; }
    if (!mobilePattern.test(mobile)) { showToast('Invalid mobile number.','error'); return; }
    if (!emailPattern.test(email)) { showToast('Invalid email address.','error'); return; }
    if (!aadhaarPattern.test(aadhaar)) { showToast('Invalid Aadhaar number.','error'); return; }
    if (!panPattern.test(pan)) { showToast('Invalid PAN number.','error'); return; }
    if (!pinPattern.test(pin)) { showToast('Invalid Pincode.','error'); return; }
    if (password.length < 6) { showToast('Password too short.','error'); return; }

    const fd = new FormData(regForm);
    fd.append('create', '1');

    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = true;

    fetch(window.location.href, { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        submitBtn.disabled = false;
        if (data.status === 'ok') {
            if (data.msg === 'registered_referred' && data.plans) {
                // build modal HTML for plans
                let options = '';
                data.plans.forEach(p => {
                    options += `<option value="${p.plan_name}" data-planid="${p.id}" data-amount="${p.amount}" data-expiry="${p.expiry}">Rs. ${p.amount} - ${p.plan_name}</option>`;
                });

                Swal.fire({
                    title: 'Referral Applied!',
                    html: `
                        <form id="planForm">
                            <div style="margin-bottom:10px;">
                                <label style="display:block;font-weight:bold;">Select Plan</label>
                                <select id="plan" name="plan" class="form-control" required>
                                    <option value="" disabled selected>Select a plan</option>
                                    ${options}
                                </select>
                            </div>
                            <div style="margin-bottom:10px;">
                                <label style="display:block;font-weight:bold;">Mobile Number</label>
                                <input type="text" id="modal_mobile" name="mobile" value="${data.mobile}" class="form-control" readonly>
                            </div>
                            <div style="margin-bottom:10px;">
                                <label style="display:block;font-weight:bold;">Amount</label>
                                <input type="text" id="amount" name="amount" class="form-control" readonly>
                            </div>
                            <div style="margin-bottom:10px;">
                                <label style="display:block;font-weight:bold;">Validity (in days)</label>
                                <input type="text" id="validity" name="validity" class="form-control" readonly>
                            </div>
                        </form>
                    `,
                    showConfirmButton: false,
                    allowOutsideClick: false,
                    didOpen: () => {
                        const planDropdown = document.getElementById('plan');
                        const amountField = document.getElementById('amount');
                        const validityField = document.getElementById('validity');
                        const mobileField = document.getElementById('modal_mobile');

                        planDropdown.addEventListener('change', (event) => {
                            const selectedOption = event.target.selectedOptions[0];
                            amountField.value = selectedOption.getAttribute('data-amount');
                            validityField.value = selectedOption.getAttribute('data-expiry');
                        });

                        const form = document.getElementById('planForm');
                        form.addEventListener('submit', (e) => { e.preventDefault(); });

                        // add submit button below
                        const footer = document.createElement('div');
                        footer.style.marginTop = '10px';
                        footer.innerHTML = `<button id="referSubmit" class="btn btn-primary" style="width:100%">Submit</button>`;
                        document.querySelector('.swal2-html-container').appendChild(footer);

                        document.getElementById('referSubmit').addEventListener('click', ()=>{
                            const selected = planDropdown.selectedOptions[0];
                            if (!selected) { Swal.showValidationMessage('Select a plan'); return; }
                            const referpay = 'referpay';
                            const planid = selected.getAttribute('data-planid');
                            const amount = amountField.value;
                            const validity = validityField.value;
                            const mobile = mobileField.value;

                            // create and submit form to payment endpoint
                            const dynamicForm = document.createElement('form');
                            dynamicForm.method = 'POST';
                            dynamicForm.action = 'auth/lib/pay.php';
                            dynamicForm.innerHTML = `
                                <input type="hidden" name="for" value="${referpay}">
                                <input type="hidden" name="planid" value="${planid}">
                                <input type="hidden" name="plan" value="${selected.value}">
                                <input type="hidden" name="amount" value="${amount}">
                                <input type="hidden" name="validity" value="${validity}">
                                <input type="hidden" name="mobile" value="${mobile}">
                            `;
                            document.body.appendChild(dynamicForm);
                            dynamicForm.submit();
                        });
                    }
                });

            } else if (data.redirect) {
                Swal.fire({title:'Success', text:'Registration successful', icon:'success'}).then(()=> { window.location.href = data.redirect; });
            } else {
                Swal.fire({title:'Success', text:'Registration successful', icon:'success'});
            }
        } else {
            Swal.fire({title:'Error', text: data.msg || 'Server error', icon:'error'});
        }
    })
    .catch(err => { console.error(err); submitBtn.disabled = false; Swal.fire({title:'Error', text:'Server error', icon:'error'}); });
});

</script>
</body>
</html>
