<?php
/**
 * home.php - الصفحة الرئيسية - نظام مطعم ماكس
 * الإصدار: 7.5 - مع دعم SMS Gateway وخريطة MapTiler
 */

define('SECURE_ACCESS', true);

// بدء الجلسة فقط إذا لم تكن نشطة
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!file_exists(__DIR__ . '/config.php')) {
    die("خطأ: ملف الإعدادات غير موجود");
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions.php';

// منع التخزين المؤقت للصفحات الحساسة
header("Cache-Control: no-cache, must-revalidate, private");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

// استخدام Prepared Statements لأمان أعلى
$stmt = $conn->prepare("SELECT * FROM categories ORDER BY name");
$stmt->execute();
$categories = $stmt->get_result();

// جلب الوجبات - ترتيب عكسي باستخدام ID
$stmt = $conn->prepare("SELECT m.*, c.name as category_name FROM meals m 
                        LEFT JOIN categories c ON m.category_id = c.id 
                        WHERE m.is_active = 1 
                        ORDER BY m.id DESC");
$stmt->execute();
$all_meals = $stmt->get_result();

// السلايدر - التحقق من وجود عمود sort_order
$check_column = $conn->query("SHOW COLUMNS FROM sliders LIKE 'sort_order'");
$has_sort_order = $check_column && $check_column->num_rows > 0;

if ($has_sort_order) {
    $stmt = $conn->prepare("SELECT * FROM sliders WHERE is_active = 1 ORDER BY sort_order ASC");
} else {
    $stmt = $conn->prepare("SELECT * FROM sliders WHERE is_active = 1 ORDER BY id ASC");
}

$stmt->execute();
$sliders = $stmt->get_result();
$sliders_array = [];
while($slide = $sliders->fetch_assoc()) {
    $sliders_array[] = $slide;
}

// معلومات العميل
$customer_phone = $_SESSION['customer_phone'] ?? '';
$customer_name = $_SESSION['customer_name'] ?? 'زائر';
$is_logged_in = isLoggedIn();

// حساب عدد السلة
$cart_count = 0;
if (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $item) {
        $cart_count += $item['quantity'] ?? 0;
    }
}

// الشكاوي غير المقروءة
$unread_tickets = 0;
if (isset($_SESSION['customer_id'])) {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM ticket_messages m 
                            JOIN customer_tickets t ON m.ticket_id = t.id 
                            WHERE t.customer_id = ? AND m.sender_type = 'admin' AND m.is_read = FALSE");
    if ($stmt) {
        $stmt->bind_param('i', $_SESSION['customer_id']);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $unread_tickets = $row['count'] ?? 0;
        $stmt->close();
    }
}

// تعريف الثوابت للصور إذا لم تكن معرفة مسبقاً
if (!defined('DEFAULT_MEAL_IMAGE')) {
   define('DEFAULT_MEAL_IMAGE', 'assets/images/no-image.png');
}

if (!defined('DEFAULT_SLIDER_IMAGE')) {
    define('DEFAULT_SLIDER_IMAGE', 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 400"%3E%3Crect width="1200" height="400" fill="%23F57C00"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" fill="white" font-family="Tajawal" font-size="32"%3Eماكس للمأكولات%3C/text%3E%3C/svg%3E');
}

// مفتاح MapTiler - يمكنك الحصول على مفتاح مجاني من https://www.maptiler.com
$MAPTILER_KEY = 'cl2LxR2PHiUdQSrmWQeb';

// تمرير آمن للبيانات إلى JavaScript
$safe_sliders = json_encode($sliders_array, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
$safe_user_name = htmlspecialchars($customer_name, ENT_QUOTES, 'UTF-8');
$safe_user_phone = htmlspecialchars($customer_phone, ENT_QUOTES, 'UTF-8');
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <meta name="theme-color" content="#F57C00">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="telephone=no">
    <title>ماكس | الرئيسية</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }
        
        :root {
            --primary: #F57C00;
            --primary-dark: #E65100;
            --primary-light: #FFB74D;
            --primary-soft: #FFF3E0;
            --accent: #FF9800;
            --success: #4CAF50;
            --danger: #F44336;
            --dark: #2E3B4E;
            --gray: #78909C;
            --gray-light: #ECEFF1;
            --white: #FFFFFF;
            --whatsapp: #25D366;
            --sms: #34B7F1;
            --shadow-sm: 0 2px 8px rgba(0,0,0,0.08);
            --shadow-md: 0 4px 16px rgba(0,0,0,0.12);
            --radius-md: 16px;
            --radius-round: 100px;
            --header-height: 60px;
        }

        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8f9fa;
            padding-top: var(--header-height);
            padding-bottom: 70px;
        }

        /* Header */
        .main-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: var(--header-height);
            z-index: 1000;
            display: flex;
            align-items: center;
            padding: 0 15px;
            box-shadow: var(--shadow-md);
        }
        
        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
        }
        
        .menu-toggle, .icon-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
        }
        
        .menu-toggle:active, .icon-btn:active { 
            transform: scale(0.95); 
            background: rgba(255,255,255,0.3); 
        }
        
        .restaurant-name {
            color: white;
            font-size: 1.3rem;
            font-weight: 800;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .header-right { display: flex; gap: 8px; position: relative; }
        
        .badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: var(--danger);
            color: white;
            font-size: 11px;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid white;
            font-weight: bold;
        }

        /* Sidebar RTL */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            display: none;
            backdrop-filter: blur(3px);
        }
        
        .sidebar-overlay.active { display: block; }
        
        .sidebar {
            position: fixed;
            top: 0;
            right: -300px;
            width: 280px;
            height: 100vh;
            background: white;
            z-index: 2001;
            transition: right 0.3s cubic-bezier(0.4,0,0.2,1);
            display: flex;
            flex-direction: column;
            box-shadow: -5px 0 20px rgba(0,0,0,0.2);
        }
        
        .sidebar.active { right: 0; }
        
        .sidebar-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 30px 20px;
            position: relative;
        }
        
        .sidebar-close {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(255,255,255,0.2);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            cursor: pointer;
        }
        
        .sidebar-user { text-align: center; }
        
        .sidebar-avatar {
            width: 70px;
            height: 70px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            margin: 0 auto 10px;
            border: 3px solid rgba(255,255,255,0.3);
        }
        
        .sidebar-name { font-weight: 700; font-size: 1.2rem; }
        .sidebar-email { font-size: 0.85rem; opacity: 0.9; }
        .sidebar-menu { flex: 1; overflow-y: auto; }
        
        .menu-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--dark);
            text-decoration: none;
            border-bottom: 1px solid var(--gray-light);
        }
        
        .menu-item:active { background: var(--primary-soft); }
        .menu-item i { width: 30px; color: var(--primary); font-size: 1.2rem; }
        .menu-item span { flex: 1; font-weight: 500; text-align: right; }
        
        .menu-badge {
            background: var(--danger);
            color: white;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: bold;
        }
        
        .sidebar-footer {
            padding: 20px;
            text-align: center;
            border-top: 1px solid var(--gray-light);
            color: var(--gray);
            font-size: 0.85rem;
        }

        /* Carousel */
        .carousel-container {
            width: 100%;
            height: 180px;
            overflow: hidden;
            position: relative;
            margin-bottom: 15px;
        }
        
        .carousel { width: 100%; height: 100%; position: relative; }
        .carousel-inner { width: 100%; height: 100%; position: relative; }
        
        .carousel-item {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .carousel-item.active { opacity: 1; }
        .carousel-item img { 
            width: 100%; 
            height: 100%; 
            object-fit: cover;
            background: var(--primary-soft);
        }
        
        .carousel-indicators {
            position: absolute;
            bottom: 15px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 8px;
            z-index: 10;
        }
        
        .carousel-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255,255,255,0.5);
            border: none;
            cursor: pointer;
        }
        
        .carousel-indicator.active { background: white; width: 20px; border-radius: 10px; }
        
        .carousel-control {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.3);
            border: none;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            cursor: pointer;
            z-index: 10;
        }
        
        .carousel-control.prev { right: 10px; }
        .carousel-control.next { left: 10px; }

        /* Categories */
        .categories-container {
            background: white;
            padding: 10px 15px;
            border-bottom: 1px solid var(--gray-light);
            overflow-x: auto;
            white-space: nowrap;
            margin-bottom: 15px;
            direction: rtl;
        }
        
        .categories-scroll { display: flex; gap: 10px; }
        
        .category-btn {
            padding: 8px 20px;
            background: white;
            border: 2px solid var(--primary-light);
            color: var(--primary);
            border-radius: var(--radius-round);
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .category-btn.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-color: transparent;
        }

        /* Search RTL */
        .search-wrapper { padding: 0 15px 15px; }
        .search-box { position: relative; }
        
        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary);
        }
        
        #instant-search {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid var(--primary-light);
            border-radius: var(--radius-round);
            font-family: 'Tajawal', sans-serif;
            font-size: 15px;
            text-align: right;
        }
        
        #instant-search:focus { outline: none; border-color: var(--primary); }
        
        .clear-search {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: var(--gray-light);
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            color: var(--gray);
            display: none;
            cursor: pointer;
        }
        
        .clear-search.visible { display: flex; align-items: center; justify-content: center; }

        /* Meals Grid */
        .meals-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 0 15px;
        }
        
        .meal-card {
            background: white;
            border-radius: var(--radius-md);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--gray-light);
            transition: transform 0.2s ease;
        }
        
        .meal-card:active { transform: scale(0.98); }
        
        .meal-image {
            width: 100%;
            height: 130px;
            object-fit: cover;
            background: linear-gradient(135deg, var(--primary-soft), var(--gray-light));
        }
        
        .meal-content { padding: 12px; }
        
        .meal-title {
            font-size: 15px;
            font-weight: 700;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .meal-category {
            font-size: 11px;
            color: var(--gray);
            margin-bottom: 8px;
        }
        
        .meal-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .meal-price {
            font-weight: 800;
            color: var(--primary);
            font-size: 15px;
        }
        
        .add-to-cart-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            border: none;
            border-radius: var(--radius-round);
            padding: 6px 12px;
            color: white;
            font-size: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 4px;
            cursor: pointer;
        }
        
        .add-to-cart-btn.loading { opacity: 0.7; pointer-events: none; }
        .add-to-cart-btn.loading i { animation: spin 1s linear infinite; }
        
        @keyframes spin { 
            from { transform: rotate(0deg); } 
            to { transform: rotate(360deg); } 
        }
        
        .portion-badge {
            background: var(--primary-soft);
            color: var(--primary);
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
        }
        
        .empty-state {
            grid-column: 1/-1;
            text-align: center;
            padding: 40px 20px;
            color: var(--gray);
        }

        /* Modals - RTL محسّن */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(3px);
        }
        
        .modal-overlay.active { display: flex; }
        
        .modal-content {
            background: white;
            border-radius: var(--radius-md);
            width: 92%;
            max-width: 450px;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalPop 0.3s ease;
            direction: rtl;
        }
        
        @keyframes modalPop {
            from { transform: scale(0.8); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 20px;
            border-radius: var(--radius-md) var(--radius-md) 0 0;
            position: relative;
            text-align: center;
        }
        
        .modal-header h3 { margin: 0; font-size: 1.2rem; }
        
        .modal-close {
            position: absolute;
            top: 15px;
            left: 15px;
            background: rgba(255,255,255,0.2);
            border: none;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .modal-body { 
            padding: 25px;
            text-align: right;
        }
        
        .form-group { margin-bottom: 20px; }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark);
            text-align: right;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid var(--primary-light);
            border-radius: 15px;
            font-family: 'Tajawal', sans-serif;
            font-size: 15px;
            text-align: right;
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(245,124,0,0.1);
        }
        
        .btn {
            padding: 14px;
            border: none;
            border-radius: var(--radius-round);
            font-weight: 700;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }
        
        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary-light);
            color: var(--primary);
        }
        
        .auth-link {
            text-align: center;
            margin-top: 15px;
            color: var(--gray);
        }
        
        .auth-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 600;
        }
        
        .otp-input {
            text-align: center;
            font-size: 24px;
            letter-spacing: 8px;
            direction: ltr;
        }
        
        .phone-input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            direction: ltr;
            background: white;
            border-radius: 15px;
            border: 2px solid var(--primary-light);
            overflow: hidden;
        }
        
        .phone-prefix {
            background: var(--primary-soft);
            padding: 12px 15px;
            color: var(--primary);
            font-weight: 700;
            font-size: 14px;
            border-right: 1px solid var(--primary-light);
            display: flex;
            align-items: center;
            height: 100%;
        }

        .phone-input-wrapper .form-control {
            border: none !important;
            border-radius: 0;
            padding: 12px 15px;
            flex: 1;
            text-align: left;
            letter-spacing: 1px;
        }

        .phone-input-wrapper .form-control:focus {
            box-shadow: none;
        }

        .phone-input-wrapper:focus-within {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(245,124,0,0.1);
        }      
        
        .whatsapp-badge {
            background: var(--whatsapp);
            color: white;
            padding: 10px;
            border-radius: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-bottom: 20px;
        }
        
        .sms-badge {
            background: var(--sms);
            color: white;
            padding: 10px;
            border-radius: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .sms-badge.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
        }
        
        .method-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .method-btn {
            flex: 1;
            padding: 12px;
            border: 2px solid var(--primary-light);
            border-radius: 15px;
            background: white;
            color: var(--dark);
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .method-btn.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-color: transparent;
        }
        
        .method-btn i { font-size: 1.2rem; }
        
        .otp-timer {
            text-align: center;
            color: var(--gray);
            font-size: 14px;
            margin-top: 15px;
        }
        
        .otp-timer span { color: var(--primary); font-weight: bold; }

        /* Portion Modal */
        .portion-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin: 20px 0;
        }
        
        .portion-option {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px;
            border: 2px solid var(--primary-light);
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .portion-option.active {
            border-color: var(--primary);
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }
        
        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            margin: 20px 0;
        }
        
        .quantity-btn {
            width: 44px;
            height: 44px;
            border: none;
            background: var(--primary-light);
            border-radius: 50%;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .quantity-btn:active { transform: scale(0.95); }
        
        .quantity-value {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--primary);
            min-width: 50px;
            text-align: center;
        }
        
        .modal-total {
            background: var(--gray-light);
            padding: 15px;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .total-label { font-weight: 600; margin-bottom: 5px; }
        .total-price { font-size: 1.5rem; font-weight: 800; color: var(--primary); }
        
        .modal-buttons { display: flex; gap: 10px; }
        
        .modal-btn {
            flex: 1;
            padding: 14px;
            border: none;
            border-radius: var(--radius-round);
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .modal-btn:active { transform: scale(0.98); }
        .modal-btn.cancel { background: var(--gray-light); color: var(--dark); }
        .modal-btn.confirm { background: linear-gradient(135deg, var(--primary), var(--accent)); color: white; }

        /* Map */
        #map {
            height: 300px;
            width: 100%;
            border-radius: 15px;
            margin-bottom: 15px;
            z-index: 1;
            background: #f0f0f0;
        }
        
        .selected-location {
            background: var(--primary-soft);
            padding: 15px;
            border-radius: 15px;
            margin-bottom: 15px;
        }
        
        .location-coords {
            color: var(--gray);
            font-size: 0.9rem;
            direction: ltr;
            text-align: left;
        }
        
        .map-loading {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f5f5f5;
            flex-direction: column;
        }
        
        .map-error {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f5f5f5;
            flex-direction: column;
            padding: 20px;
            text-align: center;
        }

        /* Toast */
        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 4000;
            pointer-events: none;
        }
        
        .toast-message {
            background: white;
            border-radius: 15px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            gap: 10px;
            border-right: 5px solid var(--success);
            animation: slideDown 0.3s ease;
            pointer-events: auto;
            direction: rtl;
        }
        
        .toast-message.success { border-right-color: var(--success); }
        .toast-message.error { border-right-color: var(--danger); }
        .toast-message.warning { border-right-color: #FF9800; }
        .toast-message.info { border-right-color: var(--sms); }
        
        @keyframes slideDown {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        /* Loading Spinner */
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }
        
        /* تحسينات للأداء */
        img {
            will-change: transform;
            transform: translateZ(0);
        }
        
        .meal-card, .category-btn, .add-to-cart-btn {
            will-change: transform;
        }
        
        /* منع ارتجاج الصور */
        .meal-image.loaded {
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
        
        /* تحسينات للجوال */
        @media (max-width: 480px) {
            .meals-grid {
                gap: 10px;
            }
            .meal-content {
                padding: 8px;
            }
            .meal-title {
                font-size: 13px;
            }
            .add-to-cart-btn {
                padding: 4px 8px;
                font-size: 11px;
            }
        }
        
        /* مؤشر التحقق */
        .verified-badge {
            background: var(--success);
            color: white;
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
            margin-right: 8px;
        }
    </style>
</head>
<body>

<!-- Header -->
<header class="main-header">
    <div class="header-content">
        <div class="header-left">
            <button class="menu-toggle" onclick="openSidebar()"><i class="bi bi-list"></i></button>
        </div>
        <div class="header-center">
            <span class="restaurant-name"><i class="bi bi-shop"></i> ماكس</span>
        </div>
        <div class="header-right">
            <?php if ($is_logged_in): ?>
            <a href="profile.php" class="icon-btn"><i class="bi bi-person-circle"></i></a>
            <?php else: ?>
            <button class="icon-btn" onclick="openAuthModal('login')"><i class="bi bi-person"></i></button>
            <?php endif; ?>
            <a href="support.php" class="icon-btn" style="position: relative;">
                <i class="bi bi-bell"></i>
                <?php if($unread_tickets > 0): ?>
                <span class="badge"><?= $unread_tickets ?></span>
                <?php endif; ?>
            </a>
        </div>
    </div>
</header>

<!-- Sidebar -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <button class="sidebar-close" onclick="closeSidebar()"><i class="bi bi-x"></i></button>
        <div class="sidebar-user">
            <div class="sidebar-avatar"><i class="bi bi-person-circle"></i></div>
            <div class="sidebar-name"><?= $safe_user_name ?></div>
            <div class="sidebar-email"><?= $safe_user_phone ?></div>
        </div>
    </div>
    <div class="sidebar-menu">
        <a href="home.php" class="menu-item"><i class="bi bi-house-door"></i><span>الرئيسية</span></a>
        <a href="cart.php" class="menu-item"><i class="bi bi-cart3"></i><span>السلة</span><span class="menu-badge" id="cart-count-sidebar"><?= $cart_count ?></span></a>
        <a href="orders.php" class="menu-item"><i class="bi bi-receipt"></i><span>طلباتي</span></a>
        <a href="profile.php" class="menu-item"><i class="bi bi-person"></i><span>حسابي</span></a>
        <a href="privacy.php" class="menu-item"><i class="bi bi-shield-lock"></i><span>سياسة الخصوصية</span></a>
        <a href="about.php" class="menu-item"><i class="bi bi-info-circle"></i><span>عن المطعم</span></a>
        <?php if ($is_logged_in): ?>
        <a href="logout.php" class="menu-item" style="color: var(--danger);"><i class="bi bi-box-arrow-left" style="color: var(--danger);"></i><span>تسجيل الخروج</span></a>
        <?php endif; ?>
    </div>
    <div class="sidebar-footer"><small>ماكس © 2026</small></div>
</div>

<!-- Carousel -->
<?php if (!empty($sliders_array)): ?>
<div class="carousel-container">
    <div class="carousel" id="mainCarousel">
        <div class="carousel-inner">
            <?php foreach($sliders_array as $index => $slide): 
                $slide_img = !empty($slide['image']) && file_exists('../../admin7/uploads/' . $slide['image']) 
                    ? '../../admin7/uploads/' . $slide['image'] 
                    : DEFAULT_SLIDER_IMAGE;
            ?>
            <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>">
                <img src="<?= htmlspecialchars($slide_img) ?>" alt="سلايدر ماكس" loading="lazy" onerror="this.src='<?= DEFAULT_SLIDER_IMAGE ?>'">
            </div>
            <?php endforeach; ?>
        </div>
        <?php if(count($sliders_array) > 1): ?>
        <div class="carousel-indicators">
            <?php foreach($sliders_array as $index => $slide): ?>
            <button class="carousel-indicator <?= $index === 0 ? 'active' : '' ?>" onclick="goToSlide(<?= $index ?>)"></button>
            <?php endforeach; ?>
        </div>
        <button class="carousel-control prev" onclick="prevSlide()"><i class="bi bi-chevron-right"></i></button>
        <button class="carousel-control next" onclick="nextSlide()"><i class="bi bi-chevron-left"></i></button>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Categories -->
<div class="categories-container">
    <div class="categories-scroll">
        <button class="category-btn active" data-category="all" onclick="filterByCategory('all')">الكل</button>
        <?php if($categories && $categories->num_rows > 0): 
            $categories->data_seek(0);
            while($cat = $categories->fetch_assoc()): 
        ?>
        <button class="category-btn" data-category="<?= (int)$cat['id'] ?>" onclick="filterByCategory(<?= (int)$cat['id'] ?>)"><?= htmlspecialchars($cat['name']) ?></button>
        <?php endwhile; endif; ?>
    </div>
</div>

<!-- Search -->
<div class="search-wrapper">
    <div class="search-box">
        <i class="bi bi-search search-icon"></i>
        <input type="text" id="instant-search" placeholder="ابحث عن وجبة..." autocomplete="off">
        <button class="clear-search" id="clear-search" onclick="clearSearch()"><i class="bi bi-x"></i></button>
    </div>
</div>

<!-- Meals Grid -->
<div class="meals-grid" id="meals-grid">
    <?php if ($all_meals && $all_meals->num_rows > 0): 
        while ($meal = $all_meals->fetch_assoc()): 
            $img = !empty($meal['image']) && file_exists('../../admin7/uploads/'.$meal['image']) 
                ? '../../admin7/uploads/'.$meal['image'] 
                : DEFAULT_MEAL_IMAGE;
            $portions = getMealPortions($conn, $meal['id']);
            $has_portions = $meal['has_portions'] && !empty($portions);
            $safe_name = htmlspecialchars($meal['name'], ENT_QUOTES, 'UTF-8');
            $safe_category = htmlspecialchars($meal['category_name'] ?? '', ENT_QUOTES, 'UTF-8');
    ?>
    <div class="meal-card" data-category-id="<?= (int)$meal['category_id'] ?>" data-name="<?= strtolower($safe_name) ?>" data-meal-id="<?= (int)$meal['id'] ?>">
        <img src="<?= htmlspecialchars($img) ?>" class="meal-image" alt="<?= $safe_name ?>" loading="lazy" onerror="this.src='<?= DEFAULT_MEAL_IMAGE ?>'">
        <div class="meal-content">
            <h3 class="meal-title">
                <?= $safe_name ?>
                <?php if($has_portions): ?>
                <span class="portion-badge"><i class="bi bi-tags"></i></span>
                <?php endif; ?>
            </h3>
            <div class="meal-category"><?= $safe_category ?></div>
            <div class="meal-footer">
                <span class="meal-price"><?= number_format((float)$meal['price'], 0) ?> ريال</span>
                <?php if ($has_portions): ?>
                <button class="add-to-cart-btn" 
                        data-meal-id="<?= (int)$meal['id'] ?>"
                        data-meal-name="<?= $safe_name ?>"
                        data-meal-price="<?= (float)$meal['price'] ?>"
                        data-has-portions="true"
                        onclick='openPortionModal(this, <?= json_encode($portions, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                    <i class="bi bi-cart-plus"></i>
                </button>
                <?php else: ?>
                <button class="add-to-cart-btn" 
                        data-meal-id="<?= (int)$meal['id'] ?>"
                        data-meal-name="<?= $safe_name ?>"
                        data-meal-price="<?= (float)$meal['price'] ?>"
                        data-has-portions="false"
                        onclick="addToCart(this, 1, null, 'كامل', <?= (float)$meal['price'] ?>)">
                    <i class="bi bi-cart-plus"></i>
                </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endwhile; else: ?>
    <div class="empty-state"><i class="bi bi-emoji-frown" style="font-size:3rem;"></i><h3>لا توجد وجبات</h3><p>سيتم إضافة وجبات قريباً</p></div>
    <?php endif; ?>
</div>

<!-- Portion Modal -->
<div class="modal-overlay" id="portionModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalMealName"></h3>
            <button class="modal-close" onclick="closePortionModal()"><i class="bi bi-x"></i></button>
        </div>
        <div class="modal-body">
            <p>اختر القسم المناسب</p>
            <div class="portion-options" id="portionOptions"></div>
            <div class="quantity-control">
                <button class="quantity-btn" onclick="modalChangeQuantity(-1)">−</button>
                <span class="quantity-value" id="modalQuantity">1</span>
                <button class="quantity-btn" onclick="modalChangeQuantity(1)">+</button>
            </div>
            <div class="modal-total">
                <div class="total-label">الإجمالي</div>
                <div class="total-price" id="modalTotal">0 ريال</div>
            </div>
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closePortionModal()">إلغاء</button>
                <button class="modal-btn confirm" onclick="confirmAddToCart()">إضافة للسلة</button>
            </div>
        </div>
    </div>
</div>

<!-- Auth Modal -->
<div class="modal-overlay" id="authModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="authModalTitle">تسجيل الدخول</h3>
            <button class="modal-close" onclick="closeAuthModal()"><i class="bi bi-x"></i></button>
        </div>
        <div class="modal-body">
            <!-- طريقة التحقق - اختيار SMS أو WhatsApp -->
            <div class="method-selector" id="methodSelector" style="display: none;">
                <button class="method-btn active" onclick="selectMethod('sms')">
                    <i class="bi bi-chat-dots"></i> رسالة نصية
                </button>
                <button class="method-btn" onclick="selectMethod('whatsapp')">
                    <i class="bi bi-whatsapp"></i> واتساب
                </button>
            </div>
            
            <div id="smsInfo" class="sms-badge" style="display: none;">
                <i class="bi bi-chat-dots"></i> سيتم إرسال رمز التحقق عبر رسالة نصية SMS
            </div>
            <div id="whatsappInfo" class="whatsapp-badge" style="display: none;">
                <i class="bi bi-whatsapp"></i> سيتم إرسال رمز التحقق عبر واتساب
            </div>
            
            <!-- Login Form -->
            <div id="loginForm" class="auth-form">
                <form onsubmit="handleLogin(event)">
                    <div class="form-group">
                        <label class="form-label">رقم الهاتف</label>
                        <div class="phone-input-wrapper">
                            <span class="phone-prefix">+967</span>
                            <input type="tel" id="loginPhone" class="form-control" required pattern="[0-9]{9}" maxlength="9" placeholder="7xxxxxxxx">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">كلمة المرور</label>
                        <input type="password" id="loginPassword" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-box-arrow-in-right"></i> تسجيل الدخول</button>
                </form>
                <div class="auth-link"><a href="#" onclick="showForgotPassword()">نسيت كلمة المرور؟</a></div>
                <div class="auth-link">ليس لديك حساب؟ <a href="#" onclick="showRegisterForm()">إنشاء حساب جديد</a></div>
            </div>
            
            <!-- Register Form -->
            <div id="registerForm" class="auth-form" style="display: none;">
                <form onsubmit="handleRegister(event)">
                    <div class="form-group">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" id="regName" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">رقم الهاتف</label>
                        <div class="phone-input-wrapper">
                            <span class="phone-prefix">+967</span>
                            <input type="tel" id="regPhone" class="form-control" required pattern="[0-9]{9}" maxlength="9" placeholder="7xxxxxxxx">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">العنوان</label>
                        <div style="display: flex; gap: 8px;">
                            <input type="text" id="regAddress" class="form-control" required placeholder="عنوانك" style="flex:1;">
                            <button type="button" class="icon-btn" onclick="openLocationPicker('register')" style="background: var(--primary-soft); color: var(--primary); width: 50px;"><i class="bi bi-geo-alt"></i></button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">كلمة المرور</label>
                        <input type="password" id="regPassword" class="form-control" required minlength="6">
                    </div>
                    <div class="form-group">
                        <label class="form-label">تأكيد كلمة المرور</label>
                        <input type="password" id="regConfirmPassword" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-person-plus"></i> إنشاء حساب</button>
                </form>
                <div class="auth-link">لديك حساب؟ <a href="#" onclick="showLoginForm()">تسجيل الدخول</a></div>
            </div>
            
            <!-- OTP Verification -->
            <div id="otpForm" class="auth-form" style="display: none;">
                <p style="text-align: center;">📱 تم إرسال رمز التحقق إلى<br><strong id="otpPhoneDisplay" style="color: var(--primary);"></strong></p>
                <p style="text-align: center; font-size: 12px; color: var(--gray);" id="otpMethodDisplay"></p>
                <form onsubmit="handleOTPVerification(event)">
                    <div class="form-group">
                        <label class="form-label">رمز التحقق</label>
                        <input type="text" id="otpCode" class="form-control otp-input" required maxlength="6" pattern="[0-9]{6}" inputmode="numeric">
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg"></i> تأكيد</button>
                </form>
                <div class="otp-timer" id="otpTimer"></div>
                <div class="auth-link">
                    <button class="btn-outline" onclick="resendOTP()" id="resendBtn" style="width: 100%;"><i class="bi bi-arrow-repeat"></i> إعادة إرسال الرمز</button>
                </div>
            </div>
            
            <!-- Forgot Password -->
            <div id="forgotPasswordForm" class="auth-form" style="display: none;">
                <form onsubmit="handleForgotPassword(event)">
                    <div class="form-group">
                        <label class="form-label">رقم الهاتف</label>
                        <div class="phone-input-wrapper">
                            <span class="phone-prefix">+967</span>
                            <input type="tel" id="forgotPhone" class="form-control" required pattern="[0-9]{9}" maxlength="9" placeholder="7xxxxxxxx">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">طريقة التحقق</label>
                        <select id="forgotMethod" class="form-control">
                            <option value="sms">📱 رسالة نصية (SMS)</option>
                            <option value="whatsapp">💚 واتساب (WhatsApp)</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-envelope"></i> إرسال رمز التحقق</button>
                </form>
                <div class="auth-link"><a href="#" onclick="showLoginForm()">العودة لتسجيل الدخول</a></div>
            </div>
            
            <!-- Reset OTP -->
            <div id="resetOtpForm" class="auth-form" style="display: none;">
                <p style="text-align: center;">📱 تم إرسال رمز إعادة التعيين إلى<br><strong id="resetPhoneDisplay" style="color: var(--primary);"></strong></p>
                <form onsubmit="handleResetOTPVerification(event)">
                    <div class="form-group">
                        <label class="form-label">رمز التحقق</label>
                        <input type="text" id="resetOtpCode" class="form-control otp-input" required maxlength="6" pattern="[0-9]{6}" inputmode="numeric">
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg"></i> تأكيد</button>
                </form>
                <div class="otp-timer" id="resetOtpTimer"></div>
                <div class="auth-link">
                    <button class="btn-outline" onclick="resendResetOTP()" id="resendResetBtn" style="width: 100%;"><i class="bi bi-arrow-repeat"></i> إعادة إرسال الرمز</button>
                </div>
            </div>
            
            <!-- Reset Password -->
            <div id="resetPasswordForm" class="auth-form" style="display: none;">
                <form onsubmit="handleResetPassword(event)">
                    <input type="hidden" id="resetPhone">
                    <div class="form-group">
                        <label class="form-label">كلمة المرور الجديدة</label>
                        <input type="password" id="newPassword" class="form-control" required minlength="6">
                    </div>
                    <div class="form-group">
                        <label class="form-label">تأكيد كلمة المرور</label>
                        <input type="password" id="confirmNewPassword" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-key"></i> تغيير كلمة المرور</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Location Modal -->
<div class="modal-overlay" id="locationModal">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3>اختر موقع التوصيل</h3>
            <button class="modal-close" onclick="closeLocationPicker()"><i class="bi bi-x"></i></button>
        </div>
        <div class="modal-body">
            <div id="map"></div>
            <div class="selected-location">
                <p id="selectedAddress"></p>
                <div class="location-coords" id="selectedCoords"></div>
            </div>
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closeLocationPicker()">إلغاء</button>
                <button class="modal-btn confirm" onclick="confirmLocation()">تأكيد</button>
            </div>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// ===== Configuration =====
const basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
const ajaxUrl = basePath + 'ajax_handler.php';
const smsApiUrl = basePath + 'sms_api.php';
const defaultMealImage = '<?= DEFAULT_MEAL_IMAGE ?>';
const defaultSliderImage = '<?= DEFAULT_SLIDER_IMAGE ?>';
const MAPTILER_KEY = '<?= $MAPTILER_KEY ?>';

// ===== Variables =====
let currentSlide = 0;
const slides = <?= $safe_sliders ?>;
let slideInterval;
let currentMealId = null, currentMealName = '', currentPortions = [], selectedPortionId = null, selectedPortionName = 'كامل', selectedPortionPrice = 0, currentQuantity = 1, currentButton = null;
let currentCategory = 'all', searchTerm = '', otpTimerInterval = null, resetOtpTimerInterval = null, currentPhone = '', resetPhoneNumber = '';
let map, marker, currentLat = 14.5667, currentLng = 44.4000, mapInitialized = false, locationSource = 'register', selectedLat, selectedLng, selectedAddress = '';
let selectedMethod = 'sms'; // 'sms' or 'whatsapp'

// ===== Helper Functions =====
function showLoading(button) {
    if (!button) return;
    const originalHtml = button.innerHTML;
    button.disabled = true;
    button.classList.add('loading');
    button.innerHTML = '<div class="spinner"></div>';
    return originalHtml;
}

function hideLoading(button, originalHtml) {
    if (!button) return;
    button.disabled = false;
    button.classList.remove('loading');
    if (originalHtml) button.innerHTML = originalHtml;
}

function showToast(msg, type = 'success') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast-message ${type}`;
    let icon = type === 'success' ? 'check-circle' : (type === 'error' ? 'exclamation-circle' : (type === 'info' ? 'info-circle' : 'info-circle'));
    toast.innerHTML = `<div class="toast-icon"><i class="bi bi-${icon}"></i></div><div>${escapeHtml(msg)}</div>`;
    container.appendChild(toast);
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ===== Method Selection =====
function selectMethod(method) {
    selectedMethod = method;
    document.querySelectorAll('.method-btn').forEach(btn => btn.classList.remove('active'));
    document.querySelector(`.method-btn[onclick="selectMethod('${method}')"]`).classList.add('active');
    
    if (method === 'sms') {
        document.getElementById('smsInfo').style.display = 'flex';
        document.getElementById('whatsappInfo').style.display = 'none';
    } else {
        document.getElementById('smsInfo').style.display = 'none';
        document.getElementById('whatsappInfo').style.display = 'flex';
    }
}

// ===== Sidebar =====
function openSidebar() { 
    document.getElementById('sidebar').classList.add('active'); 
    document.getElementById('sidebarOverlay').classList.add('active'); 
    document.body.style.overflow = 'hidden'; 
}

function closeSidebar() { 
    document.getElementById('sidebar').classList.remove('active'); 
    document.getElementById('sidebarOverlay').classList.remove('active'); 
    document.body.style.overflow = ''; 
}

// ===== Carousel =====
function showSlide(index) {
    const items = document.querySelectorAll('.carousel-item'), indicators = document.querySelectorAll('.carousel-indicator');
    if (!items.length) return;
    if (index >= items.length) index = 0; 
    if (index < 0) index = items.length - 1;
    items.forEach(i => i.classList.remove('active')); 
    indicators.forEach(i => i.classList.remove('active'));
    items[index].classList.add('active'); 
    if (indicators[index]) indicators[index].classList.add('active');
    currentSlide = index;
}

function nextSlide() { showSlide(currentSlide + 1); resetInterval(); }
function prevSlide() { showSlide(currentSlide - 1); resetInterval(); }
function goToSlide(index) { showSlide(index); resetInterval(); }

function startInterval() { 
    if (slides.length > 1) slideInterval = setInterval(() => nextSlide(), 4000); 
}

function resetInterval() { 
    clearInterval(slideInterval); 
    startInterval(); 
}

if (slides.length > 1) startInterval();

// ===== Filter & Search =====
function filterByCategory(categoryId) {
    currentCategory = categoryId;
    document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
    const activeBtn = document.querySelector(`.category-btn[data-category="${categoryId}"]`);
    if (activeBtn) activeBtn.classList.add('active');
    if (categoryId === 'all') document.querySelector('.category-btn[data-category="all"]').classList.add('active');
    filterMeals();
    localStorage.setItem('selectedCategory', categoryId);
}

function filterMeals() {
    const meals = document.querySelectorAll('.meal-card');
    let visible = 0;
    meals.forEach(meal => {
        const match = (currentCategory === 'all' || meal.dataset.categoryId == currentCategory) && 
                     (meal.dataset.name || '').includes(searchTerm.toLowerCase());
        meal.style.display = match ? '' : 'none';
        if (match) visible++;
    });
    document.querySelector('.empty-state-dynamic')?.remove();
    if (visible === 0) {
        document.getElementById('meals-grid').insertAdjacentHTML('beforeend', 
            '<div class="empty-state empty-state-dynamic"><i class="bi bi-search"></i><h3>لا توجد نتائج</h3></div>');
    }
}

const searchInput = document.getElementById('instant-search');
if (searchInput) {
    searchInput.addEventListener('input', e => { 
        searchTerm = e.target.value.trim(); 
        document.getElementById('clear-search')?.classList.toggle('visible', searchTerm.length > 0); 
        filterMeals(); 
    });
}

function clearSearch() { 
    if (searchInput) { 
        searchInput.value = ''; 
        searchTerm = ''; 
        document.getElementById('clear-search')?.classList.remove('visible'); 
        filterMeals(); 
        searchInput.focus(); 
    } 
}

// ===== Portion Modal =====
function openPortionModal(button, portions) {
    currentMealId = parseInt(button.dataset.mealId);
    currentMealName = button.dataset.mealName;
    currentPortions = portions;
    currentQuantity = 1;
    currentButton = button;
    
    if (portions && portions.length > 0) { 
        selectedPortionId = portions[0].id; 
        selectedPortionName = portions[0].name; 
        selectedPortionPrice = parseFloat(portions[0].price); 
    }
    
    document.getElementById('modalMealName').textContent = currentMealName;
    document.getElementById('modalQuantity').textContent = currentQuantity;
    
    const container = document.getElementById('portionOptions');
    container.innerHTML = '';
    if (portions) {
        portions.forEach(p => {
            const div = document.createElement('div');
            div.className = 'portion-option' + (p.id === selectedPortionId ? ' active' : '');
            div.onclick = () => selectPortion(p.id, p.name, p.price);
            div.innerHTML = `<span class="portion-name">${escapeHtml(p.name)}</span><span class="portion-price">${parseFloat(p.price).toFixed(2)} ريال</span>`;
            container.appendChild(div);
        });
    }
    
    updateModalTotal();
    document.getElementById('portionModal').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function selectPortion(id, name, price) { 
    selectedPortionId = id; 
    selectedPortionName = name; 
    selectedPortionPrice = parseFloat(price); 
    document.querySelectorAll('.portion-option').forEach(opt => opt.classList.remove('active')); 
    event.currentTarget.classList.add('active'); 
    updateModalTotal(); 
}

function modalChangeQuantity(change) { 
    currentQuantity = Math.min(99, Math.max(1, currentQuantity + change)); 
    document.getElementById('modalQuantity').textContent = currentQuantity; 
    updateModalTotal(); 
}

function updateModalTotal() { 
    document.getElementById('modalTotal').textContent = (selectedPortionPrice * currentQuantity).toFixed(2) + ' ريال'; 
}

function closePortionModal() { 
    document.getElementById('portionModal').classList.remove('active'); 
    document.body.style.overflow = ''; 
}

function confirmAddToCart() { 
    if (currentButton) { 
        addToCart(currentButton, currentQuantity, selectedPortionId, selectedPortionName, selectedPortionPrice); 
        closePortionModal(); 
    } 
}

// ===== Cart Functions =====
async function checkAuth() { 
    try {
        const response = await fetch(ajaxUrl, { 
            method: 'POST', 
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=check_auth' 
        });
        return await response.json();
    } catch(e) { 
        return { logged_in: false }; 
    }
}

async function addToCart(button, quantity, portionId, portionName, portionPrice) {
    const auth = await checkAuth();
    if (!auth.logged_in) { 
        openAuthModal('login'); 
        showToast('الرجاء تسجيل الدخول أولاً', 'warning'); 
        return; 
    }
    
    const mealId = parseInt(button.dataset.mealId);
    const originalHtml = showLoading(button);
    
    const formData = new URLSearchParams();
    formData.append('action', 'add_to_cart');
    formData.append('meal_id', mealId);
    formData.append('quantity', quantity);
    formData.append('portion_id', portionId || '');
    formData.append('portion_name', portionName);
    formData.append('portion_price', portionPrice);
    formData.append('meal_name', button.dataset.mealName);
    
    try {
        const response = await fetch(ajaxUrl, { 
            method: 'POST', 
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData 
        });
        const data = await response.json();
        if (data.success) { 
            updateCartCount(data.cart_count); 
            showToast(data.message, 'success'); 
        } else { 
            showToast(data.message, 'error'); 
        }
    } catch(e) { 
        showToast('خطأ في الاتصال', 'error');
        console.error('Add to cart error:', e);
    } finally { 
        setTimeout(() => hideLoading(button, originalHtml), 500);
    }
}

function updateCartCount(count) { 
    const badge = document.getElementById('cart-count-sidebar'); 
    if (badge) { 
        badge.textContent = count; 
        badge.style.display = count > 0 ? 'inline-block' : 'none'; 
    } 
}

// ===== OTP Timer =====
function startOTPTimer() {
    let timeLeft = 60;
    if (otpTimerInterval) clearInterval(otpTimerInterval);
    otpTimerInterval = setInterval(() => {
        timeLeft--;
        const timerDisplay = document.getElementById('otpTimer');
        if (timerDisplay) timerDisplay.innerHTML = `يمكنك إعادة الإرسال بعد <span>${timeLeft}</span> ثانية`;
        if (timeLeft <= 0) {
            clearInterval(otpTimerInterval);
            if (timerDisplay) timerDisplay.innerHTML = '';
            const btn = document.getElementById('resendBtn');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="bi bi-arrow-repeat"></i> إعادة إرسال الرمز'; }
        }
    }, 1000);
    const btn = document.getElementById('resendBtn');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="bi bi-hourglass"></i> انتظر...'; }
}

function startResetOTPTimer() {
    let timeLeft = 60;
    if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
    resetOtpTimerInterval = setInterval(() => {
        timeLeft--;
        const timerDisplay = document.getElementById('resetOtpTimer');
        if (timerDisplay) timerDisplay.innerHTML = `يمكنك إعادة الإرسال بعد <span>${timeLeft}</span> ثانية`;
        if (timeLeft <= 0) {
            clearInterval(resetOtpTimerInterval);
            if (timerDisplay) timerDisplay.innerHTML = '';
            const btn = document.getElementById('resendResetBtn');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="bi bi-arrow-repeat"></i> إعادة إرسال الرمز'; }
        }
    }, 1000);
    const btn = document.getElementById('resendResetBtn');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="bi bi-hourglass"></i> انتظر...'; }
}

// ===== Map Functions with MapTiler =====
function openLocationPicker(source = 'register') { 
    document.getElementById('locationModal').classList.add('active'); 
    document.body.style.overflow = 'hidden'; 
    locationSource = source; 
    setTimeout(() => { 
        if (!mapInitialized) initMap(); 
        else { 
            if (map) {
                map.invalidateSize(); 
                map.setView([selectedLat || currentLat, selectedLng || currentLng], 15);
            } else {
                initMap();
            }
        } 
    }, 200); 
}

function closeLocationPicker() { 
    document.getElementById('locationModal').classList.remove('active'); 
    document.body.style.overflow = ''; 
}

function initMap() { 
    const mapContainer = document.getElementById('map');
    
    mapContainer.innerHTML = '<div class="map-loading"><div class="spinner"></div><span style="margin-top:10px;">جاري تحميل الخريطة...</span></div>';
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            pos => { 
                currentLat = pos.coords.latitude; 
                currentLng = pos.coords.longitude; 
                loadMapTiler(); 
            }, 
            () => { 
                console.log('تعذر الحصول على الموقع، استخدام الموقع الافتراضي');
                loadMapTiler(); 
            }
        );
    } else { 
        loadMapTiler(); 
    }
}

function loadMapTiler() {
    const mapContainer = document.getElementById('map');
    
    try {
        map = L.map('map').setView([currentLat, currentLng], 15);
        
        let tileUrl;
        let attribution;
        
        if (MAPTILER_KEY && MAPTILER_KEY !== 'YOUR_MAPTILER_API_KEY') {
            tileUrl = `https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=${MAPTILER_KEY}`;
            attribution = '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
        } else {
            tileUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
            attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
        }
        
        const tileLayer = L.tileLayer(tileUrl, {
            attribution: attribution,
            maxZoom: 19,
            errorTileUrl: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"%3E%3Crect width="100" height="100" fill="%23ddd"/%3E%3Ctext x="50" y="50" text-anchor="middle" dy=".3em"%3E❌%3C/text%3E%3C/svg%3E'
        });
        
        tileLayer.on('tileerror', function(e) {
            console.warn('خطأ في تحميل بلاطة الخريطة');
            if (!window.fallbackUsed) {
                window.fallbackUsed = true;
                showToast('جاري استخدام خادم خريطة بديل', 'info');
            }
        });
        
        tileLayer.addTo(map);
        
        marker = L.marker([currentLat, currentLng], { draggable: true }).addTo(map);
        marker.on('dragend', e => updateLocation(e.target.getLatLng().lat, e.target.getLatLng().lng));
        map.on('click', e => { 
            marker.setLatLng(e.latlng); 
            updateLocation(e.latlng.lat, e.latlng.lng); 
        });
        
        map.on('load', () => {
            console.log('تم تحميل الخريطة بنجاح');
        });
        
        updateLocation(currentLat, currentLng);
        mapInitialized = true;
        
    } catch(error) {
        console.error('خطأ في تحميل الخريطة:', error);
        showMapFallback();
    }
}

function showMapFallback() {
    const mapContainer = document.getElementById('map');
    mapContainer.innerHTML = `
        <div class="map-error">
            <i class="bi bi-map" style="font-size:48px; color:#F57C00;"></i>
            <p style="margin-top:15px; color:#666;">تعذر تحميل الخريطة</p>
            <p style="font-size:12px; color:#999; margin-bottom:15px;">يمكنك إدخال عنوانك يدوياً</p>
            <input type="text" id="manualAddress" class="form-control" placeholder="أدخل عنوان التوصيل" style="width:100%; margin-bottom:10px;">
            <button onclick="confirmManualAddress()" class="btn btn-primary" style="width:100%;">
                <i class="bi bi-check"></i> تأكيد العنوان
            </button>
            <button onclick="retryLoadMap()" class="btn-outline" style="width:100%; margin-top:10px;">
                <i class="bi bi-arrow-repeat"></i> إعادة المحاولة
            </button>
        </div>
    `;
    mapInitialized = false;
}

function confirmManualAddress() {
    const address = document.getElementById('manualAddress')?.value;
    if (address) {
        selectedAddress = address;
        selectedLat = null;
        selectedLng = null;
        closeLocationPicker();
        if (locationSource === 'register') {
            document.getElementById('regAddress').value = address;
        }
        showToast('تم حفظ العنوان بنجاح', 'success');
    } else {
        showToast('الرجاء إدخال العنوان', 'warning');
    }
}

function retryLoadMap() {
    mapInitialized = false;
    initMap();
}

function updateLocation(lat, lng) { 
    selectedLat = lat; 
    selectedLng = lng; 
    document.getElementById('selectedCoords').textContent = `📍 ${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    document.getElementById('selectedAddress').textContent = 'جاري البحث عن العنوان...';
    
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 8000);
    
    fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=ar`, {
        signal: controller.signal,
        headers: { 'User-Agent': 'MaxRestaurantApp/1.0' }
    })
    .then(r => {
        clearTimeout(timeoutId);
        if (!r.ok) throw new Error('فشل في تحميل العنوان');
        return r.json();
    })
    .then(data => { 
        const address = data.display_name || `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
        document.getElementById('selectedAddress').textContent = address; 
        selectedAddress = address; 
    })
    .catch(err => { 
        console.warn('فشل تحميل العنوان:', err);
        const fallbackAddress = `${lat.toFixed(4)}, ${lng.toFixed(4)} (ذمار - اليمن)`;
        document.getElementById('selectedAddress').textContent = fallbackAddress; 
        selectedAddress = fallbackAddress;
        
        if (!window.addressErrorShown) {
            showToast('تعذر تحميل العنوان، سيتم استخدام الإحداثيات', 'warning');
            window.addressErrorShown = true;
            setTimeout(() => { window.addressErrorShown = false; }, 5000);
        }
    }); 
}

function confirmLocation() { 
    if (!selectedAddress || !selectedLat || !selectedLng) {
        selectedAddress = `${selectedLat?.toFixed(4) || currentLat?.toFixed(4)}, ${selectedLng?.toFixed(4) || currentLng?.toFixed(4)}`;
    }
    
    if (locationSource === 'register') { 
        document.getElementById('regAddress').value = selectedAddress; 
        closeLocationPicker(); 
    } 
}

// ===== Auth Functions =====
function handleRegister(e) {
    e.preventDefault();
    let phone = document.getElementById('regPhone').value.replace(/[^0-9]/g, '');
    if (phone.length !== 9) return showToast('رقم الهاتف يجب أن يكون 9 أرقام', 'error');
    if (document.getElementById('regPassword').value !== document.getElementById('regConfirmPassword').value) return showToast('كلمات المرور غير متطابقة', 'error');
    if (document.getElementById('regPassword').value.length < 6) return showToast('كلمة المرور يجب أن تكون 6 أحرف أو أكثر', 'error');
    
    const formData = new URLSearchParams();
    formData.append('action', 'register');
    formData.append('name', document.getElementById('regName').value);
    formData.append('phone', phone);
    formData.append('address', document.getElementById('regAddress').value);
    formData.append('password', document.getElementById('regPassword').value);
    formData.append('confirm_password', document.getElementById('regConfirmPassword').value);
    
    if (selectedLat && selectedLng) {
        formData.append('latitude', selectedLat);
        formData.append('longitude', selectedLng);
    }
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => {
            if (data.success && data.needs_verification) { 
                currentPhone = phone; 
                showOTPForm(phone); 
                startOTPTimer(); 
                showToast(data.message, 'success'); 
                if (data.debug_otp) showToast('رمز التجربة: ' + data.debug_otp, 'info');
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { btn.disabled = false; btn.innerHTML = originalHtml; });
}

function showOTPForm(phone) {
    currentPhone = phone;
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'none';
    document.getElementById('otpForm').style.display = 'block';
    document.getElementById('forgotPasswordForm').style.display = 'none';
    document.getElementById('resetPasswordForm').style.display = 'none';
    document.getElementById('resetOtpForm').style.display = 'none';
    document.getElementById('methodSelector').style.display = 'none';
    document.getElementById('smsInfo').style.display = 'none';
    document.getElementById('whatsappInfo').style.display = 'none';
    document.getElementById('authModalTitle').textContent = 'تأكيد رقم الهاتف';
    document.getElementById('otpPhoneDisplay').innerHTML = '+967' + phone;
    document.getElementById('otpMethodDisplay').innerHTML = selectedMethod === 'sms' ? '📱 تم الإرسال عبر رسالة نصية' : '💚 تم الإرسال عبر واتساب';
    document.getElementById('otpCode').value = '';
}

function handleOTPVerification(e) {
    e.preventDefault();
    const otp = document.getElementById('otpCode').value;
    if (!otp || otp.length !== 6) return showToast('أدخل رمز التحقق 6 أرقام', 'error');
    
    const formData = new URLSearchParams();
    formData.append('action', 'verify_otp');
    formData.append('otp', otp);
    formData.append('phone', currentPhone);
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => {
            if (data.success) { 
                if (otpTimerInterval) clearInterval(otpTimerInterval); 
                closeAuthModal(); 
                showToast('تم التحقق! جاري تسجيل الدخول...', 'success'); 
                setTimeout(() => location.reload(), 1500); 
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { btn.disabled = false; btn.innerHTML = originalHtml; });
}

function resendOTP() {
    if (!currentPhone) return showToast('خطأ في الجلسة', 'error');
    
    const formData = new URLSearchParams();
    formData.append('action', 'resend_otp');
    formData.append('phone', currentPhone);
    
    const btn = document.getElementById('resendBtn');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => { 
            if (data.success) { 
                showToast(data.message, 'success'); 
                startOTPTimer(); 
                if (data.debug_otp) showToast('رمز التجربة: ' + data.debug_otp, 'info'); 
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { btn.disabled = false; btn.innerHTML = originalHtml; });
}

function handleLogin(e) {
    e.preventDefault();
    let phone = document.getElementById('loginPhone').value.replace(/[^0-9]/g, '');
    if (phone.length !== 9) return showToast('رقم الهاتف غير صالح', 'error');
    const password = document.getElementById('loginPassword').value;
    if (!password) return showToast('كلمة المرور مطلوبة', 'error');
    
    const formData = new URLSearchParams();
    formData.append('action', 'login');
    formData.append('phone', phone);
    formData.append('password', password);
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => { 
            if (data.success) { 
                closeAuthModal(); 
                showToast('تم تسجيل الدخول بنجاح', 'success'); 
                setTimeout(() => location.reload(), 1500); 
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { btn.disabled = false; btn.innerHTML = originalHtml; });
}

function handleForgotPassword(e) {
    e.preventDefault();
    let phone = document.getElementById('forgotPhone').value.replace(/[^0-9]/g, '');
    if (phone.length !== 9) {
        showToast('رقم الهاتف غير صالح', 'error');
        return;
    }
    resetPhoneNumber = phone;
    
    const method = document.getElementById('forgotMethod').value;
    
    const formData = new URLSearchParams();
    formData.append('action', 'forgot_password');
    formData.append('phone', phone);
    formData.append('method', method);
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { 
        method: 'POST', 
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData 
    })
    .then(r => r.json())
    .then(data => { 
        if (data.success) { 
            sessionStorage.setItem('reset_phone', phone); 
            if (data.debug_otp) {
                showToast('رمز التجربة: ' + data.debug_otp, 'info');
            }
            showResetOTPForm(phone); 
            showToast(data.message, 'success'); 
        } else { 
            showToast(data.message, 'error'); 
        }
    })
    .catch(() => showToast('خطأ في الاتصال', 'error'))
    .finally(() => { 
        btn.disabled = false; 
        btn.innerHTML = originalHtml; 
    });
}

function showResetOTPForm(phone) {
    resetPhoneNumber = phone;
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'none';
    document.getElementById('otpForm').style.display = 'none';
    document.getElementById('forgotPasswordForm').style.display = 'none';
    document.getElementById('resetPasswordForm').style.display = 'none';
    document.getElementById('resetOtpForm').style.display = 'block';
    document.getElementById('methodSelector').style.display = 'none';
    document.getElementById('smsInfo').style.display = 'none';
    document.getElementById('whatsappInfo').style.display = 'none';
    document.getElementById('resetPhoneDisplay').innerHTML = '+967' + phone;
    document.getElementById('resetOtpCode').value = '';
    document.getElementById('authModalTitle').textContent = 'تأكيد إعادة التعيين';
    startResetOTPTimer();
}

function handleResetOTPVerification(e) {
    e.preventDefault();
    const otp = document.getElementById('resetOtpCode').value;
    if (!otp || otp.length !== 6) {
        showToast('أدخل رمز التحقق 6 أرقام', 'error');
        return;
    }
    const phone = resetPhoneNumber || sessionStorage.getItem('reset_phone');
    if (!phone) {
        showToast('خطأ في الجلسة، يرجى المحاولة مرة أخرى', 'error');
        return;
    }
    
    const formData = new URLSearchParams();
    formData.append('action', 'verify_reset_otp');
    formData.append('otp', otp);
    formData.append('phone', phone);
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => { 
            if (data.success) { 
                sessionStorage.setItem('verified_otp', otp); 
                showResetPasswordForm(phone); 
                showToast('تم التحقق من الرمز', 'success'); 
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { 
            btn.disabled = false; 
            btn.innerHTML = originalHtml; 
        });
}

function showResetPasswordForm(phone) {
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'none';
    document.getElementById('otpForm').style.display = 'none';
    document.getElementById('forgotPasswordForm').style.display = 'none';
    document.getElementById('resetOtpForm').style.display = 'none';
    document.getElementById('resetPasswordForm').style.display = 'block';
    document.getElementById('methodSelector').style.display = 'none';
    document.getElementById('resetPhone').value = phone;
    document.getElementById('authModalTitle').textContent = 'كلمة مرور جديدة';
}

function handleResetPassword(e) {
    e.preventDefault();
    const phone = document.getElementById('resetPhone').value;
    const password = document.getElementById('newPassword').value;
    const confirm = document.getElementById('confirmNewPassword').value;
    const otp = sessionStorage.getItem('verified_otp');
    
    if (password !== confirm) {
        showToast('كلمات المرور غير متطابقة', 'error');
        return;
    }
    if (password.length < 6) {
        showToast('كلمة المرور 6 أحرف على الأقل', 'error');
        return;
    }
    if (!otp) {
        showToast('لم يتم التحقق من الرمز، يرجى طلب رمز جديد', 'error');
        return;
    }
    
    const formData = new URLSearchParams();
    formData.append('action', 'reset_password');
    formData.append('phone', phone);
    formData.append('password', password);
    formData.append('confirm_password', confirm);
    formData.append('otp', otp);
    
    const btn = e.target.querySelector('button');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => { 
            if (data.success) { 
                sessionStorage.removeItem('reset_phone'); 
                sessionStorage.removeItem('verified_otp'); 
                if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
                closeAuthModal(); 
                showToast('تم تغيير كلمة المرور بنجاح', 'success'); 
                setTimeout(() => location.reload(), 1500); 
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { 
            btn.disabled = false; 
            btn.innerHTML = originalHtml; 
        });
}

function resendResetOTP() {
    const phone = resetPhoneNumber || sessionStorage.getItem('reset_phone');
    if (!phone) {
        showToast('خطأ في الجلسة', 'error');
        return;
    }
    
    const formData = new URLSearchParams();
    formData.append('action', 'forgot_password');
    formData.append('phone', phone);
    
    const btn = document.getElementById('resendResetBtn');
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<div class="spinner"></div>';
    
    fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData })
        .then(r => r.json())
        .then(data => { 
            if (data.success) { 
                if (data.debug_otp) showToast('رمز التجربة: ' + data.debug_otp, 'info'); 
                showToast('تم إعادة إرسال الرمز', 'success');
                if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
                startResetOTPTimer();
            } else { 
                showToast(data.message, 'error'); 
            }
        })
        .catch(() => showToast('خطأ في الاتصال', 'error'))
        .finally(() => { 
            btn.disabled = false; 
            btn.innerHTML = originalHtml; 
        });
}

// ===== Modal Controls =====
function openAuthModal(type = 'login') { 
    document.getElementById('authModal').classList.add('active'); 
    document.body.style.overflow = 'hidden'; 
    if (type === 'login') showLoginForm(); 
    else showRegisterForm(); 
}

function closeAuthModal() { 
    document.getElementById('authModal').classList.remove('active'); 
    document.body.style.overflow = ''; 
    if (otpTimerInterval) clearInterval(otpTimerInterval); 
    if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
    setTimeout(() => { showLoginForm(); }, 300); 
}

function showLoginForm() { 
    document.getElementById('loginForm').style.display = 'block'; 
    document.getElementById('registerForm').style.display = 'none'; 
    document.getElementById('otpForm').style.display = 'none'; 
    document.getElementById('forgotPasswordForm').style.display = 'none'; 
    document.getElementById('resetPasswordForm').style.display = 'none'; 
    document.getElementById('resetOtpForm').style.display = 'none'; 
    document.getElementById('methodSelector').style.display = 'none';
    document.getElementById('smsInfo').style.display = 'none';
    document.getElementById('whatsappInfo').style.display = 'none';
    document.getElementById('authModalTitle').textContent = 'تسجيل الدخول'; 
    if (otpTimerInterval) clearInterval(otpTimerInterval); 
    if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
}

function showRegisterForm() { 
    document.getElementById('loginForm').style.display = 'none'; 
    document.getElementById('registerForm').style.display = 'block'; 
    document.getElementById('otpForm').style.display = 'none'; 
    document.getElementById('forgotPasswordForm').style.display = 'none'; 
    document.getElementById('resetPasswordForm').style.display = 'none'; 
    document.getElementById('resetOtpForm').style.display = 'none'; 
    document.getElementById('methodSelector').style.display = 'flex';
    document.getElementById('smsInfo').style.display = 'flex';
    document.getElementById('whatsappInfo').style.display = 'none';
    document.getElementById('authModalTitle').textContent = 'إنشاء حساب'; 
    selectedMethod = 'sms';
    if (otpTimerInterval) clearInterval(otpTimerInterval); 
    if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
}

function showForgotPassword() { 
    document.getElementById('loginForm').style.display = 'none'; 
    document.getElementById('registerForm').style.display = 'none'; 
    document.getElementById('otpForm').style.display = 'none'; 
    document.getElementById('resetPasswordForm').style.display = 'none'; 
    document.getElementById('resetOtpForm').style.display = 'none'; 
    document.getElementById('forgotPasswordForm').style.display = 'block'; 
    document.getElementById('methodSelector').style.display = 'none';
    document.getElementById('smsInfo').style.display = 'none';
    document.getElementById('whatsappInfo').style.display = 'none';
    document.getElementById('authModalTitle').textContent = 'استعادة كلمة المرور'; 
    if (otpTimerInterval) clearInterval(otpTimerInterval); 
    if (resetOtpTimerInterval) clearInterval(resetOtpTimerInterval);
}

// ===== Image Loading Optimization =====
document.addEventListener('DOMContentLoaded', () => {
    const images = document.querySelectorAll('img');
    images.forEach(img => {
        img.addEventListener('load', function() {
            this.classList.add('loaded');
        });
        if (img.complete) {
            img.classList.add('loaded');
        }
    });
    
    const saved = localStorage.getItem('selectedCategory');
    if (saved && saved !== 'all') { 
        const btn = document.querySelector(`.category-btn[data-category="${saved}"]`); 
        if (btn) filterByCategory(saved); 
    }
});

// ===== Event Listeners =====
document.addEventListener('keydown', e => { 
    if (e.key === 'Escape') { 
        closeSidebar(); 
        closeAuthModal(); 
        closeLocationPicker(); 
        closePortionModal(); 
    } 
});

document.getElementById('authModal')?.addEventListener('click', e => { 
    if (e.target === document.getElementById('authModal')) closeAuthModal(); 
});

document.getElementById('locationModal')?.addEventListener('click', e => { 
    if (e.target === document.getElementById('locationModal')) closeLocationPicker(); 
});

document.getElementById('portionModal')?.addEventListener('click', e => { 
    if (e.target === document.getElementById('portionModal')) closePortionModal(); 
});

document.querySelectorAll('.menu-item').forEach(i => i.addEventListener('click', closeSidebar));
</script>
</body>
</html>