<?php
/**
 * صفحة الحساب الشخصي - Roz Skin E-Commerce
 * Pinterest & iPhone Inspired Design - نفس استايل المتجر
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';
require_once '../models/user.php';
require_once '../models/order.php';
require_once '../models/wishlist.php';

$database = new Database();
$db = $database->getConnection();
$conn = $db; // للتوافق مع unified-header

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user = new User($db);
$order = new Order($db);
$wishlist = new Wishlist($db);

// Get user data
$user_data = $user->getUserById($_SESSION['user_id']);
if (!$user_data) {
    header('Location: login.php');
    exit;
}

// Get user orders
$orders = $order->getUserOrders($_SESSION['user_id']);

// Get user wishlist
$wishlist_items = $wishlist->getUserWishlist($_SESSION['user_id']);

// Get user bookings
$bookings = [];
try {
    $stmt = $db->prepare("
        SELECT b.*, s.name as service_name, s.duration, s.price, br.name as branch_name
        FROM bookings b
        JOIN services s ON b.service_id = s.id
        LEFT JOIN branches br ON b.branch_id = br.id
        WHERE b.user_id = ?
        ORDER BY b.booking_date DESC, b.booking_time DESC
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $bookings = [];
}

// جلب إعدادات الموقع
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('site_name', 'logo_text', 'font_family', 'default_currency')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
    $currency = $settings['default_currency'] ?? 'EGP';
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
    $currency = 'EGP';
}

$currency_symbols = ['EGP' => 'ج.م', 'USD' => '$', 'EUR' => '€', 'AED' => 'د.إ'];
$currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

// جلب عدد السلة
$cart_count = 0;
if (isset($_SESSION['user_id'])) {
    try {
        require_once '../models/cart.php';
        $cart_model = new Cart($db);
        $cart_count = $cart_model->getCartCount($_SESSION['user_id']);
    } catch (Exception $e) {
        $cart_count = 0;
    }
} elseif (isset($_SESSION['guest_cart'])) {
    $cart_count = array_sum($_SESSION['guest_cart']);
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_profile'])) {
        // Handle profile picture upload
        $profile_picture_path = $user_data['profile_picture'] ?? null;
        if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'uploads/users/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            $file_extension = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
            $file_name = 'profile_' . $_SESSION['user_id'] . '_' . time() . '.' . $file_extension;
            $target_path = $upload_dir . $file_name;

            // Validate file type
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array(strtolower($file_extension), $allowed_types)) {
                if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target_path)) {
                    $profile_picture_path = $target_path;
                } else {
                    $message = 'حدث خطأ أثناء رفع الصورة';
                }
            } else {
                $message = 'نوع الملف غير مدعوم. يرجى اختيار صورة (JPG, PNG, GIF)';
            }
        }

        // Update profile in database
        $address = trim($_POST['address'] ?? '');
        if ($user->updateProfile($_SESSION['user_id'], $_POST['name'], $_POST['phone'], $address)) {
            // Update profile picture if uploaded
            if ($profile_picture_path && $profile_picture_path !== ($user_data['profile_picture'] ?? null)) {
                $user->updateProfilePicture($_SESSION['user_id'], $profile_picture_path);
            }
            // Update session data
            $_SESSION['user_name'] = $_POST['name'];
            $_SESSION['user_phone'] = $_POST['phone'];
            $_SESSION['user_address'] = $_POST['address'];
            $_SESSION['profile_picture'] = $profile_picture_path;
            $message = 'تم تحديث البيانات بنجاح!';
            // Refresh user data
            $user_data = $user->getUserById($_SESSION['user_id']);
        } else {
            $message = 'حدث خطأ أثناء تحديث البيانات';
        }
    } elseif (isset($_POST['change_password'])) {
        // Change password logic
        if (password_verify($_POST['current_password'], $user_data['password'])) {
            if ($_POST['new_password'] === $_POST['confirm_password']) {
                // Update password in database
                if ($user->updatePassword($_SESSION['user_id'], $_POST['new_password'])) {
                    $message = 'تم تغيير كلمة المرور بنجاح!';
                } else {
                    $message = 'حدث خطأ أثناء تغيير كلمة المرور';
                }
            } else {
                $message = 'كلمتا المرور غير متطابقتين';
            }
        } else {
            $message = 'كلمة المرور الحالية غير صحيحة';
        }
    }
}
?>
<!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">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <title>حسابي - <?php echo htmlspecialchars($site_name); ?></title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    
    <!-- Styles -->
    <link rel="stylesheet" href="../assets/css/pinterest-style.css">
    <link rel="stylesheet" href="../assets/css/brand-enhanced.css">
    
    <style>
        /* إضافات خاصة بصفحة الحساب */
        .account-hero {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            color: white;
            padding: var(--space-2xl) 0;
            text-align: center;
            margin-top: 80px;
        }
        
        .account-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: var(--space-xl) var(--space-md);
        }
        
        .account-grid {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: var(--space-xl);
            margin-top: var(--space-xl);
        }
        
        .sidebar {
            background: white;
            border-radius: var(--radius-xl);
            padding: var(--space-lg);
            box-shadow: var(--shadow-md);
            height: fit-content;
            position: sticky;
            top: 100px;
        }
        
        .sidebar-menu {
            list-style: none;
        }
        
        .sidebar-menu li {
            margin-bottom: var(--space-sm);
        }
        
        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            padding: var(--space-md);
            color: var(--text-secondary);
            text-decoration: none;
            border-radius: var(--radius-md);
            transition: all var(--transition-base);
            font-weight: 500;
        }
        
        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            color: white;
            transform: translateX(-4px);
        }
        
        .main-content {
            background: white;
            border-radius: var(--radius-xl);
            padding: var(--space-2xl);
            box-shadow: var(--shadow-md);
            min-height: 600px;
        }
        
        .section {
            display: none;
        }
        
        .section.active {
            display: block;
            animation: fadeInUp 0.5s ease-out;
        }
        
        .section-title {
            font-size: var(--font-size-3xl);
            font-weight: 700;
            color: var(--primary);
            margin-bottom: var(--space-xl);
            text-align: center;
            position: relative;
        }
        
        .section-title::after {
            content: '';
            position: absolute;
            bottom: -8px;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 3px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            border-radius: 2px;
        }
        
        .profile-card {
            background: linear-gradient(135deg, rgba(229, 115, 147, 0.1) 0%, rgba(209, 83, 122, 0.1) 100%);
            border-radius: var(--radius-xl);
            padding: var(--space-xl);
            margin-bottom: var(--space-xl);
            border: 2px solid rgba(229, 115, 147, 0.2);
        }
        
        .profile-header {
            display: flex;
            align-items: center;
            gap: var(--space-xl);
            margin-bottom: var(--space-lg);
        }
        
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            overflow: hidden;
            border: 4px solid rgba(255, 255, 255, 0.8);
            box-shadow: 0 8px 25px rgba(229, 115, 147, 0.3);
            flex-shrink: 0;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .profile-info h3 {
            font-size: var(--font-size-2xl);
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: var(--space-sm);
        }
        
        .profile-info p {
            font-size: var(--font-size-lg);
            color: var(--text-secondary);
            margin-bottom: var(--space-md);
        }
        
        .form-group {
            margin-bottom: var(--space-lg);
        }
        
        .form-label {
            display: block;
            margin-bottom: var(--space-sm);
            font-weight: 600;
            color: var(--text-primary);
            font-size: var(--font-size-base);
        }
        
        .form-input {
            width: 100%;
            padding: var(--space-md);
            border: 2px solid var(--border-light);
            border-radius: var(--radius-md);
            font-size: var(--font-size-base);
            font-family: inherit;
            transition: all var(--transition-base);
            background: white;
        }
        
        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(229, 115, 147, 0.1);
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: var(--space-lg);
        }
        
        .message {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
            padding: var(--space-md);
            border-radius: var(--radius-md);
            margin-bottom: var(--space-lg);
            text-align: center;
            border: 1px solid #a7f3d0;
            font-weight: 500;
        }
        
        .order-card {
            background: var(--bg-secondary);
            border-radius: var(--radius-lg);
            padding: var(--space-lg);
            margin-bottom: var(--space-md);
            border: 1px solid var(--border-light);
            transition: all var(--transition-base);
        }
        
        .order-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-lg);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--space-md);
        }
        
        .order-status {
            padding: var(--space-sm) var(--space-md);
            border-radius: var(--radius-full);
            font-size: var(--font-size-sm);
            font-weight: 600;
        }
        
        .status-pending { background: #fef3c7; color: #d97706; }
        .status-processing { background: #dbeafe; color: #2563eb; }
        .status-shipped { background: #d1fae5; color: #065f46; }
        .status-delivered { background: #d1fae5; color: #065f46; }
        .status-cancelled { background: #fee2e2; color: #dc2626; }
        
        .wishlist-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: var(--space-lg);
        }
        
        .wishlist-item {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--space-lg);
            box-shadow: var(--shadow-sm);
            display: flex;
            align-items: center;
            gap: var(--space-md);
            transition: all var(--transition-base);
            border: 1px solid var(--border-light);
        }
        
        .wishlist-item:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-md);
        }
        
        .wishlist-image {
            width: 80px;
            height: 80px;
            background: var(--bg-secondary);
            border-radius: var(--radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            overflow: hidden;
        }
        
        .wishlist-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .edit-form {
            background: white;
            border-radius: var(--radius-xl);
            padding: var(--space-xl);
            box-shadow: var(--shadow-lg);
            border: 2px solid rgba(229, 115, 147, 0.1);
        }
        
        @media (max-width: 768px) {
            .account-grid {
                grid-template-columns: 1fr;
                gap: var(--space-lg);
            }
            
            .sidebar {
                position: static;
                order: 2;
            }
            
            .main-content {
                order: 1;
                padding: var(--space-lg);
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .profile-header {
                flex-direction: column;
                text-align: center;
            }
            
            .wishlist-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
</head>
<body>

    <!-- Navigation -->
    <nav class="nav-pinterest">
        <div class="container-pinterest">
            <div class="nav-content">
                <!-- Logo -->
                <a href="index.php" class="nav-logo" style="font-size: 28px; font-weight: 700; letter-spacing: -0.5px;">
                    <?php echo htmlspecialchars($logo_text); ?>
                </a>

                <!-- Search -->
                <div class="nav-search">
                    <div style="position: relative;">
                        <input type="text" 
                               class="search-input" 
                               placeholder="ابحث عن المنتجات..."
                               id="searchInput">
                        <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="position: absolute; right: 16px; top: 50%; transform: translateY(-50%); color: var(--text-tertiary);">
                            <circle cx="11" cy="11" r="8"></circle>
                            <path d="m21 21-4.35-4.35"></path>
                        </svg>
                    </div>
                </div>

                <!-- Actions -->
                <div class="nav-actions">
                    <button class="nav-icon-btn" onclick="window.location.href='account.php'" title="حسابي">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                            <circle cx="12" cy="7" r="4"></circle>
                        </svg>
                    </button>

                    <button class="nav-icon-btn" onclick="window.location.href='wishlist.php'" title="المفضلة">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                        </svg>
                    </button>

                    <button class="nav-icon-btn" onclick="window.location.href='cart.php'" title="السلة">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="9" cy="21" r="1"></circle>
                            <circle cx="20" cy="21" r="1"></circle>
                            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                        </svg>
                        <?php if ($cart_count > 0): ?>
                            <span class="nav-badge"><?php echo $cart_count; ?></span>
                        <?php endif; ?>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- Stories Section -->
    <?php include '../includes/stories-component.php'; ?>

    <!-- Account Hero Section -->
    <section class="account-hero">
        <div class="container-pinterest">
            <h1 style="font-size: clamp(32px, 5vw, 48px); font-weight: 700; margin-bottom: var(--space-md);">
                مرحباً، <?php echo htmlspecialchars($user_data['name'] ?? $_SESSION['user_name'] ?? 'المستخدم'); ?>
            </h1>
            <p style="font-size: clamp(16px, 2vw, 18px); opacity: 0.9;">
                إدارة حسابك الشخصي ومتابعة طلباتك وقائمة الأماني
            </p>
        </div>
    </section>

    <div class="account-container">
        <div class="account-grid">
            <!-- Sidebar -->
            <div class="sidebar">
                <ul class="sidebar-menu">
                    <li>
                        <a href="#profile" class="menu-link active" data-section="profile">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                            البيانات الشخصية
                        </a>
                    </li>
                    <li>
                        <a href="#addresses" class="menu-link" data-section="addresses">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                <circle cx="12" cy="10" r="3"></circle>
                            </svg>
                            عناويني
                        </a>
                    </li>
                    <li>
                        <a href="#orders" class="menu-link" data-section="orders">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
                                <rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect>
                            </svg>
                            الطلبات
                        </a>
                    </li>
                    <li>
                        <a href="#bookings" class="menu-link" data-section="bookings">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                            حجوزاتي
                        </a>
                    </li>
                    <li>
                        <a href="#wishlist" class="menu-link" data-section="wishlist">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                            </svg>
                            قائمة الأماني
                        </a>
                    </li>
                    <li>
                        <a href="#password" class="menu-link" data-section="password">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                <circle cx="12" cy="16" r="1"></circle>
                                <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                            </svg>
                            تغيير كلمة المرور
                        </a>
                    </li>
                    <li>
                        <a href="logout.php" style="color: #dc2626;">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                                <polyline points="16 17 21 12 16 7"></polyline>
                                <line x1="21" y1="12" x2="9" y2="12"></line>
                            </svg>
                            تسجيل الخروج
                        </a>
                    </li>
                </ul>
            </div>

            <!-- Main Content -->
            <div class="main-content">
                <?php if ($message): ?>
                    <div class="message"><?php echo $message; ?></div>
                <?php endif; ?>

                <!-- Profile Section -->
                <div id="profile" class="section active">
                    <h2 class="section-title">البيانات الشخصية</h2>

                    <!-- Profile Info Display -->
                    <div class="profile-card">
                        <div class="profile-header">
                            <!-- Profile Picture -->
                            <div class="profile-avatar">
                                <?php if ($user_data['profile_picture']): ?>
                                    <img src="<?php echo htmlspecialchars($user_data['profile_picture']); ?>" alt="صورة الملف الشخصي">
                                <?php else: ?>
                                    👤
                                <?php endif; ?>
                            </div>

                            <!-- User Info -->
                            <div class="profile-info">
                                <h3><?php echo htmlspecialchars($user_data['name'] ?? $_SESSION['user_name'] ?? ''); ?></h3>
                                <p><?php echo htmlspecialchars($user_data['phone'] ?? $_SESSION['user_phone'] ?? ''); ?></p>
                                <div style="display: flex; gap: var(--space-md); align-items: center; flex-wrap: wrap;">
                                    <span style="background: rgba(16, 185, 129, 0.1); color: #059669; padding: var(--space-sm) var(--space-md); border-radius: var(--radius-full); font-size: var(--font-size-sm); font-weight: 500;">
                                        العمر: <?php echo htmlspecialchars($user_data['age'] ?? 'غير محدد'); ?> سنة
                                    </span>
                                    <button type="button" onclick="toggleEditMode()" class="btn-primary">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                        </svg>
                                        تعديل البيانات
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Edit Form (Hidden by default) -->
                    <div id="edit-form" style="display: none;">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="edit-form">
                                <h3 style="color: var(--primary); margin-bottom: var(--space-lg); text-align: center; font-size: var(--font-size-xl); font-weight: 600;">
                                    تعديل البيانات الشخصية
                                </h3>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label class="form-label">الاسم الكامل</label>
                                        <input type="text" name="name" class="form-input" value="<?php echo htmlspecialchars($user_data['name'] ?? $_SESSION['user_name'] ?? ''); ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">رقم الهاتف</label>
                                        <input type="tel" name="phone" class="form-input" value="<?php echo htmlspecialchars($user_data['phone'] ?? $_SESSION['user_phone'] ?? ''); ?>" required>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">العنوان (اختياري)</label>
                                    <textarea name="address" class="form-input" rows="3" placeholder="أدخل عنوانك الكامل للتوصيل"><?php echo htmlspecialchars($user_data['address'] ?? $_SESSION['user_address'] ?? ''); ?></textarea>
                                    <small style="color: #999; font-size: 13px; display: block; margin-top: 5px;">
                                        💡 سيتم استخدام هذا العنوان عند الطلب
                                    </small>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">العمر</label>
                                    <input type="number" class="form-input" value="<?php echo htmlspecialchars($user_data['age'] ?? ''); ?>" readonly style="background: var(--bg-secondary);">
                                </div>

                                <div class="form-group">
                                    <label class="form-label">تغيير الصورة الشخصية</label>
                                    <input type="file" name="profile_picture" class="form-input" accept="image/*">
                                    <div style="margin-top: var(--space-sm); font-size: var(--font-size-sm); color: var(--text-secondary);">
                                        JPG, PNG, GIF - الحد الأقصى 5MB
                                    </div>
                                </div>

                                <div style="display: flex; gap: var(--space-md); justify-content: center; margin-top: var(--space-xl);">
                                    <button type="submit" name="update_profile" class="btn-primary">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="20 6 9 17 4 12"></polyline>
                                        </svg>
                                        حفظ التغييرات
                                    </button>
                                    <button type="button" class="btn-secondary" onclick="toggleEditMode()">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <line x1="18" y1="6" x2="6" y2="18"></line>
                                            <line x1="6" y1="6" x2="18" y2="18"></line>
                                        </svg>
                                        إلغاء
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Addresses Section -->
                <div id="addresses" class="section">
                    <h2 class="section-title">عناويني</h2>
                    <p style="color: var(--text-secondary); margin-bottom: var(--space-lg);">
                        أضف عناوينك المفضلة لتسهيل عملية الطلب
                    </p>
                    
                    <!-- Add New Address Button -->
                    <button type="button" class="btn-add-address" onclick="showAddAddressModal()">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="12" y1="5" x2="12" y2="19"></line>
                            <line x1="5" y1="12" x2="19" y2="12"></line>
                        </svg>
                        إضافة عنوان جديد
                    </button>
                    
                    <!-- Saved Addresses -->
                    <div class="addresses-grid" id="addressesList">
                        <!-- Addresses will be loaded here -->
                        <div class="empty-state">
                            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                <circle cx="12" cy="10" r="3"></circle>
                            </svg>
                            <p style="color: #999; margin-top: 15px;">لم تضف أي عناوين بعد</p>
                        </div>
                    </div>
                </div>
                
           <!-- Orders Section -->
                <div id="orders" class="section">
                    <h2 class="section-title">الطلبات</h2>
                    <?php if (!empty($orders)): ?>
                        <?php foreach ($orders as $order_item): ?>
                            <div class="order-card">
                                <div class="order-header">
                                    <div>
                                        <strong style="font-size: var(--font-size-lg); color: var(--text-primary);">
                                            طلب رقم: #<?php echo $order_item['id']; ?>
                                        </strong>
                                        <div style="font-size: var(--font-size-sm); color: var(--text-secondary); margin-top: var(--space-xs);">
                                            التاريخ: <?php echo date('Y-m-d H:i', strtotime($order_item['created_at'])); ?>
                                        </div>
                                    </div>
                                    <span class="order-status status-<?php echo strtolower($order_item['status']); ?>">
                                        <?php
                                        $status_ar = [
                                            'pending' => 'في الانتظار',
                                            'processing' => 'قيد المعالجة',
                                            'shipped' => 'تم الشحن',
                                            'delivered' => 'تم التسليم',
                                            'cancelled' => 'ملغي'
                                        ];
                                        echo $status_ar[$order_item['status']] ?? $order_item['status'];
                                        ?>
                                    </span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: var(--space-md);">
                                    <div style="font-size: var(--font-size-lg); font-weight: 700; color: var(--primary);">
                                        المبلغ: <?php echo $currency_symbol; ?> <?php echo number_format($order_item['total'], 2); ?>
                                    </div>
                                    <button class="btn-outline btn-sm" onclick="viewOrderDetails(<?php echo $order_item['id']; ?>)">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                            <circle cx="12" cy="12" r="3"></circle>
                                        </svg>
                                        عرض التفاصيل
                                    </button>
                                </div>
                                <?php if (!empty($order_item['address'])): ?>
                                    <div style="margin-top: var(--space-md); padding-top: var(--space-md); border-top: 1px solid var(--border-light); color: var(--text-secondary); font-size: var(--font-size-sm);">
                                        <strong>عنوان التوصيل:</strong><br>
                                        <?php 
                                        $full_address = $order_item['address'] . ', ' . $order_item['city'];
                                        echo nl2br(htmlspecialchars(substr($full_address, 0, 100) . (strlen($full_address) > 100 ? '...' : ''))); 
                                        ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="text-align: center; padding: var(--space-2xl); color: var(--text-secondary);">
                            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" style="margin: 0 auto var(--space-md); opacity: 0.3;">
                                <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
                                <rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect>
                            </svg>
                            <p style="font-size: var(--font-size-lg); margin-bottom: var(--space-md);">لا توجد طلبات سابقة</p>
                            <a href="index.php" class="btn-primary">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="9" cy="21" r="1"></circle>
                                    <circle cx="20" cy="21" r="1"></circle>
                                    <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                                </svg>
                                ابدأ التسوق الآن
                            </a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Bookings Section -->
                <div id="bookings" class="section">
                    <h2 class="section-title">حجوزاتي</h2>
                    <?php if (!empty($bookings)): ?>
                        <div style="display: grid; gap: var(--space-lg);">
                            <?php foreach ($bookings as $booking): ?>
                                <div class="order-card">
                                    <div class="order-header">
                                        <div>
                                            <strong style="font-size: var(--font-size-lg); color: var(--text-primary);">
                                                <?php echo htmlspecialchars($booking['service_name']); ?>
                                            </strong>
                                            <div style="font-size: var(--font-size-sm); color: var(--text-secondary); margin-top: var(--space-xs);">
                                                <i class="far fa-calendar"></i>
                                                <?php echo date('Y-m-d', strtotime($booking['booking_date'])); ?> 
                                                في <?php echo date('h:i A', strtotime($booking['booking_time'])); ?>
                                            </div>
                                        </div>
                                        <span class="order-status status-<?php echo strtolower($booking['status']); ?>">
                                            <?php
                                            $status_ar = [
                                                'pending' => 'في الانتظار',
                                                'confirmed' => 'مؤكد',
                                                'completed' => 'مكتمل',
                                                'cancelled' => 'ملغي'
                                            ];
                                            echo $status_ar[$booking['status']] ?? $booking['status'];
                                            ?>
                                        </span>
                                    </div>
                                    
                                    <div style="margin-top: var(--space-md); display: grid; gap: var(--space-sm);">
                                        <?php if ($booking['branch_name']): ?>
                                        <div style="color: var(--text-secondary); font-size: var(--font-size-sm);">
                                            <i class="fas fa-map-marker-alt" style="color: var(--primary);"></i>
                                            <strong>الفرع:</strong> <?php echo htmlspecialchars($booking['branch_name']); ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div style="color: var(--text-secondary); font-size: var(--font-size-sm);">
                                            <i class="far fa-clock" style="color: var(--primary);"></i>
                                            <strong>المدة:</strong> <?php echo $booking['duration']; ?> دقيقة
                                        </div>
                                        
                                        <div style="color: var(--text-secondary); font-size: var(--font-size-sm);">
                                            <i class="fas fa-money-bill-wave" style="color: var(--primary);"></i>
                                            <strong>السعر:</strong> <?php echo number_format($booking['price'], 0); ?> ج.م
                                        </div>
                                        
                                        <?php if ($booking['notes']): ?>
                                        <div style="color: var(--text-secondary); font-size: var(--font-size-sm); margin-top: var(--space-sm); padding-top: var(--space-sm); border-top: 1px solid var(--border-light);">
                                            <strong>ملاحظات:</strong><br>
                                            <?php echo nl2br(htmlspecialchars($booking['notes'])); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <?php if ($booking['status'] === 'pending'): ?>
                                    <div style="margin-top: var(--space-md); display: flex; gap: var(--space-sm);">
                                        <button class="btn-outline btn-sm" style="flex: 1; color: #dc2626; border-color: #dc2626;" 
                                                onclick="cancelBooking(<?php echo $booking['id']; ?>)">
                                            <i class="fas fa-times"></i>
                                            إلغاء الحجز
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                            <p style="color: #999; margin-top: 15px;">لا توجد حجوزات حتى الآن</p>
                            <a href="services.php" class="btn-primary" style="margin-top: var(--space-md); display: inline-block;">
                                تصفح الخدمات
                            </a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Wishlist Section -->
                <div id="wishlist" class="section">
                    <h2 class="section-title">قائمة الأماني</h2>
                    <?php if (!empty($wishlist_items)): ?>
                        <div class="wishlist-grid">
                            <?php foreach ($wishlist_items as $item): ?>
                                <div class="wishlist-item">
                                    <div class="wishlist-image">
                                        <?php if ($item['image']): ?>
                                            <img src="<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>">
                                        <?php else: ?>
                                            <div style="color: var(--text-light); font-size: 2rem;">📦</div>
                                        <?php endif; ?>
                                    </div>
                                    <div style="flex: 1;">
                                        <h4 style="margin: 0 0 var(--space-sm) 0; font-weight: 600; color: var(--text-primary); font-size: var(--font-size-base);">
                                            <?php echo htmlspecialchars($item['name']); ?>
                                        </h4>
                                        <p style="margin: 0 0 var(--space-md) 0; color: var(--primary); font-weight: 700; font-size: var(--font-size-lg);">
                                            <?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0, ',', ','); ?>
                                        </p>
                                        <div style="display: flex; gap: var(--space-sm); flex-wrap: wrap;">
                                            <a href="product.php?id=<?php echo $item['product_id']; ?>" class="btn-outline btn-sm">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                                    <circle cx="12" cy="12" r="3"></circle>
                                                </svg>
                                                عرض المنتج
                                            </a>
                                            <button onclick="addToCartFromWishlist(<?php echo $item['product_id']; ?>, '<?php echo addslashes($item['name']); ?>')" class="btn-primary btn-sm">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                    <circle cx="9" cy="21" r="1"></circle>
                                                    <circle cx="20" cy="21" r="1"></circle>
                                                    <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                                                </svg>
                                                أضف للسلة
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div style="text-align: center; padding: var(--space-2xl); color: var(--text-secondary);">
                            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" style="margin: 0 auto var(--space-md); opacity: 0.3;">
                                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                            </svg>
                            <p style="font-size: var(--font-size-lg); margin-bottom: var(--space-md);">قائمة الأماني فارغة</p>
                            <a href="index.php" class="btn-primary">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                                </svg>
                                اكتشف المنتجات
                            </a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Password Section -->
                <div id="password" class="section">
                    <h2 class="section-title">تغيير كلمة المرور</h2>
                    <form method="POST">
                        <div class="edit-form">
                            <div class="form-group">
                                <label class="form-label">كلمة المرور الحالية</label>
                                <input type="password" name="current_password" class="form-input" required>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">كلمة المرور الجديدة</label>
                                    <input type="password" name="new_password" class="form-input" required>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">تأكيد كلمة المرور الجديدة</label>
                                    <input type="password" name="confirm_password" class="form-input" required>
                                </div>
                            </div>

                            <div style="display: flex; gap: var(--space-md); justify-content: center; margin-top: var(--space-xl);">
                                <button type="submit" name="change_password" class="btn-primary">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                        <circle cx="12" cy="16" r="1"></circle>
                                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                    </svg>
                                    تغيير كلمة المرور
                                </button>
                                <button type="button" class="btn-secondary" onclick="history.back()">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <line x1="18" y1="6" x2="6" y2="18"></line>
                                        <line x1="6" y1="6" x2="18" y2="18"></line>
                                    </svg>
                                    إلغاء
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="toast" class="toast-notification hidden"></div>

    <!-- Footer -->
    <footer style="background: var(--secondary); color: white; padding: var(--space-2xl) 0 var(--space-lg); margin-top: var(--space-2xl);">
        <div class="container-pinterest">
            <!-- Footer Top -->
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: var(--space-xl); margin-bottom: var(--space-xl);">
                <!-- About -->
                <div>
                    <h3 style="font-size: 20px; font-weight: 700; margin-bottom: var(--space-md); color: white;">
                        <?php echo htmlspecialchars($logo_text); ?>
                    </h3>
                    <p style="color: rgba(255,255,255,0.8); line-height: 1.6; margin-bottom: var(--space-md); font-size: 14px;">
                        متجر إلكتروني متخصص في منتجات العناية بالبشرة والجمال الطبيعية 100% مع خدمات متخصصة في مركزنا المتطور.
                    </p>
                </div>

                <!-- Quick Links -->
                <div>
                    <h3 style="font-size: 18px; font-weight: 700; margin-bottom: var(--space-md); color: white;">
                        روابط سريعة
                    </h3>
                    <ul style="list-style: none;">
                        <li style="margin-bottom: var(--space-sm);">
                            <a href="index.php" style="color: rgba(255,255,255,0.8); text-decoration: none; font-size: 14px; transition: color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='rgba(255,255,255,0.8)'">
                                الرئيسية
                            </a>
                        </li>
                        <li style="margin-bottom: var(--space-sm);">
                            <a href="products.php" style="color: rgba(255,255,255,0.8); text-decoration: none; font-size: 14px; transition: color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='rgba(255,255,255,0.8)'">
                                المنتجات
                            </a>
                        </li>
                        <li style="margin-bottom: var(--space-sm);">
                            <a href="cart.php" style="color: rgba(255,255,255,0.8); text-decoration: none; font-size: 14px; transition: color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='rgba(255,255,255,0.8)'">
                                السلة
                            </a>
                        </li>
                        <li>
                            <a href="wishlist.php" style="color: rgba(255,255,255,0.8); text-decoration: none; font-size: 14px; transition: color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='rgba(255,255,255,0.8)'">
                                المفضلة
                            </a>
                        </li>
                    </ul>
                </div>

                <!-- Contact -->
                <div>
                    <h3 style="font-size: 18px; font-weight: 700; margin-bottom: var(--space-md); color: white;">
                        تواصل معنا
                    </h3>
                    <ul style="list-style: none;">
                        <li style="margin-bottom: var(--space-sm); display: flex; align-items: center; gap: var(--space-sm);">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.8)" stroke-width="2">
                                <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                            </svg>
                            <span style="color: rgba(255,255,255,0.8); font-size: 14px;">01234567890</span>
                        </li>
                        <li style="margin-bottom: var(--space-sm); display: flex; align-items: center; gap: var(--space-sm);">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.8)" stroke-width="2">
                                <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path>
                                <polyline points="22,6 12,13 2,6"></polyline>
                            </svg>
                            <span style="color: rgba(255,255,255,0.8); font-size: 14px;">info@rozskin.com</span>
                        </li>
                        <li style="display: flex; align-items: start; gap: var(--space-sm);">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.8)" stroke-width="2" style="margin-top: 2px;">
                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                <circle cx="12" cy="10" r="3"></circle>
                            </svg>
                            <span style="color: rgba(255,255,255,0.8); font-size: 14px; line-height: 1.5;">القاهرة، مصر</span>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Footer Bottom -->
            <div style="border-top: 1px solid rgba(255,255,255,0.1); padding-top: var(--space-lg); text-align: center;">
                <p style="color: rgba(255,255,255,0.6); font-size: 14px; margin: 0;">
                    © <?php echo date('Y'); ?> <?php echo htmlspecialchars($logo_text); ?>. جميع الحقوق محفوظة.
                </p>
            </div>
        </div>
    </footer>

    <script>
        // Enhanced Toast Notification with Icons
        function showToast(message, duration = 3000) {
            const toast = document.getElementById('toast');
            
            // Add icon based on message
            let icon = '';
            if (message.includes('✓') || message.includes('نجاح') || message.includes('تم')) {
                icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-left: 8px;"><polyline points="20 6 9 17 4 12"></polyline></svg>';
            } else if (message.includes('خطأ') || message.includes('فشل')) {
                icon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-left: 8px;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>';
            }
            
            toast.innerHTML = '<div style="display: flex; align-items: center; justify-content: center;">' + icon + '<span>' + message + '</span></div>';
            toast.classList.remove('hidden');
            toast.style.animation = 'slideDown 0.3s ease-out';
            
            setTimeout(() => {
                toast.style.animation = 'slideUp 0.3s ease-in';
                setTimeout(() => {
                    toast.classList.add('hidden');
                }, 300);
            }, duration);
        }
        
        // Add toast animations
        const toastStyle = document.createElement('style');
        toastStyle.textContent = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translate(-50%, -20px);
                }
                to {
                    opacity: 1;
                    transform: translate(-50%, 0);
                }
            }
            @keyframes slideUp {
                from {
                    opacity: 1;
                    transform: translate(-50%, 0);
                }
                to {
                    opacity: 0;
                    transform: translate(-50%, -20px);
                }
            }
        `;
        document.head.appendChild(toastStyle);

        // Tab switching functionality
        function showTab(tabName) {
            // Remove active class from all links and hide all sections
            document.querySelectorAll('.menu-link').forEach(l => l.classList.remove('active'));
            document.querySelectorAll('.section').forEach(s => {
                s.classList.remove('active');
                s.style.display = 'none';
            });

            // Add active class to clicked link and show corresponding section
            const link = document.querySelector(`.menu-link[data-section="${tabName}"]`);
            if (link) {
                link.classList.add('active');
            }
            const section = document.getElementById(tabName);
            if (section) {
                section.classList.add('active');
                section.style.display = 'block';
            }
        }
        
        document.querySelectorAll('.menu-link').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const sectionId = this.getAttribute('data-section');
                showTab(sectionId);
            });
        });
        
        // Check URL parameter for tab
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab');
        if (tab) {
            showTab(tab);
        }
        
        // Check URL hash for tab (e.g., #addresses)
        if (window.location.hash) {
            const hashTab = window.location.hash.substring(1); // Remove #
            showTab(hashTab);
        }

        // Toggle edit mode
        function toggleEditMode() {
            const editForm = document.getElementById('edit-form');
            const profileCard = document.querySelector('.profile-card');
            
            if (editForm.style.display === 'none' || editForm.style.display === '') {
                editForm.style.display = 'block';
                profileCard.style.display = 'none';
            } else {
                editForm.style.display = 'none';
                profileCard.style.display = 'block';
            }
        }

        // Add to Cart from Wishlist
        function addToCartFromWishlist(productId, productName) {
            const button = event.target;
            const originalHTML = button.innerHTML;
            
            // Show loading
            button.disabled = true;
            button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation: spin 1s linear infinite;"><circle cx="12" cy="12" r="10" stroke-opacity="0.25"></circle><path d="M12 2a10 10 0 0 1 10 10" stroke-opacity="0.75"></path></svg>';

            fetch('../api/cart/add.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'product_id=' + productId + '&quantity=1'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('✓ تم إضافة ' + productName + ' للسلة');
                    
                    // Update cart badge - تحديث عداد السلة فقط 🛒
                    const cartBadge = document.getElementById('cartBadge'); // استخدام ID محدد
                    if (cartBadge) {
                        cartBadge.textContent = data.cart_count || parseInt(cartBadge.textContent) + 1;
                    }
                    
                    // Success animation
                    button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg> تم الإضافة';
                    setTimeout(() => {
                        button.innerHTML = originalHTML;
                        button.disabled = false;
                    }, 2000);
                } else {
                    showToast(data.message || 'حدث خطأ');
                    button.innerHTML = originalHTML;
                    button.disabled = false;
                }
            })
            .catch(() => {
                showToast('حدث خطأ، حاول مرة أخرى');
                button.innerHTML = originalHTML;
                button.disabled = false;
            });
        }

        // View Order Details
        function viewOrderDetails(orderId) {
            window.location.href = 'order-success.php?order_id=' + orderId;
        }
        
        // Add spin animation
        const style = document.createElement('style');
        style.textContent = `
            @keyframes spin {
                from { transform: rotate(0deg); }
                to { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);

        // Search functionality
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const query = this.value.trim();
                if (query) {
                    window.location.href = 'products.php?search=' + encodeURIComponent(query);
                }
            }
        });
    </script>
    
    <!-- Add Address Modal -->
    <div id="addAddressModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>إضافة عنوان جديد</h3>
                <button type="button" class="modal-close" onclick="closeAddAddressModal()">×</button>
            </div>
            <div class="modal-body">
                <form id="addAddressForm">
                    <div class="form-group">
                        <label>اسم العنوان</label>
                        <input type="text" id="addressLabel" class="form-input" placeholder="مثال: المنزل، العمل" required>
                    </div>
                    
                    <div class="form-group">
                        <label>العنوان الكامل</label>
                        <textarea id="addressFull" class="form-input" rows="3" placeholder="الشارع، المنطقة، المدينة" required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <button type="button" class="btn-location" onclick="getMyLocation()">
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                <circle cx="12" cy="10" r="3"></circle>
                            </svg>
                            استخدام موقعي الحالي
                        </button>
                        <small style="color: #999; display: block; margin-top: 8px;">
                            سيتم تحديد موقعك تلقائياً
                        </small>
                    </div>
                    
                    <input type="hidden" id="addressLat">
                    <input type="hidden" id="addressLng">
                    
                    <div class="modal-actions">
                        <button type="button" class="btn-secondary" onclick="closeAddAddressModal()">إلغاء</button>
                        <button type="submit" class="btn-primary">حفظ العنوان</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <style>
        .btn-add-address {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            color: white;
            border: none;
            padding: 14px 24px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: var(--space-xl);
            transition: all 0.3s;
        }
        
        .btn-add-address:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(229, 115, 147, 0.3);
        }
        
        .addresses-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: var(--space-lg);
        }
        
        .address-card {
            background: white;
            border: 2px solid var(--border-light);
            border-radius: 16px;
            padding: var(--space-lg);
            transition: all 0.3s;
            position: relative;
        }
        
        .address-card:hover {
            border-color: var(--primary);
            box-shadow: 0 4px 15px rgba(229, 115, 147, 0.1);
        }
        
        .address-card.default {
            border-color: var(--primary);
            background: linear-gradient(135deg, rgba(229, 115, 147, 0.05) 0%, rgba(209, 83, 122, 0.05) 100%);
        }
        
        .address-label {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .address-text {
            color: var(--text-secondary);
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: var(--space-md);
        }
        
        .address-actions {
            display: flex;
            gap: 8px;
        }
        
        .btn-location {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-location:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
        }
        
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            padding: 20px;
        }
        
        .modal-content {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideUp 0.3s ease-out;
        }
        
        @keyframes modalSlideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .modal-header {
            padding: 24px;
            border-bottom: 1px solid var(--border-light);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .modal-header h3 {
            font-size: 20px;
            font-weight: 700;
            color: var(--text-primary);
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 32px;
            color: var(--text-secondary);
            cursor: pointer;
            line-height: 1;
            padding: 0;
            width: 32px;
            height: 32px;
        }
        
        .modal-body {
            padding: 24px;
        }
        
        .modal-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }
        
        .btn-secondary {
            flex: 1;
            padding: 12px;
            background: var(--bg-secondary);
            color: var(--text-primary);
            border: none;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
        }
        
        .btn-primary {
            flex: 1;
            padding: 12px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
    </style>
    
    <script>
        // Cancel booking function
        function cancelBooking(bookingId) {
            if (!confirm('هل أنت متأكد من إلغاء هذا الحجز؟')) {
                return;
            }
            
            fetch('../api/bookings/cancel.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({booking_id: bookingId})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    alert('تم إلغاء الحجز بنجاح');
                    location.reload();
                } else {
                    alert(data.message || 'حدث خطأ');
                }
            })
            .catch(() => alert('حدث خطأ في الاتصال'));
        }
        
        function showAddAddressModal() {
            document.getElementById('addAddressModal').style.display = 'flex';
        }
        
        function closeAddAddressModal() {
            document.getElementById('addAddressModal').style.display = 'none';
            document.getElementById('addAddressForm').reset();
        }
        
        function getMyLocation() {
            if (navigator.geolocation) {
                const btn = event.target.closest('.btn-location');
                btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle></svg> جاري تحديد الموقع...';
                btn.disabled = true;
                
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        const lat = position.coords.latitude;
                        const lng = position.coords.longitude;
                        
                        document.getElementById('addressLat').value = lat;
                        document.getElementById('addressLng').value = lng;
                        
                        // Get address from coordinates using reverse geocoding
                        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 || `${lat}, ${lng}`;
                                document.getElementById('addressFull').value = address;
                                btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"></path></svg> تم تحديد الموقع';
                                btn.style.background = 'linear-gradient(135deg, #4CAF50 0%, #45a049 100%)';
                                setTimeout(() => {
                                    btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg> استخدام موقعي الحالي';
                                    btn.disabled = false;
                                }, 2000);
                            })
                            .catch(error => {
                                document.getElementById('addressFull').value = `الموقع: ${lat}, ${lng}`;
                                btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg> استخدام موقعي الحالي';
                                btn.disabled = false;
                            });
                    },
                    function(error) {
                        alert('لم نتمكن من تحديد موقعك. تأكد من السماح بالوصول للموقع.');
                        btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg> استخدام موقعي الحالي';
                        btn.disabled = false;
                    }
                );
            } else {
                alert('المتصفح لا يدعم خاصية تحديد الموقع');
            }
        }
        
        document.getElementById('addAddressForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const addressData = {
                label: document.getElementById('addressLabel').value,
                address: document.getElementById('addressFull').value,
                lat: document.getElementById('addressLat').value || null,
                lng: document.getElementById('addressLng').value || null,
                is_default: false
            };
            
            // Save address to backend
            fetch('../api/addresses.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(addressData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ تم حفظ العنوان بنجاح!');
                    closeAddAddressModal();
                    loadAddresses();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('حدث خطأ أثناء حفظ العنوان');
            });
        });
        
        function loadAddresses() {
            fetch('../api/addresses.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.addresses.length > 0) {
                        displayAddresses(data.addresses);
                    } else {
                        document.getElementById('addressesList').innerHTML = `
                            <div class="empty-state">
                                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
                                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                    <circle cx="12" cy="10" r="3"></circle>
                                </svg>
                                <p style="color: #999; margin-top: 15px;">لم تضف أي عناوين بعد</p>
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
        
        function displayAddresses(addresses) {
            const html = addresses.map(addr => `
                <div class="address-card ${addr.is_default ? 'default' : ''}">
                    <div class="address-label">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                            <circle cx="12" cy="10" r="3"></circle>
                        </svg>
                        ${addr.label}
                        ${addr.is_default ? '<span style="background: var(--primary); color: white; padding: 2px 8px; border-radius: 4px; font-size: 11px; margin-right: 8px;">افتراضي</span>' : ''}
                    </div>
                    <div class="address-text">${addr.address}</div>
                    <div class="address-actions">
                        <button type="button" class="btn-secondary" style="padding: 8px 16px; font-size: 13px;" onclick="deleteAddress(${addr.id})">
                            حذف
                        </button>
                        ${addr.latitude && addr.longitude ? `
                            <button type="button" class="btn-secondary" style="padding: 8px 16px; font-size: 13px;" onclick="window.open('https://www.google.com/maps?q=${addr.latitude},${addr.longitude}', '_blank')">
                                عرض على الخريطة
                            </button>
                        ` : ''}
                    </div>
                </div>
            `).join('');
            
            document.getElementById('addressesList').innerHTML = html;
        }
        
        function deleteAddress(addressId) {
            if (!confirm('هل تريد حذف هذا العنوان؟')) return;
            
            fetch('../api/addresses.php', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ address_id: addressId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadAddresses();
                } else {
                    alert('حدث خطأ أثناء الحذف');
                }
            });
        }
        
        // Load addresses when page loads
        if (document.getElementById('addressesList')) {
            loadAddresses();
        }
    </script>

</body>
</html>