﻿<?php
require_once dirname(dirname(__DIR__)) . '/config/database.php';
require_once dirname(dirname(__DIR__)) . '/includes/functions.php';
require_once dirname(dirname(__DIR__)) . '/includes/whatsapp.php';

initSession();

// Redirect if already logged in
if (isLoggedIn('client')) {
    header('Location: ../index.php');
    exit;
}

// Check if registration is enabled in system settings
$db = getDB();
$reg_setting = $db->query("SELECT setting_value FROM system_settings WHERE setting_key = 'user_registration'");
$reg_enabled = ($reg_setting && $row = $reg_setting->fetch_assoc()) ? $row['setting_value'] : '1';

if ($reg_enabled !== '1') {
    // Show a pretty disabled message
    $registration_disabled = true;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Honeypot protection against spam bots
    if (!empty($_POST['website_url'])) {
        $error = 'An error occurred. Please try again.';
        sleep(2);
    } 
    // 2. CSRF Token Validation
    elseif (!validateCSRFToken()) {
        $error = 'Session expired or invalid request. Please refresh the page and try again.';
    } 
    // 3. IP-based rate limiting to prevent registration flooding (1 attempt per 10 seconds)
    else {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        }
        $ip_hash = md5($ip);
        $rate_limit_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'reg_limit_' . $ip_hash;
        
        $is_rate_limited = false;
        if (file_exists($rate_limit_file)) {
            $last_time = (int)file_get_contents($rate_limit_file);
            if ((time() - $last_time) < 10) {
                $is_rate_limited = true;
            }
        }

        if ($is_rate_limited) {
            $error = 'Too many attempts from this IP. Please wait 10 seconds.';
        } else {
            // Record this attempt
            @file_put_contents($rate_limit_file, time());

            $name = sanitize($_POST['name'] ?? '');
            $phone = sanitize($_POST['phone'] ?? '');
            $password = $_POST['password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';
            $email = $phone . '@gobotad.com';
            $otp = sanitize($_POST['otp'] ?? '');

            // Validation
            if (empty($name) || empty($phone) || empty($password) || empty($otp)) {
                $error = 'Please fill in all fields including the OTP';
            } elseif (strlen($name) < 2 || strlen($name) > 50) {
                $error = 'Name must be between 2 and 50 characters';
            } elseif (!validateName($name)) {
                $error = 'Name contains invalid characters or file extensions';
            } elseif (!validatePhone($phone)) {
                $error = 'Invalid phone number';
            } elseif (strlen($password) < 6) {
                $error = 'Password must be at least 6 characters';
            } elseif (strlen($password) > 72) {
                $error = 'Password must be under 72 characters';
            } elseif ($password !== $confirm_password) {
                $error = 'Passwords do not match';
            } else {
                $db = getDB();

                // Verify OTP
                if (!verifyOTP($db, $phone, $otp)) {
                    $error = 'Invalid or expired OTP code';
                } else {
                    // Check if phone exists
                    $sql = "SELECT id FROM users WHERE phone = ? LIMIT 1";
                    $stmt = $db->prepare($sql);
                    $stmt->bind_param('s', $phone);
                    $stmt->execute();
                    if ($stmt->get_result()->num_rows > 0) {
                        $error = 'Phone number already registered';
                    } else {
                        // Insert new user
                        $hashedPassword = hashPassword($password);
                        $sql = "INSERT INTO users (name, email, phone, password, status) VALUES (?, ?, ?, ?, 'active')";
                        $stmt = $db->prepare($sql);
                        $stmt->bind_param('ssss', $name, $email, $phone, $hashedPassword);

                        if ($stmt->execute()) {
                            // Clean up rate limit file on successful registration
                            if (file_exists($rate_limit_file)) {
                                @unlink($rate_limit_file);
                            }
                            // ✅ WhatsApp Welcome Message
                            WhatsAppService::sendWelcome($phone, $name);
                            $success = 'Account created successfully! Redirecting to login...';
                            header('refresh:2;url=../../index.php');
                        } else {
                            $error = 'Registration failed. Please try again.';
                        }
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account — GoBotad</title>
    <meta name="description" content="Join GoBotad to order from the best local restaurants in Botad.">
    <link rel="canonical" href="https://gobotad.com/client/auth/register" />
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://gobotad.com/client/auth/register">
    <meta property="og:title" content="Create Account — GoBotad">
    <meta property="og:description" content="Join GoBotad to order from the best local restaurants in Botad.">
    <meta property="og:image" content="https://gobotad.com/uploads/banners/69d16da394dd8_1775332771.png">

    <!-- Twitter -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:url" content="https://gobotad.com/client/auth/register">
    <meta name="twitter:title" content="Create Account — GoBotad">
    <meta name="twitter:description" content="Join GoBotad to order from the best local restaurants in Botad.">
    <meta name="twitter:image" content="https://gobotad.com/uploads/banners/69d16da394dd8_1775332771.png">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Manrope:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap"
        rel="stylesheet">
  <link rel="stylesheet" href="../assets/css/fa-all.min.css">
    <style>
        *,
        *::before,
        *::after {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        :root {
            --orange: #f97316;
            --orange-d: #ea580c;
            --dark: #0f172a;
            --dark2: #1e293b;
            --gray: #64748b;
            --light: #f8fafc;
            --white: #ffffff;
            --radius: 18px;
        }

        html,
        body {
            height: 100%;
        }

        body {
            font-family: 'Plus Jakarta Sans', 'Manrope', 'Inter', sans-serif;
            background: var(--dark);
            min-height: 100vh;
            display: flex;
            overflow-x: hidden;
        }

        /* ── LAYOUT ─────────────────────────────────────────────── */
        .wrap {
            display: flex;
            width: 100%;
            min-height: 100vh;
        }

        /* ── LEFT PANEL ─────────────────────────────────────────── */
        .left {
            flex: 1.1;
            background: linear-gradient(155deg, #0f172a 0%, #1a1040 60%, #0c1a2e 100%);
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 4rem 4rem;
            overflow: hidden;
        }

        .left::before {
            content: '';
            position: absolute;
            width: 600px;
            height: 600px;
            background: radial-gradient(circle, rgba(249, 115, 22, .18) 0%, transparent 70%);
            top: -150px;
            right: -200px;
            pointer-events: none;
        }

        .left::after {
            content: '';
            position: absolute;
            width: 400px;
            height: 400px;
            background: radial-gradient(circle, rgba(99, 102, 241, .12) 0%, transparent 70%);
            bottom: -100px;
            left: -100px;
            pointer-events: none;
        }

        /* floating food emojis */
        .floaters {
            position: absolute;
            inset: 0;
            pointer-events: none;
            overflow: hidden;
        }

        .floater {
            position: absolute;
            font-size: 2rem;
            opacity: 0.07;
            animation: floatUp 8s ease-in-out infinite;
        }

        .floater:nth-child(1) {
            left: 10%;
            top: 80%;
            animation-delay: 0s;
        }

        .floater:nth-child(2) {
            left: 30%;
            top: 90%;
            animation-delay: 1.5s;
        }

        .floater:nth-child(3) {
            left: 55%;
            top: 85%;
            animation-delay: 3s;
        }

        .floater:nth-child(4) {
            left: 75%;
            top: 95%;
            animation-delay: 0.7s;
        }

        .floater:nth-child(5) {
            left: 90%;
            top: 75%;
            animation-delay: 2.2s;
        }

        @keyframes floatUp {
            0% {
                transform: translateY(0) rotate(0deg);
            }

            50% {
                transform: translateY(-60px) rotate(15deg);
            }

            100% {
                transform: translateY(0) rotate(0deg);
            }
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 0.85rem;
            margin-bottom: 3.5rem;
            position: relative;
            z-index: 2;
            text-decoration: none;
        }

        .brand-icon {
            width: 52px;
            height: 52px;
            background: linear-gradient(135deg, var(--orange), #ef4444);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            box-shadow: 0 8px 24px rgba(249, 115, 22, .4);
        }

        .brand-name {
            font-size: 1.6rem;
            font-weight: 900;
            color: white;
            text-decoration: none;
        }

        .brand-name span {
            color: var(--orange);
        }

        .hero-headline {
            position: relative;
            z-index: 2;
            font-size: clamp(2rem, 3.5vw, 3.2rem);
            font-weight: 900;
            color: white;
            line-height: 1.15;
            margin-bottom: 1.25rem;
        }

        .hero-headline em {
            font-style: normal;
            background: linear-gradient(135deg, var(--orange), #fbbf24);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .hero-sub {
            position: relative;
            z-index: 2;
            color: #94a3b8;
            font-size: 1.05rem;
            line-height: 1.7;
            margin-bottom: 2.5rem;
            max-width: 400px;
        }

        .features {
            list-style: none;
            position: relative;
            z-index: 2;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            margin-bottom: 3rem;
        }

        .feature-item {
            display: flex;
            align-items: center;
            gap: 0.85rem;
            background: rgba(255, 255, 255, 0.04);
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 14px;
            padding: 0.9rem 1.25rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            font-weight: 500;
            transition: all 0.25s;
        }

        .feature-item:hover {
            background: rgba(249, 115, 22, .08);
            border-color: rgba(249, 115, 22, .2);
            transform: translateX(4px);
        }

        .feature-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            background: linear-gradient(135deg, var(--orange), #ef4444);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
            flex-shrink: 0;
            box-shadow: 0 4px 12px rgba(249, 115, 22, .3);
        }

        /* ── RIGHT PANEL ─────────────────────────────────────────── */
        .right {
            width: 480px;
            flex-shrink: 0;
            background: #ffffff;
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 3.5rem 3rem;
            position: relative;
            overflow-y: auto;
        }

        .right::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--orange), #f59e0b, #ef4444);
        }

        /* Webkit Scrollbar for right panel */
        .right::-webkit-scrollbar {
            width: 6px;
        }

        .right::-webkit-scrollbar-track {
            background: transparent;
        }

        .right::-webkit-scrollbar-thumb {
            background-color: #cbd5e1;
            border-radius: 10px;
        }

        .form-header {
            margin-bottom: 2rem;
        }

        .form-title {
            font-size: 1.75rem;
            font-weight: 900;
            color: var(--dark);
            margin-bottom: 0.4rem;
        }

        .form-sub {
            font-size: 0.9rem;
            color: var(--gray);
        }

        /* Alerts */
        .alert {
            padding: 0.9rem 1.1rem;
            border-radius: 12px;
            font-size: 0.875rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.6rem;
            margin-bottom: 1.25rem;
        }

        .alert-error {
            background: #fff1f2;
            color: #ef4444;
            border: 1px solid #fecdd3;
        }

        .alert-success {
            background: #f0fdf4;
            color: #16a34a;
            border: 1px solid #bbf7d0;
        }

        /* Input Group */
        .field {
            margin-bottom: 1.1rem;
        }

        .field label {
            display: block;
            font-size: 0.78rem;
            font-weight: 800;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 0.45rem;
        }

        .input-wrap {
            position: relative;
        }

        .input-wrap i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            font-size: 0.95rem;
            pointer-events: none;
        }

        .input-wrap input {
            width: 100%;
            padding: 0.9rem 1rem 0.9rem 2.8rem;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            font-size: 0.95rem;
            font-weight: 500;
            font-family: 'Plus Jakarta Sans', 'Manrope', 'Inter', sans-serif;
            outline: none;
            transition: all 0.2s;
            background: #fafafa;
            color: var(--dark);
        }

        .input-wrap input:focus {
            border-color: var(--orange);
            background: white;
            box-shadow: 0 0 0 3px rgba(249, 115, 22, .1);
        }

        .toggle-pass {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            cursor: pointer;
            font-size: 0.95rem;
            transition: color 0.2s;
        }

        .toggle-pass:hover {
            color: var(--orange);
        }

        .row-between {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.25rem;
        }

        .remember {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.85rem;
            color: #64748b;
            cursor: pointer;
            font-weight: 600;
        }

        .remember input {
            width: auto;
            accent-color: var(--orange);
        }

        /* Submit button */
        .btn-login {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, var(--orange), var(--orange-d));
            color: white;
            border: none;
            border-radius: 14px;
            font-size: 1rem;
            font-weight: 800;
            font-family: 'Plus Jakarta Sans', 'Manrope', 'Inter', sans-serif;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(249, 115, 22, .4);
            transition: all 0.25s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.6rem;
            position: relative;
            overflow: hidden;
        }

        .btn-login::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -60%;
            width: 60%;
            height: 200%;
            background: rgba(255, 255, 255, 0.15);
            transform: skewX(-20deg);
            transition: left 0.4s;
        }

        .btn-login:hover::before {
            left: 130%;
        }

        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 28px rgba(249, 115, 22, .5);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        /* Divider */
        .divider {
            display: flex;
            align-items: center;
            gap: 1rem;
            color: #cbd5e1;
            font-size: 0.8rem;
            font-weight: 700;
            margin: 1.5rem 0;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .divider::before,
        .divider::after {
            content: '';
            flex: 1;
            height: 1px;
            background: #e2e8f0;
        }

        /* Footer links */
        .footer-link {
            text-align: center;
            font-size: 0.88rem;
            color: #94a3b8;
            font-weight: 500;
        }

        .footer-link a {
            color: var(--orange);
            font-weight: 700;
            text-decoration: none;
        }

        .footer-link a:hover {
            text-decoration: underline;
        }

        /* Loading overlay */
        .loader {
            position: fixed;
            inset: 0;
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(6px);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 999;
        }

        .spinner {
            width: 44px;
            height: 44px;
            border: 4px solid #f1f5f9;
            border-top-color: var(--orange);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* ── Responsive ─────────────────────────────────────────── */
        @media(max-width:900px) {
            .left {
                display: none;
            }

            .right {
                width: 100%;
            }
        }

        @media(max-width:480px) {
            .right {
                padding: 2.5rem 1.5rem;
            }
        }
    </style>
</head>

<body>

    <div class="loader" id="loader">
        <div class="spinner"></div>
    </div>

    <div class="wrap">

        <!-- ── LEFT PANEL ───────────────────────────────────────── -->
        <div class="left">
            <div class="floaters" aria-hidden="true">
                <span class="floater">🍔</span>
                <span class="floater">🍟</span>
                <span class="floater">🥤</span>
                <span class="floater">🍕</span>
                <span class="floater">🥪</span>
            </div>

            <a href="../../index.php" class="brand">
                <div class="brand-icon">🍔</div>
                <div class="brand-name">Go<span>Foodz</span></div>
            </a>

            <h1 class="hero-headline">
                Join the Foodie<br>
                <em>Community.</em>
            </h1>
            <p class="hero-sub">
                Create an account to start ordering your favorite meals, tracking your deliveries in real-time, and
                enjoying exclusive deals.
            </p>

            <ul class="features">
                <li class="feature-item">
                    <div class="feature-icon"><i class="fas fa-gift"></i></div>
                    Welcome offers and discounts
                </li>
                <li class="feature-item">
                    <div class="feature-icon"><i class="fas fa-clock-rotate-left"></i></div>
                    Easy reordering of favorite meals
                </li>
                <li class="feature-item">
                    <div class="feature-icon"><i class="fas fa-wallet"></i></div>
                    Fast checkout with GoBotad wallet
                </li>
            </ul>
        </div>

        <!-- ── RIGHT PANEL ──────────────────────────────────────── -->
        <div class="right">

            <div class="form-header">
                <h2 class="form-title">Create Account ✨</h2>
                <p class="form-sub">Sign up to get started with GoBotad</p>
            </div>

            <?php if (isset($registration_disabled) && $registration_disabled): ?>
                <div style="text-align: center; padding: 3rem 1rem; background: #fff7ed; border-radius: 20px; border: 2px dashed #ffedd5; margin-top: 2rem;">
                    <div style="width: 70px; height: 70px; background: #ffedd5; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1.5rem; color: #f97316; font-size: 1.8rem;">
                        <i class="fas fa-user-slash"></i>
                    </div>
                    <h3 style="font-size: 1.4rem; font-weight: 800; color: #7c2d12; margin-bottom: 0.8rem;">Registration Paused</h3>
                    <p style="color: #9a3412; font-size: 0.95rem; line-height: 1.6; margin-bottom: 2rem;">We are currently not accepting new user registrations. Please check back later or contact support if you need an account.</p>
                    <a href="../../index.php" class="btn-login" style="max-width: 180px; margin: 0 auto; text-decoration: none;">
                        <i class="fas fa-arrow-left"></i> Back to Login
                    </a>
                </div>
            <?php else: ?>


            <!-- Alerts -->
            <?php if ($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-circle-exclamation"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-circle-check"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <!-- Registration Form -->
            <form method="POST" id="registerForm">
                <?php echo csrf_input(); ?>
                
                <!-- Honeypot field for bot protection -->
                <div style="display:none;">
                    <input type="text" name="website_url" value="" autocomplete="off" tabindex="-1">
                </div>

                <div class="field">
                    <label>Full Name</label>
                    <div class="input-wrap">
                        <i class="fas fa-user"></i>
                        <input type="text" name="name" placeholder="John Doe"
                            value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" required>
                    </div>
                </div>



                <div class="field">
                    <label>Phone Number</label>
                    <div class="input-wrap">
                        <i class="fas fa-phone"></i>
                        <input type="tel" id="phoneInput" name="phone" placeholder="10-digit mobile number" maxlength="10"
                            inputmode="numeric" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>" required>
                    </div>
                </div>

                <div class="field">
                    <label>Password</label>
                    <div class="input-wrap">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="password" id="passwordInput" placeholder="Minimum 6 characters"
                            required>
                        <span class="toggle-pass" data-target="passwordInput"><i class="fas fa-eye"></i></span>
                    </div>
                </div>

                <div class="field">
                    <label>Confirm Password</label>
                    <div class="input-wrap">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="confirm_password" id="confirmPasswordInput"
                            placeholder="Re-enter password" required>
                        <span class="toggle-pass" data-target="confirmPasswordInput"><i class="fas fa-eye"></i></span>
                    </div>
                </div>

                <!-- OTP Verification Field -->
                <div class="field" id="otpField" style="display: none; margin-bottom: 1.5rem;">
                    <label>OTP Verification Code</label>
                    <div class="input-wrap">
                        <i class="fas fa-key"></i>
                        <input type="text" name="otp" id="otpInput" placeholder="Enter 6-digit OTP code" maxlength="6"
                            inputmode="numeric">
                    </div>
                </div>

                <div class="row-between" style="margin-bottom:1.5rem;">
                    <label class="remember" style="font-weight:500;">
                        <input type="checkbox" name="terms" required checked>
                        <span>I agree to the <a href="#" style="color:var(--orange);text-decoration:none;">Terms</a> &
                            <a href="#" style="color:var(--orange);text-decoration:none;">Privacy Policy</a></span>
                    </label>
                </div>

                <button type="button" class="btn-login" id="sendOtpBtn" style="margin-bottom: 1rem;">
                    <i class="fas fa-paper-plane"></i> Send OTP via SMS
                </button>

                <button type="submit" class="btn-login" id="registerBtn" style="display: none;">
                    <i class="fas fa-user-plus"></i> Verify & Sign Up
                </button>

            </form>

            <div class="divider">or</div>

            <p class="footer-link">
                Already have an account? <a href="../../index.php">Login here</a>
            </p>

            <details class="seo-text" style="margin-top: 2rem; padding-top: 2rem; border-top: 1px solid #e2e8f0; font-size: 0.8rem; color: #94a3b8; line-height: 1.6; text-align: justify;">
                <summary style="font-size: 0.9rem; color: #64748b; font-weight: 700; cursor: pointer; outline: none;">Read More: Join the GoBotad Food Delivery Network <i class="fas fa-chevron-down" style="font-size: 0.75rem; margin-left: 4px;"></i></summary>
                <div style="margin-top: 1rem;">
                    <p style="margin-bottom: 1rem;">Creating an account with GoBotad unlocks a world of culinary delights right at your fingertips. By registering, you gain immediate access to the finest restaurants, cafes, and street food vendors across Botad. Our seamless registration process ensures that you can start browsing extensive menus, discovering new local favorites, and placing orders in a matter of seconds. We prioritize your privacy and ensure that all your personal information and delivery addresses are securely stored for quick and easy future checkouts.</p>
                    <p style="margin-bottom: 1rem;">As a registered GoBotad member, you will enjoy a highly personalized food ordering experience. Save your favorite meals for one-tap reordering, manage multiple delivery addresses for your home and workplace, and securely save payment methods for lightning-fast transactions. Members also receive exclusive access to daily promotional offers, massive discounts, and special loyalty rewards.</p>
                </div>
            </details>
            <?php endif; ?>

    <script>
        // Toggle Password
        const toggles = document.querySelectorAll('.toggle-pass');
        toggles.forEach(toggle => {
            toggle.addEventListener('click', () => {
                const targetId = toggle.getAttribute('data-target');
                const input = document.getElementById(targetId);
                if (input.type === 'password') {
                    input.type = 'text';
                    toggle.innerHTML = '<i class="fas fa-eye-slash"></i>';
                } else {
                    input.type = 'password';
                    toggle.innerHTML = '<i class="fas fa-eye"></i>';
                }
            });
        });

        // Intercept form submission for client-side validation
        const registerForm = document.getElementById('registerForm');
        const sendOtpBtn = document.getElementById('sendOtpBtn');
        const otpField = document.getElementById('otpField');
        const registerBtn = document.getElementById('registerBtn');
        const phoneInput = document.getElementById('phoneInput');

        if (sendOtpBtn) {
            sendOtpBtn.addEventListener('click', async () => {
                const phone = phoneInput.value.trim();
                if (!/^[6-9]\d{9}$/.test(phone)) {
                    alert('Please enter a valid 10-digit mobile number first.');
                    return;
                }

                sendOtpBtn.disabled = true;
                sendOtpBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending OTP...';

                try {
                    const response = await fetch('../../api/send-otp.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ phone: phone })
                    });
                    const resData = await response.json();
                    if (resData.success) {
                        alert('Verification code sent successfully to ' + phone + ' via SMS!');
                        otpField.style.display = 'block';
                        document.getElementById('otpInput').required = true;
                        registerBtn.style.display = 'block';
                        sendOtpBtn.innerHTML = '<i class="fas fa-redo"></i> Resend OTP';
                        sendOtpBtn.disabled = false;
                    } else {
                        alert(resData.message || 'Failed to send verification code. Please try again.');
                        sendOtpBtn.disabled = false;
                        sendOtpBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Send OTP via SMS';
                    }
                } catch (err) {
                    alert('An error occurred. Please try again.');
                    sendOtpBtn.disabled = false;
                    sendOtpBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Send OTP via SMS';
                }
            });
        }

        if (registerForm) {
            registerForm.addEventListener('submit', (e) => {
                const phone = phoneInput.value.trim();
                const pass = document.getElementById('passwordInput').value;
                const conf = document.getElementById('confirmPasswordInput').value;
                const otp = document.getElementById('otpInput').value.trim();
                
                if (pass !== conf) {
                    e.preventDefault();
                    alert('Passwords do not match');
                    return;
                }

                if (!/^[6-9]\d{9}$/.test(phone)) {
                    e.preventDefault();
                    alert('Please enter a valid 10-digit mobile number');
                    return;
                }

                if (!/^\d{6}$/.test(otp)) {
                    e.preventDefault();
                    alert('Please enter a valid 6-digit OTP code');
                    return;
                }

                document.getElementById('loader').style.display = 'flex';
            });
        }
    </script>
</body>
</html>