<?php
session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';
require_once '../models/user.php';

// إعدادات الصفحة
$page_title = 'المفضلة';
$base_path = '../';

// الاتصال بقاعدة البيانات
$database = new Database();
$conn = $database->getConnection();

// Initialize user model for footer
$user_model = new User($conn);

// جلب إعدادات العملة
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('default_currency')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    $currency = $settings['default_currency'] ?? 'EGP';
} catch (PDOException $e) {
    $currency = 'EGP';
}

$currency_symbols = ['EGP' => 'ج.م', 'USD' => '$', 'EUR' => '€', 'AED' => 'د.إ'];
$currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

// جلب المنتجات المفضلة
$wishlist_items = [];

if (isset($_SESSION['user_id'])) {
    $stmt = $conn->prepare("
        SELECT w.*, p.name, p.price, p.image, p.stock_quantity as stock 
        FROM wishlist w 
        JOIN products p ON w.product_id = p.id 
        WHERE w.user_id = ?
        ORDER BY w.created_at DESC
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $wishlist_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// تضمين Header
include '../includes/unified-header.php';
?>

<!-- Hero Section -->
<section class="py-8 bg-gradient-to-br from-pink-50 to-purple-50">
    <div class="container">
        <div class="flex items-center gap-3 text-sm text-gray-600 mb-4">
            <a href="index.php" class="hover:text-[#E57393]">الرئيسية</a>
            <i class="fas fa-chevron-left text-xs"></i>
            <span class="text-[#E57393]">المفضلة</span>
        </div>
        <h1 class="text-4xl font-bold">
            <i class="fas fa-heart text-[#E57393]"></i>
            قائمة المفضلة
        </h1>
        <p class="text-gray-600 mt-2">
            <?php echo count($wishlist_items); ?> منتج في المفضلة
        </p>
    </div>
</section>

<!-- Wishlist Content -->
<section class="py-12">
    <div class="container">
        <?php if (empty($wishlist_items)): ?>
            <!-- Empty Wishlist -->
            <div class="text-center py-16">
                <div class="w-32 h-32 mx-auto mb-6 rounded-full bg-gradient-to-br from-pink-100 to-purple-100 flex items-center justify-center">
                    <i class="fas fa-heart text-6xl text-[#E57393]"></i>
                </div>
                <h2 class="text-2xl font-bold mb-4">قائمة المفضلة فارغة</h2>
                <p class="text-gray-600 mb-8">لم تقم بإضافة أي منتجات للمفضلة بعد</p>
                <a href="products.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-shopping-bag"></i>
                    تصفح المنتجات
                </a>
            </div>
        <?php else: ?>
            <!-- Wishlist Grid -->
            <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
                <?php foreach ($wishlist_items as $item): ?>
                    <div class="card" data-item-id="<?php echo $item['id']; ?>">
                        <div class="card-image relative">
                            <img src="uploads/products/<?php echo htmlspecialchars($item['image']); ?>" 
                                 alt="<?php echo htmlspecialchars($item['name']); ?>">
                            
                            <!-- Remove from Wishlist Button -->
                            <button onclick="removeFromWishlist(<?php echo $item['product_id']; ?>)" 
                                    class="absolute top-4 right-4 w-10 h-10 rounded-full bg-white shadow-lg flex items-center justify-center hover:bg-red-50 transition group">
                                <i class="fas fa-heart text-[#E57393] group-hover:text-red-500"></i>
                            </button>
                            

                        </div>
                        
                        <div class="card-body">
                            <h3 class="card-title">
                                <a href="product.php?id=<?php echo $item['product_id']; ?>" class="hover:text-[#E57393]">
                                    <?php echo htmlspecialchars($item['name']); ?>
                                </a>
                            </h3>
                            
                            <div class="price-container mb-4">
                                <span class="price-current"><?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0); ?></span>
                            </div>
                            
                            <?php if ($item['stock'] > 0): ?>
                                <button onclick="addToCart(<?php echo $item['product_id']; ?>)" 
                                        class="btn btn-primary w-full btn-sm">
                                    <i class="fas fa-shopping-cart"></i>
                                    أضف للسلة
                                </button>
                            <?php else: ?>
                                <button class="btn btn-outline w-full btn-sm" disabled>
                                    <i class="fas fa-times-circle"></i>
                                    غير متوفر
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Actions -->
            <div class="mt-12 text-center">
                <button onclick="addAllToCart()" class="btn btn-primary btn-lg mr-4">
                    <i class="fas fa-shopping-cart"></i>
                    أضف الكل للسلة
                </button>
                <button onclick="clearWishlist()" class="btn btn-outline btn-lg">
                    <i class="fas fa-trash"></i>
                    مسح القائمة
                </button>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- Recommended Products -->
<section class="py-12 bg-gray-50">
    <div class="container">
        <h2 class="text-3xl font-bold text-center mb-8">منتجات مقترحة</h2>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
            <?php
            $stmt = $conn->prepare("SELECT * FROM products WHERE stock_quantity > 0 ORDER BY RAND() LIMIT 4");
            $stmt->execute();
            $recommended = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($recommended as $product):
            ?>
                <div class="card">
                    <div class="card-image">
                        <img src="uploads/products/<?php echo htmlspecialchars($product['image']); ?>" 
                             alt="<?php echo htmlspecialchars($product['name']); ?>">
                        <button onclick="toggleWishlist(<?php echo $product['id']; ?>)" 
                                class="absolute top-4 right-4 icon-btn">
                            <i class="far fa-heart"></i>
                        </button>
                    </div>
                    <div class="card-body">
                        <h3 class="card-title"><?php echo htmlspecialchars($product['name']); ?></h3>
                        <div class="price-container mb-4">
                            <span class="price-current"><?php echo $currency_symbol; ?> <?php echo number_format($product['price'], 0); ?></span>
                        </div>
                        <button onclick="addToCart(<?php echo $product['id']; ?>)" class="btn btn-primary w-full btn-sm">
                            <i class="fas fa-shopping-cart"></i>
                            أضف للسلة
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<script>
// Remove from Wishlist
function removeFromWishlist(productId) {
    fetch('../api/wishlist/toggle.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'product_id=' + productId
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showToast('تم الحذف من المفضلة', 'success');
            setTimeout(() => location.reload(), 500);
        }
    })
    .catch(err => {
        showToast('حدث خطأ', 'error');
    });
}

// Add to Cart
function addToCart(productId) {
    fetch('../api/cart/add.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'product_id=' + productId + '&quantity=1'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showToast('تم إضافة المنتج للسلة', 'success');
            // Update cart badge
            document.getElementById('cartBadge').textContent = data.cart_count;
        }
    })
    .catch(err => {
        showToast('حدث خطأ', 'error');
    });
}

// Add All to Cart
function addAllToCart() {
    const productIds = <?php echo json_encode(array_column($wishlist_items, 'product_id')); ?>;
    
    if (productIds.length === 0) return;
    
    let completed = 0;
    productIds.forEach(id => {
        addToCart(id);
        completed++;
        if (completed === productIds.length) {
            setTimeout(() => {
                showToast('تم إضافة جميع المنتجات للسلة', 'success');
            }, 500);
        }
    });
}

// Clear Wishlist
function clearWishlist() {
    if (!confirm('هل تريد مسح جميع المنتجات من المفضلة؟')) return;
    
    const productIds = <?php echo json_encode(array_column($wishlist_items, 'product_id')); ?>;
    
    productIds.forEach(id => {
        removeFromWishlist(id);
    });
}

// Toggle Wishlist
function toggleWishlist(productId) {
    fetch('../api/wishlist/toggle.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'product_id=' + productId
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showToast(data.in_wishlist ? 'تم الإضافة للمفضلة' : 'تم الحذف من المفضلة', 'success');
            // Update wishlist badge
            document.getElementById('wishlistBadge').textContent = data.wishlist_count;
        }
    })
    .catch(err => {
        showToast('حدث خطأ', 'error');
    });
}
</script>

<?php include '../includes/unified-footer.php'; ?>
