<?php
/**
 * checkout.php - صفحة تأكيد الطلب الكاملة
 * نسخة معدلة ومحسنة مع توحيد الجلسات وإصلاح مشكلة Duplicate Email
 */

// بداية الصفحة - سطر واحد فقط
require_once 'config.php';

// التحقق من تسجيل الدخول
if (!isLoggedIn()) {
    $_SESSION['redirect_url'] = 'checkout.php';
    header('Location: home.php?login=required');
    exit;
}

// التحقق من وجود السلة
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart']) || empty($_SESSION['cart'])) {
    header('Location: cart.php');
    exit;
}

// التحقق من وجود المستخدم في قاعدة البيانات
$customer_id = $_SESSION['customer_id'];
$customer_email = $_SESSION['customer_email'] ?? '';

// التحقق من وجود المستخدم في قاعدة البيانات
$check_user = $conn->query("SELECT id FROM customers WHERE id = $customer_id");

if ($check_user->num_rows == 0) {
    // المستخدم غير موجود في قاعدة البيانات
    // نتحقق أولاً مما إذا كان البريد الإلكتروني موجوداً
    
    if (!empty($customer_email)) {
        $check_email = $conn->query("SELECT id FROM customers WHERE email = '$customer_email'");
        
        if ($check_email->num_rows > 0) {
            // البريد الإلكتروني موجود - نستخدم هذا المستخدم ونحدث الجلسة
            $existing_user = $check_email->fetch_assoc();
            $_SESSION['customer_id'] = $existing_user['id'];
            $customer_id = $existing_user['id'];
            
            // تحديث بيانات المستخدم في الجلسة
            $user_data = $conn->query("SELECT name, phone, address, latitude, longitude FROM customers WHERE id = $customer_id")->fetch_assoc();
            $_SESSION['customer_name'] = $user_data['name'];
            $_SESSION['customer_phone'] = $user_data['phone'];
            $_SESSION['customer_address'] = $user_data['address'];
            $_SESSION['customer_lat'] = $user_data['latitude'];
            $_SESSION['customer_lng'] = $user_data['longitude'];
        } else {
            // البريد الإلكتروني غير موجود - ننشئ مستخدم جديد ببريد فريد
            $name = $_SESSION['customer_name'] ?? 'مستخدم';
            $phone = $_SESSION['customer_phone'] ?? '000000000';
            $address = $_SESSION['customer_address'] ?? 'عنوان مؤقت';
            $latitude = $_SESSION['customer_lat'] ?? null;
            $longitude = $_SESSION['customer_lng'] ?? null;
            
            // إنشاء بريد فريد باستخدام الوقت الحالي لتجنب التكرار
            $unique_email = 'user_' . time() . '_' . rand(1000, 9999) . '@temp.max';
            
            $insert = $conn->prepare("
                INSERT INTO customers (id, name, phone, email, address, latitude, longitude, email_verified) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 1)
            ");
            $insert->bind_param("issssdd", $customer_id, $name, $phone, $unique_email, $address, $latitude, $longitude);
            $insert->execute();
            
            // تحديث الجلسة بالبريد الجديد
            $_SESSION['customer_email'] = $unique_email;
        }
    } else {
        // لا يوجد بريد إلكتروني - ننشئ مستخدم بدون بريد
        $name = $_SESSION['customer_name'] ?? 'مستخدم';
        $phone = $_SESSION['customer_phone'] ?? '000000000';
        $address = $_SESSION['customer_address'] ?? 'عنوان مؤقت';
        $latitude = $_SESSION['customer_lat'] ?? null;
        $longitude = $_SESSION['customer_lng'] ?? null;
        
        $insert = $conn->prepare("
            INSERT INTO customers (id, name, phone, address, latitude, longitude, email_verified) 
            VALUES (?, ?, ?, ?, ?, ?, 1)
        ");
        $insert->bind_param("isssdd", $customer_id, $name, $phone, $address, $latitude, $longitude);
        $insert->execute();
    }
}

// التحقق إذا كان الطلب AJAX
$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

// معالجة تحديث الموقع عبر AJAX
if ($is_ajax && isset($_POST['action']) && $_POST['action'] === 'update_location') {
    header('Content-Type: application/json');
    
    $customer_id = $_SESSION['customer_id'];
    $latitude = isset($_POST['latitude']) ? (float)$_POST['latitude'] : null;
    $longitude = isset($_POST['longitude']) ? (float)$_POST['longitude'] : null;
    $address = $conn->real_escape_string($_POST['address'] ?? '');
    
    if (!$latitude || !$longitude) {
        echo json_encode(['success' => false, 'message' => 'الموقع غير صالح']);
        exit;
    }
    
    $stmt = $conn->prepare("UPDATE customers SET latitude = ?, longitude = ?, address = ? WHERE id = ?");
    $stmt->bind_param("ddsi", $latitude, $longitude, $address, $customer_id);
    
    if ($stmt->execute()) {
        // تحديث الجلسة
        $_SESSION['customer_lat'] = $latitude;
        $_SESSION['customer_lng'] = $longitude;
        $_SESSION['customer_address'] = $address;
        
        echo json_encode(['success' => true, 'message' => 'تم تحديث الموقع بنجاح']);
    } else {
        echo json_encode(['success' => false, 'message' => 'حدث خطأ في تحديث الموقع']);
    }
    exit;
}

// معالجة تأكيد الطلب
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_order'])) {
    header('Content-Type: application/json');
    
    $customer_id = $_SESSION['customer_id'];
    $notes = isset($_POST['notes']) ? $conn->real_escape_string($_POST['notes']) : '';
    
    // حساب إجماليات السلة
    $cart_total = 0;
    $cart_items = [];
    
    if (!empty($_SESSION['cart'])) {
        foreach ($_SESSION['cart'] as $item) {
            if (isset($item['meal_id']) && isset($item['quantity'])) {
                $cart_total += ($item['price'] ?? 0) * $item['quantity'];
                $cart_items[] = $item;
            }
        }
    }
    
    $delivery_fee = $settings['delivery_fee'] ?? 10.00;
    $final_total = $cart_total + $delivery_fee;
    
    $conn->begin_transaction();
    
    try {
        // التحقق مرة أخرى من وجود المستخدم
        $check_user = $conn->query("SELECT id FROM customers WHERE id = $customer_id");
        if ($check_user->num_rows == 0) {
            throw new Exception("المستخدم غير موجود في قاعدة البيانات");
        }
        
        // إنشاء الطلب
        $order_sql = "INSERT INTO orders (customer_id, total, notes, status, delivery_fee, subtotal, created_at) 
                      VALUES (?, ?, ?, 'pending', ?, ?, NOW())";
        $stmt = $conn->prepare($order_sql);
        $stmt->bind_param("idsdd", $customer_id, $final_total, $notes, $delivery_fee, $cart_total);
        
        if (!$stmt->execute()) {
            throw new Exception("فشل في إنشاء الطلب: " . $conn->error);
        }
        
        $order_id = $conn->insert_id;
        
        // إضافة عناصر الطلب
        foreach ($cart_items as $item) {
            $item_sql = "INSERT INTO order_items (order_id, meal_id, quantity, price, portion_id, portion_name) 
                         VALUES (?, ?, ?, ?, ?, ?)";
            $item_stmt = $conn->prepare($item_sql);
            
            $meal_id = $item['meal_id'];
            $quantity = $item['quantity'];
            $price = $item['price'];
            $portion_id = $item['portion_id'] ?? null;
            $portion_name = $item['portion_name'] ?? 'كامل';
            
            $item_stmt->bind_param("iiidss", $order_id, $meal_id, $quantity, $price, $portion_id, $portion_name);
            
            if (!$item_stmt->execute()) {
                throw new Exception("فشل في إضافة عناصر الطلب: " . $conn->error);
            }
        }
        
        $conn->commit();
        
        // تفريغ السلة
        $_SESSION['cart'] = [];
        
        echo json_encode([
            'success' => true,
            'order_id' => $order_id,
            'message' => 'تم تأكيد طلبك بنجاح!'
        ]);
        exit;
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Order error: " . $e->getMessage());
        
        echo json_encode([
            'success' => false,
            'message' => 'حدث خطأ في تأكيد الطلب: ' . $e->getMessage()
        ]);
        exit;
    }
}

// حساب إجماليات السلة للعرض
$cart_total = 0;
$cart_items = [];

// جلب بيانات الوجبات
$meal_ids = [];
foreach ($_SESSION['cart'] as $item) {
    if (is_array($item) && isset($item['meal_id']) && isset($item['quantity']) && $item['quantity'] > 0) {
        $meal_ids[] = (int)$item['meal_id'];
    }
}

if (!empty($meal_ids)) {
    $placeholders = str_repeat('?,', count($meal_ids) - 1) . '?';
    
    $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.id IN ($placeholders)
    ");
    
    if ($stmt) {
        $types = str_repeat('i', count($meal_ids));
        $stmt->bind_param($types, ...$meal_ids);
        $stmt->execute();
        $meals_result = $stmt->get_result();
        
        $meals_by_id = [];
        while ($meal = $meals_result->fetch_assoc()) {
            $meals_by_id[$meal['id']] = $meal;
        }
        
        foreach ($_SESSION['cart'] as $index => $cart_item) {
            if (is_array($cart_item) && isset($cart_item['meal_id']) && isset($meals_by_id[$cart_item['meal_id']])) {
                $meal = $meals_by_id[$cart_item['meal_id']];
                $quantity = $cart_item['quantity'];
                $portion_id = $cart_item['portion_id'] ?? null;
                $portion_name = $cart_item['portion_name'] ?? 'كامل';
                $final_price = $cart_item['price'] ?? $meal['price'];
                $subtotal = $final_price * $quantity;
                $cart_total += $subtotal;
                
                $cart_items[] = [
                    'index' => $index,
                    'id' => $meal['id'],
                    'name' => $meal['name'],
                    'quantity' => $quantity,
                    'price' => $final_price,
                    'subtotal' => $subtotal,
                    'portion_id' => $portion_id,
                    'portion_name' => $portion_name
                ];
            }
        }
    }
}

$delivery_fee = $settings['delivery_fee'] ?? 10.00;
$final_total = $cart_total + $delivery_fee;

// جلب بيانات المستخدم مع الموقع المحفوظ
$customer_id = $_SESSION['customer_id'];
$user_query = $conn->prepare("SELECT name, phone, address, latitude, longitude FROM customers WHERE id = ?");
$user_query->bind_param("i", $customer_id);
$user_query->execute();
$user_result = $user_query->get_result();

if ($user_result->num_rows > 0) {
    $user_data = $user_result->fetch_assoc();
    $customer_name = $user_data['name'] ?? $_SESSION['customer_name'] ?? 'زائر';
    $customer_phone = $user_data['phone'] ?? $_SESSION['customer_phone'] ?? '';
    $customer_address = $user_data['address'] ?? $_SESSION['customer_address'] ?? '';
    $customer_lat = $user_data['latitude'] ?? null;
    $customer_lng = $user_data['longitude'] ?? null;
    
    // تحديث الجلسة ببيانات المستخدم من قاعدة البيانات
    $_SESSION['customer_name'] = $customer_name;
    $_SESSION['customer_phone'] = $customer_phone;
    $_SESSION['customer_address'] = $customer_address;
    $_SESSION['customer_lat'] = $customer_lat;
    $_SESSION['customer_lng'] = $customer_lng;
} else {
    // إذا لم يكن المستخدم موجوداً، نستخدم بيانات الجلسة
    $customer_name = $_SESSION['customer_name'] ?? 'زائر';
    $customer_phone = $_SESSION['customer_phone'] ?? '';
    $customer_address = $_SESSION['customer_address'] ?? '';
    $customer_lat = $_SESSION['customer_lat'] ?? null;
    $customer_lng = $_SESSION['customer_lng'] ?? null;
}

// حساب عدد العناصر في السلة
$cart_count = 0;
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
    ");
    $stmt->bind_param('i', $_SESSION['customer_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $unread_tickets = $row['count'] ?? 0;
    $stmt->close();
}

// تسجيل الدخول للصفحة
error_log("Checkout page loaded - User ID: $customer_id, Cart items: " . count($cart_items));
?>
<!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">
    <title>Max - تأكيد الطلب</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">
    <!-- Leaflet for maps -->
    <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;
            --shadow-sm: 0 2px 8px rgba(245, 124, 0, 0.1);
            --shadow-md: 0 4px 16px rgba(245, 124, 0, 0.15);
            --radius-md: 20px;
            --radius-round: 100px;
            --header-height: 60px;
        }

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

        .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;
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .menu-toggle {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .menu-toggle:active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.3);
        }

        .header-center {
            flex: 1;
            text-align: center;
        }

        .restaurant-name {
            color: white;
            font-size: 1.3rem;
            font-weight: 800;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .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;
            text-decoration: none;
            position: relative;
            transition: all 0.2s ease;
        }

        .icon-btn:active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.3);
        }

        .badge {
            position: absolute;
            top: -5px;
            left: -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-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;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .sidebar-close:active {
            transform: scale(0.9);
            background: rgba(255, 255, 255, 0.3);
        }

        .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;
            color: white;
        }

        .sidebar-email {
            font-size: 0.85rem;
            opacity: 0.9;
            color: white;
        }

        .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);
            transition: background 0.2s ease;
        }

        .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;
        }

        .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;
        }

        .page-container {
            padding: 15px;
            max-width: 500px;
            margin: 0 auto;
        }

        .page-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .page-title {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--primary);
            margin-bottom: 5px;
        }

        .page-subtitle {
            color: var(--gray);
            font-size: 0.95rem;
        }

        .card {
            background: white;
            border-radius: var(--radius-md);
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--primary-light);
        }

        .card-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .info-row {
            display: flex;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid var(--gray-light);
        }

        .info-row:last-child {
            border-bottom: none;
        }

        .info-label {
            width: 80px;
            color: var(--gray);
            font-size: 0.9rem;
        }

        .info-value {
            flex: 1;
            font-weight: 600;
        }

        .order-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid var(--gray-light);
        }

        .order-item:last-child {
            border-bottom: none;
        }

        .item-name {
            font-weight: 600;
        }

        .item-quantity {
            color: var(--gray);
            font-size: 0.9rem;
            margin-right: 5px;
        }

        .portion-badge {
            background: var(--primary-soft);
            color: var(--primary);
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 11px;
            margin-right: 5px;
        }

        .item-price {
            font-weight: 700;
            color: var(--dark);
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid var(--gray-light);
        }

        .summary-row:last-of-type {
            border-bottom: none;
            font-weight: 800;
            font-size: 1.2rem;
            color: var(--primary);
        }

        .location-box {
            background: var(--primary-soft);
            border-radius: 15px;
            padding: 15px;
            margin: 10px 0;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .location-icon {
            width: 40px;
            height: 40px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary);
        }

        .location-content {
            flex: 1;
        }

        .location-address {
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 3px;
        }

        .location-coords {
            font-size: 0.75rem;
            color: var(--gray);
            direction: ltr;
            text-align: left;
        }

        .change-location-btn {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
            padding: 8px 15px;
            border-radius: var(--radius-round);
            font-weight: 600;
            font-size: 0.9rem;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .change-location-btn:active {
            background: var(--primary-soft);
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid var(--primary-light);
            border-radius: 15px;
            font-family: 'Tajawal', sans-serif;
            font-size: 15px;
            resize: none;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
        }

        .order-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            font-size: 18px;
            font-weight: 700;
            padding: 16px;
            border: none;
            border-radius: var(--radius-round);
            width: 100%;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            box-shadow: var(--shadow-md);
            transition: all 0.2s ease;
        }

        .order-btn:active {
            transform: scale(0.98);
        }

        .order-btn.loading {
            opacity: 0.7;
            pointer-events: none;
        }

        .order-btn.loading i {
            animation: spin 1s linear infinite;
        }

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

        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
            padding: 10px 20px;
            border-radius: var(--radius-round);
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            cursor: pointer;
        }

        .btn-outline:active {
            background: var(--primary-soft);
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 14px;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            padding: 14px;
            border-radius: var(--radius-round);
            font-weight: 700;
            cursor: pointer;
        }

        .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: 90%;
            max-width: 350px;
            padding: 25px;
            text-align: center;
            animation: modalPop 0.3s ease;
        }

        @keyframes modalPop {
            from {
                transform: scale(0.8);
                opacity: 0;
            }
            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .modal-icon {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: rgba(245,124,0,0.1);
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 2.5rem;
        }

        .modal-icon.success {
            background: rgba(76,175,80,0.1);
            color: var(--success);
        }

        .modal-title {
            font-size: 1.3rem;
            font-weight: 800;
            margin-bottom: 10px;
        }

        .modal-text {
            color: var(--gray);
            margin-bottom: 20px;
        }

        .modal-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .modal-btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: var(--radius-round);
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            text-align: center;
            transition: all 0.2s ease;
        }

        .modal-btn.cancel {
            background: var(--gray-light);
            color: var(--dark);
        }

        .modal-btn.confirm {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.9);
            z-index: 5000;
            display: none;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            gap: 15px;
        }

        .loading-overlay.active {
            display: flex;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid var(--primary-light);
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .loading-text {
            color: var(--primary);
            font-weight: 600;
            font-size: 1.1rem;
        }

        .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;
        }

        .toast-message.success { border-right-color: var(--success); }
        .toast-message.error { border-right-color: var(--danger); }

        .toast-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toast-icon.success {
            background: rgba(76,175,80,0.1);
            color: var(--success);
        }

        .toast-icon.error {
            background: rgba(244,67,54,0.1);
            color: var(--danger);
        }

        #map {
            height: 300px;
            width: 100%;
            border-radius: 15px;
            margin-bottom: 15px;
            z-index: 1;
        }

        .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;
        }
    </style>
</head>
<body>
    <!-- الهيدر الموحد -->
    <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> Max
                </span>
            </div>
            <div class="header-right">
                <a href="support.php" class="icon-btn" title="الإشعارات">
                    <i class="bi bi-bell"></i>
                    <?php if($unread_tickets > 0): ?>
                    <span class="badge"><?= $unread_tickets ?></span>
                    <?php endif; ?>
                </a>
            </div>
        </div>
    </header>

    <!-- القائمة الجانبية الموحدة -->
    <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"><?= htmlspecialchars($customer_name) ?></div>
                <div class="sidebar-email"><?= htmlspecialchars($customer_email ?? '') ?></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>
                <?php if($cart_count > 0): ?>
                <span class="menu-badge"><?= $cart_count ?></span>
                <?php endif; ?>
            </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>
            <a href="about.php#developer" class="menu-item">
                <i class="bi bi-code-square"></i>
                <span>عن المطور</span>
            </a>
            <?php if (isLoggedIn()): ?>
            <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>Max App v3.0</small>
        </div>
    </div>

    <!-- مودال تأكيد الطلب -->
    <div class="modal-overlay" id="confirmModal">
        <div class="modal-content">
            <div class="modal-icon">
                <i class="bi bi-question-lg"></i>
            </div>
            <h3 class="modal-title">تأكيد الطلب</h3>
            <p class="modal-text">هل أنت متأكد من تأكيد هذا الطلب؟</p>
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closeConfirmModal()">إلغاء</button>
                <button class="modal-btn confirm" id="finalConfirmBtn">تأكيد</button>
            </div>
        </div>
    </div>

    <!-- مودال النجاح -->
    <div class="modal-overlay" id="successModal">
        <div class="modal-content">
            <div class="modal-icon success">
                <i class="bi bi-check-lg"></i>
            </div>
            <h3 class="modal-title">تم بنجاح!</h3>
            <p class="modal-text" id="successMessage">تم تأكيد طلبك بنجاح</p>
            <div class="modal-buttons">
                <a href="orders.php" class="modal-btn confirm">عرض الطلبات</a>
                <a href="home.php" class="modal-btn cancel">الرئيسية</a>
            </div>
        </div>
    </div>

    <!-- شاشة التحميل -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">جاري تأكيد الطلب...</div>
    </div>

    <!-- مودال اختيار الموقع -->
    <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()" style="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; display: flex; align-items: center; justify-content: center; cursor: pointer;">
                    <i class="bi bi-x"></i>
                </button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <div id="map" style="height: 300px; width: 100%; border-radius: 15px; margin-bottom: 15px;"></div>
                <div class="selected-location">
                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                        <i class="bi bi-geo-alt-fill" style="color: var(--primary);"></i>
                        <span style="font-weight: 600;">العنوان:</span>
                    </div>
                    <p id="selectedAddress" style="color: var(--dark); margin-bottom: 8px;"></p>
                    <div class="location-coords" id="selectedCoords"></div>
                </div>
                <div class="modal-buttons" style="display: flex; gap: 10px;">
                    <button class="btn-outline" onclick="closeLocationPicker()" style="flex:1;">إلغاء</button>
                    <button class="btn-primary" onclick="confirmLocation()" style="flex:1;">تأكيد الموقع</button>
                </div>
            </div>
        </div>
    </div>

    <!-- حاوية الرسائل -->
    <div class="toast-container" id="toastContainer"></div>

    <!-- المحتوى الرئيسي -->
    <div class="page-container">
        <div class="page-header">
            <h1 class="page-title">تأكيد الطلب</h1>
            <p class="page-subtitle">الخطوة الأخيرة لإتمام طلبك</p>
        </div>

        <form id="checkoutForm">
            <!-- معلومات العميل -->
            <div class="card">
                <h5 class="card-title"><i class="bi bi-person"></i> معلومات العميل</h5>
                <div class="info-row">
                    <span class="info-label">الاسم:</span>
                    <span class="info-value"><?= htmlspecialchars($customer_name) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">الهاتف:</span>
                    <span class="info-value"><?= htmlspecialchars($customer_phone) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">العنوان:</span>
                    <span class="info-value"><?= htmlspecialchars($customer_address) ?></span>
                </div>
            </div>

            <!-- موقع التوصيل -->
            <div class="card">
                <h5 class="card-title"><i class="bi bi-geo-alt"></i> موقع التوصيل</h5>
                
                <div class="location-box" id="deliveryLocationBox">
                    <div class="location-icon">
                        <i class="bi bi-geo-alt-fill"></i>
                    </div>
                    <div class="location-content">
                        <div class="location-address" id="deliveryAddress">
                            <?= htmlspecialchars($customer_address) ?>
                        </div>
                        <?php if ($customer_lat && $customer_lng): ?>
                        <div class="location-coords" id="deliveryCoords">
                            <?= number_format($customer_lat, 6) ?>, <?= number_format($customer_lng, 6) ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <button type="button" class="change-location-btn" onclick="changeDeliveryLocation()" style="margin-top: 10px; width: 100%;">
                    <i class="bi bi-pencil"></i> تغيير موقع التوصيل
                </button>
                
                <!-- حقول مخفية للموقع -->
                <input type="hidden" id="deliveryLat" name="latitude" value="<?= $customer_lat ?>">
                <input type="hidden" id="deliveryLng" name="longitude" value="<?= $customer_lng ?>">
            </div>

            <!-- ملخص الطلب -->
            <div class="card">
                <h5 class="card-title"><i class="bi bi-list-check"></i> ملخص الطلب</h5>
                
                <div id="orderItems">
                    <?php foreach ($cart_items as $item): ?>
                    <div class="order-item">
                        <div>
                            <span class="item-name"><?= htmlspecialchars($item['name']) ?></span>
                            <span class="item-quantity">× <?= $item['quantity'] ?></span>
                            <?php if (!empty($item['portion_name']) && $item['portion_name'] != 'كامل'): ?>
                            <span class="portion-badge"><?= htmlspecialchars($item['portion_name']) ?></span>
                            <?php endif; ?>
                        </div>
                        <span class="item-price"><?= number_format($item['subtotal'], 2) ?> ر.ي</span>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <hr style="margin: 15px 0; border: 1px solid var(--gray-light);">
                
                <div class="summary-row">
                    <span>مجموع السلع:</span>
                    <span id="cartTotal"><?= number_format($cart_total, 2) ?> ر.ي</span>
                </div>
                
                <div class="summary-row">
                    <span>رسوم التوصيل:</span>
                    <span id="deliveryFee"><?= number_format($delivery_fee, 2) ?> ر.ي</span>
                </div>
                
                <div class="summary-row">
                    <strong>الإجمالي الكلي:</strong>
                    <strong id="finalTotal"><?= number_format($final_total, 2) ?> ر.ي</strong>
                </div>
            </div>

            <!-- ملاحظات -->
            <div class="card">
                <h5 class="card-title"><i class="bi bi-chat-left-text"></i> ملاحظات</h5>
                <textarea class="form-control" id="notes" name="notes" rows="3" 
                          placeholder="أي ملاحظات إضافية (اختياري)"></textarea>
            </div>

            <!-- زر التأكيد -->
            <button type="button" class="order-btn" id="confirmBtn">
                <i class="bi bi-bag-check"></i> تأكيد الطلب
                <small id="btnTotal"><?= number_format($final_total, 2) ?> ريال</small>
            </button>
        </form>
    </div>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    // ===== المتغيرات العامة =====
    let map;
    let marker;
    let mapInitialized = false;
    let currentLat = <?= $customer_lat ?: 14.5667 ?>;
    let currentLng = <?= $customer_lng ?: 44.4000 ?>;
    let selectedLat = currentLat;
    let selectedLng = currentLng;
    let selectedAddress = '<?= addslashes($customer_address) ?>';

    // ===== دوال القائمة الجانبية =====
    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 = '';
    }

    // ===== دوال الموقع =====
    function changeDeliveryLocation() {
        openLocationPicker('checkout');
    }

    function openLocationPicker(source = 'checkout') {
        document.getElementById('locationModal').classList.add('active');
        document.body.style.overflow = 'hidden';
        
        setTimeout(() => {
            if (!mapInitialized) {
                initMap();
            } else {
                map.invalidateSize();
                marker.setLatLng([currentLat, currentLng]);
            }
        }, 200);
    }

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

    function initMap() {
        map = L.map('map').setView([currentLat, currentLng], 13);
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        marker = L.marker([currentLat, currentLng], { draggable: true }).addTo(map);
        
        marker.on('dragend', function(e) {
            const latlng = e.target.getLatLng();
            updateLocationFromCoords(latlng.lat, latlng.lng);
        });
        
        map.on('click', function(e) {
            marker.setLatLng(e.latlng);
            updateLocationFromCoords(e.latlng.lat, e.latlng.lng);
        });
        
        updateLocationFromCoords(currentLat, currentLng);
        mapInitialized = true;
    }

    function updateLocationFromCoords(lat, lng) {
        selectedLat = lat;
        selectedLng = lng;
        
        document.getElementById('selectedCoords').textContent = 
            `الإحداثيات: ${lat.toFixed(6)}, ${lng.toFixed(6)}`;
        
        fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=ar`)
            .then(response => response.json())
            .then(data => {
                const address = data.display_name || 'ذمار - شارع رداع - مطعم ماكس';
                document.getElementById('selectedAddress').textContent = address;
                selectedAddress = address;
            })
            .catch(() => {
                document.getElementById('selectedAddress').textContent = 'ذمار - شارع رداع - مطعم ماكس';
                selectedAddress = 'ذمار - شارع رداع - مطعم ماكس';
            });
    }

    function confirmLocation() {
        if (!selectedAddress || !selectedLat || !selectedLng) {
            showToast('الرجاء اختيار موقع', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('action', 'update_location');
        formData.append('latitude', selectedLat);
        formData.append('longitude', selectedLng);
        formData.append('address', selectedAddress);
        
        fetch('checkout.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('deliveryAddress').textContent = selectedAddress;
                document.getElementById('deliveryCoords').textContent = 
                    selectedLat.toFixed(6) + ', ' + selectedLng.toFixed(6);
                document.getElementById('deliveryLat').value = selectedLat;
                document.getElementById('deliveryLng').value = selectedLng;
                
                currentLat = selectedLat;
                currentLng = selectedLng;
                
                closeLocationPicker();
                showToast('تم تحديث موقع التوصيل', 'success');
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('حدث خطأ في تحديث الموقع', 'error');
        });
    }

    // ===== دوال المودالات =====
    function openConfirmModal() {
        document.getElementById('confirmModal').classList.add('active');
    }

    function closeConfirmModal() {
        document.getElementById('confirmModal').classList.remove('active');
    }

    function openSuccessModal() {
        document.getElementById('successModal').classList.add('active');
    }

    // ===== تأكيد الطلب =====
    document.getElementById('confirmBtn').addEventListener('click', function() {
        openConfirmModal();
    });

    document.getElementById('finalConfirmBtn').addEventListener('click', function() {
        closeConfirmModal();
        document.getElementById('loadingOverlay').classList.add('active');
        
        const formData = new FormData(document.getElementById('checkoutForm'));
        formData.append('submit_order', '1');
        
        fetch('checkout.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('loadingOverlay').classList.remove('active');
            
            if (data.success) {
                document.getElementById('successMessage').textContent = data.message;
                openSuccessModal();
            } else {
                showToast(data.message || 'حدث خطأ', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('loadingOverlay').classList.remove('active');
            showToast('حدث خطأ في الاتصال', 'error');
        });
    });

    // ===== دوال الرسائل =====
    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        
        const toast = document.createElement('div');
        toast.className = `toast-message ${type}`;
        
        let icon = type === 'success' ? 'check-lg' : 'exclamation-lg';
        
        toast.innerHTML = `
            <div class="toast-icon ${type}"><i class="bi bi-${icon}"></i></div>
            <div class="toast-content">${message}</div>
        `;
        
        container.appendChild(toast);
        
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
                if (toast.parentNode) toast.remove();
            }, 300);
        }, 3000);
    }

    // ===== أحداث الإغلاق =====
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeSidebar();
            closeLocationPicker();
            closeConfirmModal();
        }
    });

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

    document.getElementById('confirmModal').addEventListener('click', function(e) {
        if (e.target === this) closeConfirmModal();
    });

    document.getElementById('successModal').addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
            window.location.href = 'home.php';
        }
    });

    // ===== تهيئة الصفحة =====
    document.addEventListener('DOMContentLoaded', function() {
        window.updateDeliveryAddress = function(address) {
            document.getElementById('deliveryAddress').textContent = address;
        };
    });
    </script>
</body>
</html>