<?php
// Check if user is logged in
require_once 'includes/config.php';
require_once 'includes/functions.php';
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    redirect(SITE_URL . '/auth/login.php');
}

require_once 'includes/header.php';

// Get user information
$user = getUserById($pdo, $_SESSION['user_id']);

// Get user's order history
$stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY order_date DESC");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get user's favorite products
$favorites = getFavoriteProducts($pdo, $_SESSION['user_id']);

$message = '';

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $username = sanitizeInput($_POST['username']);
    $email = sanitizeInput($_POST['email']);
    $phone = sanitizeInput($_POST['phone']);
    
    // Validation
    if (empty($username) || empty($email)) {
        $message = '<div class="alert error">جميع الحقول مطلوبة.</div>';
    } else {
        // Check if email is already taken by another user
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $_SESSION['user_id']]);
        if ($stmt->fetch()) {
            $message = '<div class="alert error">البريد الإلكتروني مستخدم بالفعل من قبل مستخدم آخر.</div>';
        } else {
            // Update user information
            $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, phone = ? WHERE id = ?");
            if ($stmt->execute([$username, $email, $phone, $_SESSION['user_id']])) {
                $message = '<div class="alert success">تم تحديث الملف الشخصي بنجاح!</div>';
                // Update session variables
                $_SESSION['username'] = $username;
                $user = getUserById($pdo, $_SESSION['user_id']);
            } else {
                $message = '<div class="alert error">خطأ في تحديث الملف الشخصي. يرجى المحاولة مرة أخرى.</div>';
            }
        }
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validation
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $message = '<div class="alert error">جميع الحقول مطلوبة.</div>';
    } elseif ($new_password !== $confirm_password) {
        $message = '<div class="alert error">كلمات المرور الجديدة غير متطابقة.</div>';
    } elseif (strlen($new_password) < 6) {
        $message = '<div class="alert error">يجب أن تكون كلمة المرور مكونة من 6 أحرف على الأقل.</div>';
    } else {
        // Verify current password
        if (verifyPassword($current_password, $user['password'])) {
            // Update password
            $hashed_password = hashPassword($new_password);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashed_password, $_SESSION['user_id']])) {
                $message = '<div class="alert success">تم تغيير كلمة المرور بنجاح!</div>';
            } else {
                $message = '<div class="alert error">خطأ في تغيير كلمة المرور. يرجى المحاولة مرة أخرى.</div>';
            }
        } else {
            $message = '<div class="alert error">كلمة المرور الحالية غير صحيحة.</div>';
        }
    }
}
?>
<style>
/* Enhanced Profile Page Styles */
.profile-header {
    display: flex;
    align-items: center;
    background: linear-gradient(135deg, #3498db, #2c3e50);
    color: white;
    padding: 40px;
    border-radius: 16px;
    margin-bottom: 30px;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    position: relative;
    overflow: hidden;
    animation: fadeInUp 0.6s ease;
}

.profile-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9InBhdHRlcm4iIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CiAgICAgIDxjaXJjbGUgY3g9IjIwIiBjeT0iMjAiIHI9IjEiIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIi8+CiAgICA8L3BhdHRlcm4+CiAgPC9kZWZzPgogIDxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjcGF0dGVybikiLz4KPC9zdmc+') 0 0;
    opacity: 0.2;
}

body[dir='rtl'] .profile-header {
    flex-direction: row-reverse;
}

.profile-avatar {
    font-size: 6rem;
    margin-right: 30px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

body[dir='rtl'] .profile-avatar {
    margin-right: 0;
    margin-left: 30px;
}

.profile-info h1 {
    margin: 0 0 15px 0;
    font-size: 2.5rem;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.profile-email {
    margin: 0 0 15px 0;
    opacity: 0.95;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-email::before {
    content: '\f0e0';
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
}

.profile-phone {
    margin: 0 0 15px 0;
    opacity: 0.95;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-phone::before {
    content: '\f095';
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
}

.profile-role {
    display: inline-block;
    padding: 8px 20px;
    border-radius: 30px;
    font-weight: bold;
    font-size: 1rem;
    margin-bottom: 15px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    text-transform: uppercase;
    letter-spacing: 1px;
}

.profile-role.user {
    background: linear-gradient(135deg, #2ecc71, #27ae60);
}

.profile-role.admin {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
}

.profile-member-since {
    opacity: 0.9;
    font-size: 1rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-member-since::before {
    content: '\f274';
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
}

.profile-tabs {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 40px;
    animation: fadeIn 0.8s ease;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.tab-buttons {
    display: flex;
    border-bottom: 2px solid #eee;
}

body[dir='rtl'] .tab-buttons {
    flex-direction: row-reverse;
}

.tab-button {
    flex: 1;
    padding: 20px;
    background: none;
    border: none;
    font-size: 1.1rem;
    font-weight: 600;
    color: #7f8c8d;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.tab-button i {
    font-size: 1.2rem;
}

.tab-button.active {
    color: #3498db;
    background-color: rgba(52, 152, 219, 0.05);
}

.tab-button.active::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 100%;
    height: 4px;
    background: linear-gradient(90deg, #3498db, #2c3e50);
    border-radius: 2px 2px 0 0;
}

.tab-button:hover:not(.active) {
    background-color: #f8f9fa;
    color: #3498db;
}

.tab-content-wrapper {
    padding: 30px;
}

.profile-section {
    margin-bottom: 40px;
    animation: fadeIn 0.5s ease;
}

.profile-section h2 {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 10px;
}

.password-section {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 25px;
    border-radius: 12px;
    border: 1px solid #e1e8ed;
}

.profile-form .form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.profile-form .form-group {
    margin-bottom: 0;
}

.profile-form .form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #2c3e50;
}

.profile-form .form-group input {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e1e8ed;
    border-radius: 8px;
    font-size: 1rem;
    transition: all 0.3s ease;
    background-color: #fff;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
}

.profile-form .form-group input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.15);
}

.profile-form .form-text {
    display: block;
    margin-top: 5px;
    font-size: 0.85rem;
    color: #7f8c8d;
}

.btn-primary {
    background: linear-gradient(135deg, #3498db, #2980b9);
    color: white;
    border: none;
    padding: 12px 25px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    background: linear-gradient(135deg, #2980b9, #2573a7);
}

.order-card {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    margin-bottom: 20px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    border: 1px solid #eee;
    transition: all 0.3s ease;
}

.order-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
    flex-direction: row-reverse;
}

.order-info h3 {
    margin: 0 0 8px 0;
    color: #2c3e50;
    font-size: 1.3rem;
}

.order-date {
    margin: 0;
    color: #7f8c8d;
    font-size: 0.95rem;
}

.order-status {
    padding: 6px 16px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.9rem;
}

.order-status.completed {
    background: linear-gradient(135deg, #2ecc71, #27ae60);
    color: white;
    box-shadow: 0 2px 5px rgba(46, 204, 113, 0.2);
}

.order-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row-reverse;
}

.order-amount {
    font-size: 1.2rem;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}

.order-amount span {
    font-size: 0.9rem;
    color: #7f8c8d;
}

.order-amount strong {
    font-size: 1.5rem;
    color: #e74c3c;
    font-weight: 700;
}

.btn-outline {
    background: transparent;
    border: 2px solid #3498db;
    color: #3498db;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-outline:hover {
    background: #3498db;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(52, 152, 219, 0.2);
}

.empty-state {
    text-align: center;
    padding: 70px 20px;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-radius: 16px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    border: 1px solid #e9ecef;
}

.empty-state i {
    font-size: 5rem;
    color: #bdc3c7;
    margin-bottom: 25px;
    animation: bounce 2s infinite;
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-20px); }
}

.empty-state h3 {
    margin-bottom: 15px;
    color: #2c3e50;
    font-size: 1.8rem;
}

.empty-state p {
    color: #7f8c8d;
    max-width: 500px;
    margin: 0 auto 30px;
    font-size: 1.1rem;
    line-height: 1.6;
}

.favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 25px;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-weight: 500;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    animation: slideIn 0.3s ease;
}

@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateX(20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

.alert.success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert.error {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.message-container {
    margin-bottom: 20px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .profile-header {
        flex-direction: column;
        text-align: center;
        padding: 30px 20px;
    }
    
    .profile-avatar {
        margin-right: 0;
        margin-bottom: 20px;
    }
    
    body[dir='rtl'] .profile-avatar {
        margin-left: 0;
    }
    
    .profile-info h1 {
        font-size: 2rem;
    }
    
    .tab-buttons {
        flex-direction: column;
    }
    
    .profile-form .form-row {
        grid-template-columns: 1fr;
    }
    
    .order-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .order-details {
        width: 100%;
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .order-amount {
        align-items: flex-start;
    }
    
    .favorites-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
    }
}

@media (max-width: 480px) {
    .profile-header {
        padding: 25px 15px;
    }
    
    .profile-avatar {
        font-size: 5rem;
    }
    
    .profile-info h1 {
        font-size: 1.8rem;
    }
    
    .tab-button {
        padding: 15px;
        font-size: 1rem;
    }
    
    .tab-content-wrapper {
        padding: 20px 15px;
    }
    
    .profile-section h2 {
        font-size: 1.4rem;
    }
    
    .btn-primary, .btn-outline {
        width: 100%;
        justify-content: center;
    }
}
</style>
<div class="container" dir="rtl">
    <div class="profile-header">
        <div class="profile-avatar">
            <i class="fas fa-user-circle"></i>
        </div>
        <div class="profile-info">
            <h1><?php echo htmlspecialchars($user['username']); ?></h1>
            <p class="profile-email"><?php echo htmlspecialchars($user['email']); ?></p>
            <?php if (!empty($user['phone'])): ?>
                <p class="profile-phone">رقم الهاتف: <?php echo htmlspecialchars($user['phone']); ?></p>
            <?php endif; ?>
            <span class="profile-role <?php echo $user['role']; ?>"><?php echo ($user['role'] == 'admin') ? 'مدير' : 'مستخدم'; ?></span>
            <p class="profile-member-since">عضو منذ <?php echo date('j F Y', strtotime($user['created_at'])); ?></p>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="message-container">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div class="profile-tabs">
        <div class="tab-buttons">
            <button class="tab-button active" data-tab="profile">
                <i class="fas fa-user"></i>
                <span>الملف الشخصي</span>
            </button>
            <button class="tab-button" data-tab="orders">
                <i class="fas fa-shopping-bag"></i>
                <span>سجل الطلبات</span>
            </button>
            <button class="tab-button" data-tab="favorites">
                <i class="fas fa-heart"></i>
                <span>المفضلة</span>
            </button>
        </div>

        <div class="tab-content">
            <!-- Profile Tab -->
            <div class="tab-pane active" id="profile-tab">
                <div class="tab-content-wrapper">
                    <div class="profile-section">
                        <h2><i class="fas fa-user-edit"></i> المعلومات الشخصية</h2>
                        <form method="POST" action="" class="profile-form">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="username">اسم المستخدم</label>
                                    <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="email">البريد الإلكتروني</label>
                                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="phone">رقم الهاتف</label>
                                    <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                </div>
                                
                                <div class="form-group">
                                    <label for="role">الدور</label>
                                    <input type="text" id="role" name="role" value="<?php echo ($user['role'] == 'admin') ? 'مدير' : 'مستخدم'; ?>" readonly>
                                </div>
                            </div>
                            
                            <button type="submit" name="update_profile" class="btn btn-primary">
                                <i class="fas fa-save"></i> تحديث الملف الشخصي
                            </button>
                        </form>
                    </div>
                    
                    <div class="profile-section password-section">
                        <h2><i class="fas fa-lock"></i> تغيير كلمة المرور</h2>
                        <form method="POST" action="" class="profile-form">
                            <div class="form-group">
                                <label for="current_password">كلمة المرور الحالية</label>
                                <input type="password" id="current_password" name="current_password" required>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="new_password">كلمة المرور الجديدة</label>
                                    <input type="password" id="new_password" name="new_password" required>
                                    <small class="form-text">يجب أن تكون كلمة المرور مكونة من 6 أحرف على الأقل.</small>
                                </div>
                                
                                <div class="form-group">
                                    <label for="confirm_password">تأكيد كلمة المرور الجديدة</label>
                                    <input type="password" id="confirm_password" name="confirm_password" required>
                                </div>
                            </div>
                            
                            <button type="submit" name="change_password" class="btn btn-primary">
                                <i class="fas fa-key"></i> تغيير كلمة المرور
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Orders Tab -->
            <div class="tab-pane" id="orders-tab">
                <div class="tab-content-wrapper">
                    <h2><i class="fas fa-shopping-bag"></i> سجل الطلبات</h2>
                    <?php if (empty($orders)): ?>
                        <div class="empty-state">
                            <i class="fas fa-shopping-cart"></i>
                            <h3>لم يتم العثور على طلبات</h3>
                            <p>لم تقم بوضع أي طلبات بعد.</p>
                            <a href="<?php echo SITE_URL; ?>/products/index.php" class="btn btn-primary">
                                <i class="fas fa-shopping-bag"></i> ابدأ التسوق
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="orders-list">
                            <?php foreach ($orders as $order): ?>
                                <div class="order-card">
                                    <div class="order-header">
                                        <div class="order-info">
                                            <h3>طلب #<?php echo $order['id']; ?></h3>
                                            <p class="order-date"><?php echo date('j F Y', strtotime($order['order_date'])); ?></p>
                                        </div>
                                        <div class="order-status completed">مكتمل</div>
                                    </div>
                                    <div class="order-details">
                                        <div class="order-amount">
                                            <span>الإجمالي:</span>
                                            <strong>$<?php echo number_format($order['total_amount'], 2); ?></strong>
                                        </div>
                                        <a href="<?php echo SITE_URL; ?>/invoice.php?id=<?php echo $order['id']; ?>" target="_blank" class="btn btn-outline">
                                            <i class="fas fa-file-invoice"></i> عرض الفاتورة
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Favorites Tab -->
            <div class="tab-pane" id="favorites-tab">
                <div class="tab-content-wrapper">
                    <h2><i class="fas fa-heart"></i> المنتجات المفضلة</h2>
                    <?php if (empty($favorites)): ?>
                        <div class="empty-state">
                            <i class="fas fa-heart"></i>
                            <h3>لم يتم العثور على مفضلة</h3>
                            <p>لم تقم بإضافة أي منتجات إلى المفضلة بعد.</p>
                            <a href="<?php echo SITE_URL; ?>/products/index.php" class="btn btn-primary">
                                <i class="fas fa-box"></i> تصفح المنتجات
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="products-grid favorites-grid">
                            <?php foreach ($favorites as $product): ?>
                                <div class="product-card" data-product-id="<?php echo $product['id']; ?>">
                                    <div class="product-image">
                                        <?php if (!empty($product['image'])): ?>
                                            <img src="<?php echo SITE_URL . '/' . htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                                        <?php else: ?>
                                            <div class="image-placeholder">
                                                <i class="fas fa-image"></i>
                                            </div>
                                        <?php endif; ?>
                                        <button class="favorite-btn active" data-product-id="<?php echo $product['id']; ?>">
                                            <i class="fas fa-heart"></i>
                                        </button>
                                    </div>
                                    <div class="product-info">
                                        <h3><?php echo htmlspecialchars($product['name']); ?></h3>
                                        <div class="product-price">$<?php echo number_format($product['price'], 2); ?></div>
                                        <a href="<?php echo SITE_URL; ?>/products/view.php?id=<?php echo $product['id']; ?>" class="btn btn-primary btn-block">
                                            <i class="fas fa-eye"></i> عرض التفاصيل
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Tab switching functionality
document.addEventListener('DOMContentLoaded', function() {
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab') + '-tab';
            
            // Remove active class from all buttons and panes
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // Add active class to clicked button and corresponding pane
            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // Favorite button functionality
    const favoriteButtons = document.querySelectorAll('.favorite-btn');
    
    favoriteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const isFavorite = this.classList.contains('active');
            
            // Update UI immediately
            if (isFavorite) {
                this.classList.remove('active');
            } else {
                this.classList.add('active');
            }
            
            // Send request to server
            fetch('<?php echo SITE_URL; ?>/toggle_favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ product_id: productId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update button state based on server response
                    if (data.is_favorite) {
                        this.classList.add('active');
                    } else {
                        this.classList.remove('active');
                    }
                } else {
                    // Revert UI change if server request failed
                    if (isFavorite) {
                        this.classList.add('active');
                    } else {
                        this.classList.remove('active');
                    }
                    // alert('خطأ في تحديث المفضلة. يرجى المحاولة مرة أخرى.');
                }
            })
            .catch(error => {
                // Revert UI change if request failed
                if (isFavorite) {
                    this.classList.add('active');
                } else {
                    this.classList.remove('active');
                }
                console.error('Error:', error);
                // alert('خطأ في تحديث المفضلة. يرجى المحاولة مرة أخرى.');
            });
        });
    });
});
</script>

<?php require_once 'includes/footer.php'; ?>