<?php
/**
 * profile.php - صفحة الملف الشخصي الكاملة
 * نسخة معدلة ومحسنة مع توحيد الجلسات وإصلاح جميع المشاكل
 */

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

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

// ============================================
// هنا يبدأ الكود الأصلي لملف profile.php
// (المستخدمين المسجلين فقط هم من يصلون إلى هنا)
// ============================================

$customer_id = $_SESSION['customer_id'];
$message = '';
$message_type = '';

// جلب معلومات العميل
$customer = $conn->query("SELECT * FROM customers WHERE id='$customer_id'")->fetch_assoc();

// التحقق من وجود طلبات نشطة تمنع حذف الحساب
$active_orders_query = $conn->query("
    SELECT COUNT(*) as count 
    FROM orders 
    WHERE customer_id = '$customer_id' 
    AND status IN ('pending', 'accepted', 'preparing', 'ready', 'on_the_way')
");
$active_orders = $active_orders_query->fetch_assoc()['count'];

// معالجة تحديث الملف الشخصي
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // معالجة حذف الحساب - يجب أن تكون الأولى في المعالجة
    if (isset($_POST['delete_account'])) {
        // تعيين header JSON
        header('Content-Type: application/json');
        
        $phone_verify = $_POST['delete_phone'] ?? '';
        $password_verify = $_POST['delete_password'] ?? '';
        
        // التحقق من وجود طلبات نشطة
        if ($active_orders > 0) {
            echo json_encode([
                'success' => false,
                'message' => 'لا يمكن حذف الحساب لوجود طلبات نشطة'
            ]);
            exit();
        }
        
        // التحقق من رقم الهاتف
        if ($phone_verify !== $customer['phone']) {
            echo json_encode([
                'success' => false,
                'message' => 'رقم الهاتف غير صحيح'
            ]);
            exit();
        }
        
        // التحقق من كلمة المرور
        if (!password_verify($password_verify, $customer['password'])) {
            echo json_encode([
                'success' => false,
                'message' => 'كلمة المرور غير صحيحة'
            ]);
            exit();
        }
        
        // بدء معاملة قاعدة البيانات
        $conn->begin_transaction();
        
        try {
            // حذف رسائل التذاكر أولاً
            $conn->query("
                DELETE tm FROM ticket_messages tm
                INNER JOIN customer_tickets ct ON tm.ticket_id = ct.id
                WHERE ct.customer_id = '$customer_id'
            ");
            
            // حذف التذاكر
            $conn->query("DELETE FROM customer_tickets WHERE customer_id = '$customer_id'");
            
            // حذف عناصر الطلبات
            $conn->query("
                DELETE oi FROM order_items oi
                INNER JOIN orders o ON oi.order_id = o.id
                WHERE o.customer_id = '$customer_id'
            ");
            
            // حذف الطلبات
            $conn->query("DELETE FROM orders WHERE customer_id = '$customer_id'");
            
            // حذف العميل
            $conn->query("DELETE FROM customers WHERE id = '$customer_id'");
            
            $conn->commit();
            
            // تدمير الجلسة
            session_destroy();
            
            echo json_encode([
                'success' => true,
                'message' => 'تم حذف الحساب بنجاح'
            ]);
            exit();
            
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode([
                'success' => false,
                'message' => 'حدث خطأ أثناء حذف الحساب'
            ]);
            exit();
        }
    }
    
    if (isset($_POST['update_profile'])) {
        $name = $conn->real_escape_string($_POST['name']);
        $phone = $conn->real_escape_string($_POST['phone']);
        $address = $conn->real_escape_string($_POST['address']);
        
        // التحقق إذا كان الهاتف مسجلاً لعميل آخر
        $check_sql = "SELECT id FROM customers WHERE phone = '$phone' AND id != '$customer_id'";
        $check_result = $conn->query($check_sql);
        
        if ($check_result->num_rows > 0) {
            $message = "رقم الهاتف مسجل مسبقاً";
            $message_type = "danger";
        } else {
            $sql = "UPDATE customers SET name='$name', phone='$phone', address='$address' WHERE id='$customer_id'";
            
            if ($conn->query($sql) === TRUE) {
                $_SESSION['customer_name'] = $name;
                $_SESSION['customer_phone'] = $phone;
                $_SESSION['customer_address'] = $address;
                $_SESSION['success_message'] = "✅ تم تحديث الملف الشخصي بنجاح";
                
                header('Location: profile.php?success=1');
                exit();
            } else {
                $message = "خطأ في تحديث الملف الشخصي: " . $conn->error;
                $message_type = "danger";
            }
        }
    }
    
    if (isset($_POST['change_password'])) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        if (password_verify($current_password, $customer['password'])) {
            if ($new_password === $confirm_password) {
                if (strlen($new_password) >= 6) {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $sql = "UPDATE customers SET password='$hashed_password' WHERE id='$customer_id'";
                    
                    if ($conn->query($sql) === TRUE) {
                        $_SESSION['success_message'] = "✅ تم تغيير كلمة المرور بنجاح";
                        header('Location: profile.php?success=2');
                        exit();
                    } else {
                        $message = "خطأ في تغيير كلمة المرور: " . $conn->error;
                        $message_type = "danger";
                    }
                } else {
                    $message = "كلمة المرور يجب أن تكون 6 أحرف على الأقل";
                    $message_type = "danger";
                }
            } else {
                $message = "كلمات المرور غير متطابقة";
                $message_type = "danger";
            }
        } else {
            $message = "كلمة المرور الحالية غير صحيحة";
            $message_type = "danger";
        }
    }
}

// جلب إحصائيات العميل
$stats = $conn->query("
    SELECT 
        COUNT(*) as total_orders,
        COALESCE(SUM(total), 0) as total_spent,
        COUNT(CASE WHEN status = 'delivered' THEN 1 END) as completed_orders
    FROM orders 
    WHERE customer_id = '$customer_id'
")->fetch_assoc();

// جلب آخر طلب
$last_order = $conn->query("
    SELECT created_at, total 
    FROM orders 
    WHERE customer_id = '$customer_id' 
    ORDER BY created_at DESC 
    LIMIT 1
")->fetch_assoc();

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

// رسائل النجاح من الجلسة
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);
$success_type = isset($_GET['success']) ? $_GET['success'] : '';

// تحديث بيانات المستخدم في الجلسة
$_SESSION['customer_name'] = $customer['name'];
$_SESSION['customer_phone'] = $customer['phone'];
$_SESSION['customer_address'] = $customer['address'];
?>
<!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">
    <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">
    <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;
            --warning: #FF9800;
            --info: #29B6F6;
            --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-sm: 12px;
            --radius-md: 20px;
            --radius-lg: 28px;
            --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;
        }

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

        .profile-avatar {
            width: 90px;
            height: 90px;
            background: linear-gradient(135deg, var(--primary-light), var(--primary-soft));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            color: var(--primary);
            margin: 0 auto 10px;
            border: 3px solid white;
            box-shadow: var(--shadow-md);
        }

        .profile-name {
            font-size: 1.3rem;
            font-weight: 800;
            color: var(--dark);
        }

        .profile-phone {
            color: var(--gray);
            font-size: 0.9rem;
            margin-top: 3px;
            direction: ltr;
            text-align: center;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            border-radius: var(--radius-md);
            padding: 15px 5px;
            text-align: center;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--primary-light);
        }

        .stat-number {
            font-size: 1.4rem;
            font-weight: 800;
            color: var(--primary);
            line-height: 1.2;
        }

        .stat-label {
            font-size: 11px;
            color: var(--gray);
            font-weight: 500;
        }

        .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;
            border-bottom: 2px solid var(--primary-soft);
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: var(--dark);
            font-size: 0.9rem;
        }

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

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(245, 124, 0, 0.1);
        }

        .btn {
            padding: 12px 24px;
            border-radius: var(--radius-round);
            border: none;
            font-family: 'Tajawal', sans-serif;
            font-weight: 700;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            width: 100%;
            box-shadow: var(--shadow-sm);
        }

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

        .btn-secondary {
            background: linear-gradient(135deg, var(--info), #0288D1);
            color: white;
            width: 100%;
            margin-top: 10px;
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #C62828);
            color: white;
            width: 100%;
            padding: 16px;
            font-size: 16px;
            margin-top: 20px;
        }

        .btn-outline-danger {
            background: transparent;
            border: 2px solid var(--danger);
            color: var(--danger);
            width: 100%;
            padding: 14px;
            font-size: 16px;
            margin-top: 15px;
        }

        .btn-outline-danger:active {
            background: rgba(244, 67, 54, 0.1);
        }

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

        .toggle-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .toggle-btn {
            flex: 1;
            padding: 12px;
            background: white;
            border: 2px solid var(--primary-light);
            border-radius: var(--radius-round);
            color: var(--primary);
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .toggle-btn.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-color: transparent;
        }

        .toggle-btn:active {
            transform: scale(0.95);
        }

        .section-hidden {
            display: none;
        }

        .alert {
            padding: 15px;
            border-radius: 15px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-right: 5px solid transparent;
        }

        .alert-success {
            background: rgba(76, 175, 80, 0.1);
            border-right-color: var(--success);
            color: var(--success);
        }

        .alert-danger {
            background: rgba(244, 67, 54, 0.1);
            border-right-color: var(--danger);
            color: var(--danger);
        }

        .alert-warning {
            background: rgba(255, 152, 0, 0.1);
            border-right-color: var(--warning);
            color: var(--warning);
        }

        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 3000;
        }

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

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

        @keyframes slideDown {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        /* ===== مودال حذف الحساب ===== */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 4000;
            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: 380px;
            padding: 25px;
            animation: modalPop 0.3s ease;
        }

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

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

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

        .modal-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: var(--danger);
            margin-bottom: 5px;
        }

        .modal-subtitle {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .warning-box {
            background: rgba(244, 67, 54, 0.05);
            border: 1px solid rgba(244, 67, 54, 0.2);
            border-radius: 15px;
            padding: 15px;
            margin: 20px 0;
        }

        .warning-item {
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--danger);
            font-size: 0.9rem;
            margin-bottom: 8px;
        }

        .warning-item:last-child {
            margin-bottom: 0;
        }

        .warning-item i {
            font-size: 1rem;
        }

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

        .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.cancel {
            background: var(--gray-light);
            color: var(--dark);
        }

        .modal-btn.delete {
            background: var(--danger);
            color: white;
        }

        .modal-btn:active {
            transform: scale(0.95);
        }

        .modal-btn:disabled {
            opacity: 0.5;
            pointer-events: none;
        }

        .delete-status {
            text-align: center;
            margin: 15px 0;
            padding: 10px;
            border-radius: 10px;
            font-weight: 600;
        }

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

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

        .delete-loading {
            display: none;
            text-align: center;
            margin: 15px 0;
        }

        .delete-loading.active {
            display: block;
        }

        .delete-loading .spinner {
            width: 40px;
            height: 40px;
            border: 3px solid var(--primary-light);
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </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['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>
                <?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 active">
                <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 (isset($_SESSION['customer_id'])): ?>
            <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="deleteModal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-icon">
                    <i class="bi bi-exclamation-triangle"></i>
                </div>
                <h3 class="modal-title">حذف الحساب</h3>
                <p class="modal-subtitle">هذا الإجراء لا يمكن التراجع عنه</p>
            </div>
            
            <?php if ($active_orders > 0): ?>
            <div class="warning-box">
                <div class="warning-item">
                    <i class="bi bi-exclamation-circle-fill"></i>
                    <span>لا يمكن حذف الحساب لوجود طلبات نشطة</span>
                </div>
                <div class="warning-item">
                    <i class="bi bi-truck"></i>
                    <span>لديك <?= $active_orders ?> طلب/طلبات قيد التنفيذ</span>
                </div>
            </div>
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closeDeleteModal()">فهمت</button>
            </div>
            <?php else: ?>
            <div class="warning-box">
                <div class="warning-item">
                    <i class="bi bi-exclamation-circle-fill"></i>
                    <span>سيتم حذف جميع بياناتك بشكل نهائي</span>
                </div>
                <div class="warning-item">
                    <i class="bi bi-clock-history"></i>
                    <span>لا يمكن استعادة الحساب بعد الحذف</span>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">رقم الهاتف للتأكيد</label>
                <input type="tel" class="form-control" id="deletePhone" placeholder="أدخل رقم هاتفك">
            </div>
            
            <div class="form-group">
                <label class="form-label">كلمة المرور للتأكيد</label>
                <input type="password" class="form-control" id="deletePassword" placeholder="أدخل كلمة المرور">
            </div>
            
            <div id="deleteStatus" class="delete-status"></div>
            
            <div class="delete-loading" id="deleteLoading">
                <div class="spinner"></div>
                <div>جاري حذف الحساب...</div>
            </div>
            
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closeDeleteModal()">إلغاء</button>
                <button class="modal-btn delete" onclick="confirmDelete()" id="confirmDeleteBtn">حذف الحساب</button>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- حاوية الرسائل -->
    <div class="toast-container" id="toastContainer">
        <?php if (!empty($success_message)): ?>
        <div class="toast-message success">
            <div class="toast-icon"><i class="bi bi-check-lg"></i></div>
            <div class="toast-content"><?= htmlspecialchars($success_message) ?></div>
        </div>
        <?php elseif ($success_type == 1): ?>
        <div class="toast-message success">
            <div class="toast-icon"><i class="bi bi-check-lg"></i></div>
            <div class="toast-content">✅ تم تحديث الملف الشخصي بنجاح</div>
        </div>
        <?php elseif ($success_type == 2): ?>
        <div class="toast-message success">
            <div class="toast-icon"><i class="bi bi-check-lg"></i></div>
            <div class="toast-content">✅ تم تغيير كلمة المرور بنجاح</div>
        </div>
        <?php endif; ?>
    </div>

    <div class="page-container">
        <?php if ($message): ?>
            <div class="alert alert-<?= $message_type ?>">
                <i class="bi <?= $message_type == 'success' ? 'bi-check-circle-fill' : 'bi-exclamation-triangle-fill' ?>"></i>
                <span><?= $message ?></span>
            </div>
        <?php endif; ?>

        <!-- صورة الملف الشخصي -->
        <div class="profile-header">
            <div class="profile-avatar">
                <i class="bi bi-person-circle"></i>
            </div>
            <h2 class="profile-name"><?= htmlspecialchars($customer['name']) ?></h2>
            <div class="profile-phone"><?= htmlspecialchars($customer['phone']) ?></div>
        </div>

        <!-- الإحصائيات -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?= $stats['total_orders'] ?></div>
                <div class="stat-label">إجمالي الطلبات</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?= $stats['completed_orders'] ?></div>
                <div class="stat-label">مكتملة</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?= number_format($stats['total_spent'], 0) ?></div>
                <div class="stat-label">ريال مصروف</div>
            </div>
        </div>

        <!-- أزرار التبديل -->
        <div class="toggle-buttons">
            <button class="toggle-btn active" id="showInfoBtn" onclick="showSection('info')">
                <i class="bi bi-person"></i> المعلومات
            </button>
            <button class="toggle-btn" id="showPasswordBtn" onclick="showSection('password')">
                <i class="bi bi-key"></i> كلمة المرور
            </button>
        </div>

        <!-- قسم المعلومات الشخصية -->
        <div class="card" id="infoSection">
            <h5 class="card-title">
                <i class="bi bi-pencil-square"></i> تعديل المعلومات
            </h5>
            <form method="POST">
                <div class="form-group">
                    <label class="form-label">الاسم الكامل</label>
                    <input type="text" class="form-control" name="name" value="<?= htmlspecialchars($customer['name']) ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">رقم الهاتف</label>
                    <input type="tel" class="form-control" name="phone" value="<?= htmlspecialchars($customer['phone']) ?>" required placeholder="05xxxxxxxx">
                </div>
                <div class="form-group">
                    <label class="form-label">العنوان</label>
                    <textarea class="form-control" name="address" rows="2" required><?= htmlspecialchars($customer['address']) ?></textarea>
                </div>
                <button type="submit" name="update_profile" class="btn btn-primary">
                    <i class="bi bi-check-lg"></i> حفظ التغييرات
                </button>
            </form>
        </div>

        <!-- قسم تغيير كلمة المرور (مخفي افتراضياً) -->
        <div class="card section-hidden" id="passwordSection">
            <h5 class="card-title">
                <i class="bi bi-shield-lock"></i> تغيير كلمة المرور
            </h5>
            <form method="POST">
                <div class="form-group">
                    <label class="form-label">كلمة المرور الحالية</label>
                    <input type="password" class="form-control" name="current_password" required>
                </div>
                <div class="form-group">
                    <label class="form-label">كلمة المرور الجديدة</label>
                    <input type="password" class="form-control" name="new_password" required minlength="6">
                </div>
                <div class="form-group">
                    <label class="form-label">تأكيد كلمة المرور الجديدة</label>
                    <input type="password" class="form-control" name="confirm_password" required minlength="6">
                </div>
                <button type="submit" name="change_password" class="btn btn-secondary">
                    <i class="bi bi-key"></i> تغيير كلمة المرور
                </button>
            </form>
        </div>

        <!-- زر حذف الحساب -->
        <button class="btn btn-outline-danger" onclick="openDeleteModal()">
            <i class="bi bi-trash3"></i> حذف الحساب
        </button>
    </div>

    <script>
    // ===== القائمة الجانبية =====
    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 showSection(section) {
        const infoSection = document.getElementById('infoSection');
        const passwordSection = document.getElementById('passwordSection');
        const infoBtn = document.getElementById('showInfoBtn');
        const passwordBtn = document.getElementById('showPasswordBtn');
        
        if (section === 'info') {
            infoSection.classList.remove('section-hidden');
            passwordSection.classList.add('section-hidden');
            infoBtn.classList.add('active');
            passwordBtn.classList.remove('active');
        } else {
            infoSection.classList.add('section-hidden');
            passwordSection.classList.remove('section-hidden');
            infoBtn.classList.remove('active');
            passwordBtn.classList.add('active');
        }
    }

    // ===== مودال حذف الحساب =====
    const deleteModal = document.getElementById('deleteModal');
    const deletePhone = document.getElementById('deletePhone');
    const deletePassword = document.getElementById('deletePassword');
    const deleteStatus = document.getElementById('deleteStatus');
    const deleteLoading = document.getElementById('deleteLoading');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

    function openDeleteModal() {
        deleteModal.classList.add('active');
        document.body.style.overflow = 'hidden';
        
        if (deletePhone) deletePhone.value = '';
        if (deletePassword) deletePassword.value = '';
        if (deleteStatus) {
            deleteStatus.innerHTML = '';
            deleteStatus.className = 'delete-status';
        }
        if (deleteLoading) deleteLoading.classList.remove('active');
        if (confirmDeleteBtn) confirmDeleteBtn.disabled = false;
    }

    function closeDeleteModal() {
        deleteModal.classList.remove('active');
        document.body.style.overflow = '';
    }

    // ===== تأكيد حذف الحساب =====
    async function confirmDelete() {
        if (!deletePhone || !deletePassword) {
            showDeleteStatus('الرجاء إدخال رقم الهاتف وكلمة المرور', 'error');
            return;
        }
        
        const phone = deletePhone.value.trim();
        const password = deletePassword.value;
        
        if (!phone || !password) {
            showDeleteStatus('الرجاء إدخال رقم الهاتف وكلمة المرور', 'error');
            return;
        }
        
        confirmDeleteBtn.disabled = true;
        deleteLoading.classList.add('active');
        deleteStatus.innerHTML = '';
        deleteStatus.className = 'delete-status';
        
        const formData = new FormData();
        formData.append('delete_account', '1');
        formData.append('delete_phone', phone);
        formData.append('delete_password', password);
        
        fetch(window.location.href, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showDeleteStatus(data.message, 'success');
                setTimeout(() => {
                    window.location.href = 'home.php';
                }, 2000);
            } else {
                showDeleteStatus(data.message, 'error');
                confirmDeleteBtn.disabled = false;
                deleteLoading.classList.remove('active');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showDeleteStatus('حدث خطأ في حذف الحساب', 'error');
            confirmDeleteBtn.disabled = false;
            deleteLoading.classList.remove('active');
        });
    }

    function showDeleteStatus(message, type) {
        if (deleteStatus) {
            deleteStatus.innerHTML = message;
            deleteStatus.className = `delete-status ${type}`;
        }
    }

    // ===== دوال تسجيل الخروج =====
    function handleLogout(event) {
        event.preventDefault();
        
        fetch('ajax_handler.php?action=logout')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = 'home.php';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                window.location.href = 'logout.php';
            });
    }

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

    // ===== إغلاق المودال عند النقر خارج المحتوى =====
    if (deleteModal) {
        deleteModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeleteModal();
            }
        });
    }

    // ===== إغلاق بالـ ESC =====
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeSidebar();
            if (deleteModal && deleteModal.classList.contains('active')) {
                closeDeleteModal();
            }
        }
    });

    // ===== إغلاق القائمة الجانبية عند النقر على الروابط =====
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', closeSidebar);
    });

    // ===== إزالة رسالة النجاح بعد 3 ثواني =====
    setTimeout(() => {
        const toast = document.querySelector('.toast-message');
        if (toast) toast.remove();
    }, 3000);

    // ===== تحسين إدخال رقم الهاتف =====
    const phoneInputs = document.querySelectorAll('input[type="tel"]');
    phoneInputs.forEach(input => {
        input.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    });
    </script>
</body>
</html>