<?php
/**
 * صفحة المنتجات - Roz Skin E-Commerce
 * تصميم مبسط ومتسق مع المتجر
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();
$conn = $db; // للتوافق مع unified-header

// جلب إعدادات الموقع
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('site_name', 'logo_text', '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']);
}

// معالجة البحث والفلترة
$search = $_GET['search'] ?? '';
$category_id = $_GET['category'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 12;
$offset = ($page - 1) * $per_page;

// بناء الاستعلام
$where_conditions = ['1=1']; // عرض جميع المنتجات
$params = [];

if (!empty($search)) {
    $where_conditions[] = "(name LIKE ? OR description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($category_id)) {
    $where_conditions[] = "category_id = ?";
    $params[] = $category_id;
}

$where_clause = implode(' AND ', $where_conditions);

// ترتيب النتائج
$order_by = match($sort) {
    'price_low' => 'price ASC',
    'price_high' => 'price DESC',
    'name' => 'name ASC',
    'oldest' => 'created_at ASC',
    default => 'created_at DESC'
};

// جلب المنتجات
try {
    $query = "SELECT * FROM products WHERE $where_clause ORDER BY $order_by LIMIT $per_page OFFSET $offset";
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // عدد المنتجات الإجمالي للترقيم
    $count_query = "SELECT COUNT(*) FROM products WHERE $where_clause";
    $count_stmt = $db->prepare($count_query);
    $count_stmt->execute($params);
    $total_products = $count_stmt->fetchColumn();
    $total_pages = ceil($total_products / $per_page);
} catch (PDOException $e) {
    $products = [];
    $total_products = 0;
    $total_pages = 0;
}

// جلب الفئات
try {
    $categories_stmt = $db->prepare("
        SELECT c.id, c.name, c.image, c.description, COUNT(p.id) as product_count
        FROM categories c
        LEFT JOIN products p ON c.id = p.category_id
        WHERE c.type = 'product' AND c.is_active = 1
        GROUP BY c.id, c.name, c.image, c.description
        ORDER BY c.name
    ");
    $categories_stmt->execute();
    $categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $categories = [];
}

// جلب المنتجات المفضلة للمستخدم
$wishlist_products = [];
if (isset($_SESSION['user_id'])) {
    try {
        $wishlist_stmt = $db->prepare("SELECT product_id FROM wishlist WHERE user_id = ?");
        $wishlist_stmt->execute([$_SESSION['user_id']]);
        $wishlist_products = $wishlist_stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch(PDOException $e) {
        $wishlist_products = [];
    }
}
?>
<!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">
    
    <style>
        /* Hero Section - تصميم أنيق وجذاب */
        .products-hero {
            position: relative;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 50%, #C73E6B 100%);
            color: white;
            padding: 120px 0 80px;
            text-align: center;
            margin-top: 80px;
            overflow: hidden;
        }
        
        .products-hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                radial-gradient(circle at 20% 50%, rgba(255,255,255,0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 80%, rgba(255,255,255,0.1) 0%, transparent 50%);
            animation: float 20s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-20px); }
        }
        
        .hero-content {
            position: relative;
            z-index: 1;
            max-width: 800px;
            margin: 0 auto;
            padding: 0 var(--space-md);
        }
        
        .hero-badge {
            display: inline-block;
            background: rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
            padding: 8px 20px;
            border-radius: 50px;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: var(--space-lg);
            border: 1px solid rgba(255,255,255,0.3);
        }
        
        .hero-title {
            font-size: clamp(32px, 5vw, 56px);
            font-weight: 700;
            margin-bottom: var(--space-lg);
            line-height: 1.2;
            text-shadow: 0 2px 20px rgba(0,0,0,0.1);
        }
        
        .hero-subtitle {
            font-size: clamp(16px, 2.5vw, 20px);
            opacity: 0.95;
            line-height: 1.6;
            margin-bottom: var(--space-xl);
        }
        
        .hero-features {
            display: flex;
            justify-content: center;
            gap: var(--space-xl);
            flex-wrap: wrap;
            margin-top: var(--space-xl);
        }
        
        .hero-feature {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            font-size: 15px;
            opacity: 0.9;
        }
        
        .hero-feature svg {
            width: 20px;
            height: 20px;
        }
        
        .hero-subtitle {
            font-size: clamp(14px, 2vw, 18px);
            opacity: 0.9;
            max-width: 600px;
            margin: 0 auto;
        }
        
        /* الفلاتر - مبسطة */
        .filters-section {
            background: var(--bg-secondary);
            padding: var(--space-lg) 0;
        }
        
        .filters-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 var(--space-md);
        }
        
        .filters-form {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--space-lg);
            box-shadow: var(--shadow-sm);
            display: flex;
            flex-wrap: wrap;
            gap: var(--space-md);
            align-items: end;
        }
        
        .filter-group {
            flex: 1;
            min-width: 200px;
        }
        
        .filter-label {
            display: block;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: var(--space-xs);
            font-size: 14px;
        }
        
        .filter-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--border-light);
            border-radius: var(--radius-md);
            font-size: 16px;
            transition: border-color 0.2s;
            background: white;
        }
        
        .filter-input:focus {
            outline: none;
            border-color: var(--primary);
        }
        
        .filter-buttons {
            display: flex;
            gap: var(--space-sm);
        }
        
        /* المحتوى الرئيسي */
        .main-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: var(--space-xl) var(--space-md);
        }
        
        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--space-xl);
            flex-wrap: wrap;
            gap: var(--space-md);
        }
        
        .results-info {
            color: var(--text-secondary);
            font-size: 16px;
        }
        
        .results-count {
            font-weight: 700;
            color: var(--primary);
        }
        
        /* شبكة المنتجات - مبسطة */
        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: var(--space-lg);
            margin-bottom: var(--space-2xl);
        }
        
        .product-card {
            background: white;
            border-radius: var(--radius-lg);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid var(--border-light);
        }
        
        .product-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-md);
        }
        
        .product-image {
            width: 100%;
            height: 250px;
            object-fit: cover;
            background: var(--bg-secondary);
        }
        
        .product-info {
            padding: var(--space-md);
        }
        
        .product-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: var(--space-sm);
            line-height: 1.3;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .product-description {
            font-size: 14px;
            color: var(--text-secondary);
            margin-bottom: var(--space-md);
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .product-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: var(--space-sm);
            border-top: 1px solid var(--border-light);
        }
        
        .product-price {
            font-size: 20px;
            font-weight: 700;
            color: var(--primary);
        }
        
        /* زر السلة - في أسفل البطاقة */
        .btn-add-cart {
            width: 48px;
            height: 48px;
            border: none;
            border-radius: 50%;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 4px 12px rgba(229, 115, 147, 0.3);
            flex-shrink: 0;
            position: relative;
        }
        
        .btn-add-cart::before {
            content: '';
            position: absolute;
            inset: -2px;
            border-radius: 50%;
            padding: 2px;
            background: linear-gradient(135deg, #E57393, #D1537A);
            -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor;
            mask-composite: exclude;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .btn-add-cart:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: 0 8px 20px rgba(229, 115, 147, 0.4);
            background: linear-gradient(135deg, #D1537A 0%, #C73E6B 100%);
        }
        
        .btn-add-cart:hover::before {
            opacity: 1;
        }
        
        .btn-add-cart:active {
            transform: translateY(0) scale(0.98);
        }
        
        .btn-add-cart svg {
            width: 22px;
            height: 22px;
            stroke-width: 2.5;
        }
        
        .product-actions {
            display: flex;
            gap: var(--space-xs);
        }
        
        /* زر المفضلة (القلب) - في أعلى الصورة */
        .wishlist-btn {
            position: absolute;
            top: 12px;
            right: 12px;
            width: 44px;
            height: 44px;
            border: none;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            color: #E57393;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            z-index: 2;
        }
        
        .wishlist-btn:hover {
            transform: scale(1.15);
            box-shadow: 0 4px 16px rgba(229, 115, 147, 0.3);
            background: rgba(255, 255, 255, 1);
        }
        
        .wishlist-btn.active {
            background: #E57393;
            color: white;
        }
        
        .wishlist-btn.active svg {
            fill: currentColor;
            animation: heartBeat 0.3s ease;
        }
        
        @keyframes heartBeat {
            0%, 100% { transform: scale(1); }
            25% { transform: scale(1.3); }
            50% { transform: scale(1.1); }
        }
        
        .product-image-wrapper {
            position: relative;
        }
        
        /* الترقيم - مبسط */
        .pagination {
            display: flex;
            justify-content: center;
            gap: var(--space-sm);
            margin: var(--space-2xl) 0;
        }
        
        .page-btn {
            min-width: 44px;
            height: 44px;
            border: 2px solid var(--border-light);
            background: white;
            color: var(--text-primary);
            border-radius: var(--radius-md);
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            font-weight: 500;
        }
        
        .page-btn:hover,
        .page-btn.active {
            border-color: var(--primary);
            background: var(--primary);
            color: white;
        }
        
        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        /* حالة عدم وجود منتجات */
        .no-products {
            text-align: center;
            padding: var(--space-2xl);
            color: var(--text-secondary);
        }
        
        .no-products-icon {
            width: 64px;
            height: 64px;
            margin: 0 auto var(--space-lg);
            opacity: 0.3;
        }
        
        /* Badge Styles */
        .nav-badge {
            position: absolute;
            top: -4px;
            right: -4px;
            background: #E57393;
            color: white;
            font-size: 11px;
            font-weight: 700;
            min-width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 6px;
            box-shadow: 0 2px 8px rgba(229, 115, 147, 0.4);
            animation: badgePop 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        @keyframes badgePop {
            0% { transform: scale(0); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }
        
        /* Hide on mobile */
        .hide-mobile {
            display: inline;
        }
        
        /* الاستجابة للموبايل */
        @media (max-width: 768px) {
            .products-hero {
                padding: 100px 0 60px;
                background-attachment: scroll !important;
            }
            
            .hero-content {
                padding: 0 20px;
            }
            
            .hero-title {
                font-size: 32px !important;
                line-height: 1.3 !important;
            }
            
            .hero-subtitle {
                font-size: 16px !important;
                line-height: 1.6 !important;
            }
            
            .hide-mobile {
                display: none;
            }
            
            .hero-features {
                flex-direction: column;
                gap: var(--space-md);
            }
            
            .hero-feature {
                font-size: 14px !important;
                padding: 10px 16px !important;
            }
            
            .filters-form {
                flex-direction: column;
                align-items: stretch;
                padding: var(--space-md);
            }
            
            .filter-group {
                min-width: auto;
            }
            
            .filter-buttons {
                justify-content: center;
                flex-direction: column;
            }
            
            .filter-buttons .btn-primary,
            .filter-buttons .btn-secondary {
                width: 100%;
            }
            
            .content-header {
                flex-direction: column;
                text-align: center;
            }
            
            .products-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: var(--space-md);
            }
            
            .product-info {
                padding: var(--space-md);
            }
            
            .pagination {
                flex-wrap: wrap;
            }
            
            .nav-search {
                display: none;
            }
        }
        
        @media (max-width: 480px) {
            .products-hero {
                padding: 80px 0 40px;
                margin-top: 70px;
            }
            
            .hero-content {
                padding: 0 16px;
            }
            
            .hero-badge {
                font-size: 12px;
                padding: 6px 14px;
            }
            
            .hero-title {
                font-size: 28px !important;
                margin-bottom: 16px !important;
            }
            
            .hero-subtitle {
                font-size: 15px !important;
                margin-bottom: 24px !important;
            }
            
            .hero-features {
                font-size: 13px;
                gap: 10px;
            }
            
            .hero-feature {
                font-size: 13px !important;
                padding: 8px 14px !important;
            }
            
            .hero-feature svg {
                width: 16px;
                height: 16px;
            }
            
            .filters-section {
                padding: var(--space-md) 0;
            }
            
            .filters-form {
                padding: var(--space-sm);
            }
            
            .products-grid {
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }
            
            .product-card {
                border-radius: var(--radius-md);
            }
            
            .product-image {
                height: 180px;
            }
            
            .product-info {
                padding: 10px;
            }
            
            .product-title {
                font-size: 14px;
                margin-bottom: 6px;
            }
            
            .product-description {
                font-size: 12px;
                margin-bottom: 10px;
            }
            
            .product-price {
                font-size: 16px;
            }
            
            .btn-add-cart {
                width: 40px;
                height: 40px;
            }
            
            .btn-add-cart svg {
                width: 18px;
                height: 18px;
            }
            
            .wishlist-btn {
                width: 32px;
                height: 32px;
                top: 6px;
                right: 6px;
            }
            
            .wishlist-btn svg {
                width: 16px;
                height: 16px;
            }
            
            .nav-icon-btn {
                width: 40px;
                height: 40px;
            }
            
            .nav-icon-btn svg {
                width: 20px;
                height: 20px;
            }
        }
        
        /* RTL Navigation Fix - Override for this page */
        .nav-content {
            flex-direction: row-reverse !important; /* Logo on right */
        }
        
        .nav-actions {
            flex-direction: row-reverse !important; /* Cart first on right */
        }
        
        .nav-badge {
            left: 6px !important; /* Badge on left side */
            right: auto !important;
        }
        
        .search-input {
            padding: 12px 16px 12px 44px !important; /* Icon space on left */
        }
        
        .search-icon {
            left: 16px !important; /* Icon on left */
            right: auto !important;
        }
    </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">
                    <?php echo htmlspecialchars($logo_text); ?>
                </a>

                <!-- Search -->
                <div class="nav-search">
                    <div style="position: relative;">
                        <input type="text" 
                               class="search-input" 
                               placeholder="ابحث عن المنتجات..."
                               id="searchInput"
                               value="<?php echo htmlspecialchars($search); ?>">
                        <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <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">
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <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>
                    <?php else: ?>
                        <button class="nav-icon-btn" onclick="showLoginModal()" title="تسجيل الدخول">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
                                <polyline points="10 17 15 12 10 7"></polyline>
                                <line x1="15" y1="12" x2="3" y2="12"></line>
                            </svg>
                        </button>
                    <?php endif; ?>

                    <!-- زر السلة 🛒 - يظهر أولاً على اليمين -->
                    <button class="nav-icon-btn" onclick="window.location.href='cart.php'" title="السلة 🛒" style="position: relative;">
                        <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>
                        <span class="nav-badge" id="cartBadge" style="display: <?php echo $cart_count > 0 ? 'flex' : 'none'; ?>;"><?php echo $cart_count; ?></span>
                    </button>

                    <!-- زر المفضلة ❤️ - يظهر ثانياً على اليسار -->
                    <button class="nav-icon-btn" onclick="window.location.href='wishlist.php'" title="المفضلة ❤️" style="position: relative;">
                        <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>
                        <span class="nav-badge" id="wishlistBadge" style="display: none;">0</span>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- Stories Section -->
    <?php include '../includes/stories-component.php'; ?>

    <!-- Hero Section with Background Image -->
    <section class="products-hero" style="background-image: linear-gradient(135deg, rgba(229, 115, 147, 0.92) 0%, rgba(209, 83, 122, 0.92) 50%, rgba(199, 62, 107, 0.92) 100%), url('https://images.unsplash.com/photo-1596462502278-27bfdc403348?w=1920&h=600&fit=crop&q=80'); background-size: cover; background-position: center; background-attachment: fixed;">
        <div class="hero-content">
            <div class="hero-badge">✨ منتجات طبيعية 100%</div>
            <h1 class="hero-title" style="color: white; text-shadow: 0 4px 20px rgba(0,0,0,0.3);">اكتشفي مجموعتنا المميزة</h1>
            <p class="hero-subtitle" style="color: white; text-shadow: 0 2px 10px rgba(0,0,0,0.2); font-size: 18px; line-height: 1.8;">
                منتجات عناية فاخرة بالبشرة والجمال، مصنوعة بحب من مكونات طبيعية<br class="hide-mobile">
                لإطلالة مثالية تعكس جمالك الطبيعي
            </p>
            <div class="hero-features">
                <div class="hero-feature" style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 12px 20px; border-radius: 50px; border: 1px solid rgba(255,255,255,0.3);">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                        <polyline points="22 4 12 14.01 9 11.01"></polyline>
                    </svg>
                    <span>جودة مضمونة</span>
                </div>
                <div class="hero-feature" style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 12px 20px; border-radius: 50px; border: 1px solid rgba(255,255,255,0.3);">
                    <svg 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>
                    <span>مناسبة لجميع أنواع البشرة</span>
                </div>
                <div class="hero-feature" style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 12px 20px; border-radius: 50px; border: 1px solid rgba(255,255,255,0.3);">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
                    </svg>
                    <span>آمنة ومختبرة</span>
                </div>
            </div>
        </div>
    </section>

    <!-- Filters Section -->
    <section class="filters-section">
        <div class="filters-container">
            <form method="GET" action="products.php" class="filters-form">
                <div class="filter-group">
                    <label class="filter-label">البحث</label>
                    <input type="text" 
                           name="search" 
                           class="filter-input" 
                           placeholder="ابحث عن منتج..."
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                
                <div class="filter-group">
                    <label class="filter-label">الفئة</label>
                    <select name="category" class="filter-input">
                        <option value="">جميع الفئات</option>
                        <?php foreach($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" 
                                    <?php echo $category_id == $category['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                                (<?php echo $category['product_count']; ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label class="filter-label">ترتيب</label>
                    <select name="sort" class="filter-input">
                        <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>الأحدث</option>
                        <option value="oldest" <?php echo $sort === 'oldest' ? 'selected' : ''; ?>>الأقدم</option>
                        <option value="price_low" <?php echo $sort === 'price_low' ? 'selected' : ''; ?>>السعر: الأقل أولاً</option>
                        <option value="price_high" <?php echo $sort === 'price_high' ? 'selected' : ''; ?>>السعر: الأعلى أولاً</option>
                        <option value="name" <?php echo $sort === 'name' ? 'selected' : ''; ?>>الاسم</option>
                    </select>
                </div>
                
                <div class="filter-buttons">
                    <button type="submit" class="btn-primary">بحث</button>
                    <a href="products.php" class="btn-secondary">إعادة تعيين</a>
                </div>
            </form>
        </div>
    </section>
 
   <!-- عرض المنتجات -->
    <section class="products-section">
        <div class="container-pinterest">
            <!-- عدد النتائج -->
            <div class="content-header">
                <h2 class="section-title">
                    <?php if (!empty($search)): ?>
                        نتائج البحث عن: "<?php echo htmlspecialchars($search); ?>"
                    <?php elseif (!empty($category_id)): ?>
                        <?php 
                        $selected_cat = array_filter($categories, fn($c) => $c['id'] == $category_id);
                        if (!empty($selected_cat)) {
                            $selected_cat = reset($selected_cat);
                            echo htmlspecialchars($selected_cat['name']);
                        }
                        ?>
                    <?php else: ?>
                        جميع المنتجات
                    <?php endif; ?>
                </h2>
                <p class="results-count">
                    <?php echo number_format($total_products); ?> منتج
                </p>
            </div>

            <!-- شبكة المنتجات -->
            <?php if (!empty($products)): ?>
                <div class="products-grid">
                    <?php foreach($products as $product): 
                        // Fix image path
                        if (!empty($product['image'])) {
                            // If path already contains 'uploads/', use as is
                            if (strpos($product['image'], 'uploads/') === 0) {
                                $imageUrl = '../' . htmlspecialchars($product['image']);
                            } else {
                                $imageUrl = '../uploads/products/' . htmlspecialchars($product['image']);
                            }
                        } else {
                            $imageUrl = 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=400&h=500&fit=crop';
                        }
                    ?>
                        <div class="product-card" onclick="window.location.href='product.php?id=<?php echo $product['id']; ?>'">
                            <?php 
                            $hasDiscount = !empty($product['discount_price']) && $product['discount_price'] < $product['price'];
                            if ($hasDiscount):
                                $discountPercent = round((($product['price'] - $product['discount_price']) / $product['price']) * 100);
                            ?>
                                <div style="position: absolute; top: 12px; left: 12px; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); color: white; padding: 6px 12px; border-radius: 20px; font-weight: 700; font-size: 13px; z-index: 2; box-shadow: 0 2px 8px rgba(229, 115, 147, 0.4);">
                                    -<?php echo $discountPercent; ?>%
                                </div>
                            <?php endif; ?>
                            <div class="product-image-wrapper">
                                <img src="<?php echo $imageUrl; ?>" 
                                     alt="<?php echo htmlspecialchars($product['name']); ?>"
                                     class="product-image"
                                     loading="lazy">
                                <div class="product-overlay"></div>
                                <?php $is_in_wishlist = in_array($product['id'], $wishlist_products); ?>
                                <!-- زر المفضلة (القلب) - في أعلى الصورة -->
                                <button class="wishlist-btn <?php echo $is_in_wishlist ? 'active' : ''; ?>" 
                                        onclick="event.stopPropagation(); toggleWishlist(<?php echo $product['id']; ?>, '<?php echo addslashes($product['name']); ?>', this);"
                                        title="<?php echo $is_in_wishlist ? 'إزالة من المفضلة' : 'إضافة للمفضلة'; ?>">
                                    <svg width="22" height="22" viewBox="0 0 24 24" fill="<?php echo $is_in_wishlist ? 'currentColor' : '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>
                            </div>
                            <div class="product-info">
                                <h3 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h3>
                                <?php if (!empty($product['size'])): ?>
                                    <p class="text-xs text-gray-500 mb-1">
                                        <i class="fas fa-ruler-horizontal"></i> <?php echo htmlspecialchars($product['size']); ?>
                                    </p>
                                <?php endif; ?>
                                <p class="product-description">
                                    <?php 
                                    // Use short_description if available, otherwise use description
                                    $desc = !empty($product['short_description']) ? $product['short_description'] : $product['description'];
                                    echo htmlspecialchars(mb_substr($desc, 0, 100)) . (mb_strlen($desc) > 100 ? '...' : ''); 
                                    ?>
                                </p>
                                <div class="product-footer">
                                    <?php 
                                    $hasDiscount = !empty($product['discount_price']) && $product['discount_price'] < $product['price'];
                                    if ($hasDiscount): 
                                    ?>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="product-price" style="text-decoration: line-through; opacity: 0.6; font-size: 14px;">
                                                <?php echo $currency_symbol; ?> <?php echo number_format($product['price'], 0); ?>
                                            </span>
                                            <span class="product-price" style="color: #E57393; font-weight: 700;">
                                                <?php echo $currency_symbol; ?> <?php echo number_format($product['discount_price'], 0); ?>
                                            </span>
                                        </div>
                                    <?php else: ?>
                                        <span class="product-price">
                                            <?php echo $currency_symbol; ?> <?php echo number_format($product['price'], 0); ?>
                                        </span>
                                    <?php endif; ?>
                                    <!-- زر السلة - في أسفل البطاقة -->
                                    <button class="btn-add-cart" 
                                            onclick="event.stopPropagation(); addToCart(<?php echo $product['id']; ?>);"
                                            title="إضافة للسلة">
                                        <svg 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 if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                               class="pagination-btn">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <polyline points="15 18 9 12 15 6"></polyline>
                                </svg>
                            </a>
                        <?php endif; ?>

                        <?php
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        for ($i = $start; $i <= $end; $i++): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
                               class="pagination-btn <?php echo $i === $page ? 'active' : ''; ?>">
                                <?php echo $i; ?>
                            </a>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                               class="pagination-btn">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <polyline points="9 18 15 12 9 6"></polyline>
                                </svg>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

            <?php else: ?>
                <div class="no-products">
                    <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
                        <circle cx="11" cy="11" r="8"></circle>
                        <path d="m21 21-4.35-4.35"></path>
                    </svg>
                    <h3>لا توجد منتجات</h3>
                    <p>
                        <?php if (!empty($search) || !empty($category_id)): ?>
                            لم نجد منتجات تطابق معايير البحث. جرب تغيير الفلاتر.
                        <?php else: ?>
                            لا توجد منتجات متاحة حالياً.
                        <?php endif; ?>
                    </p>
                    <a href="products.php" class="btn-primary">عرض جميع المنتجات</a>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <!-- Toast -->
    <div id="toast" class="toast-notification hidden"></div>

    <script>
        // Toast
        function showToast(message, duration = 3000) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.classList.remove('hidden');
            setTimeout(() => toast.classList.add('hidden'), duration);
        }

        // إضافة للسلة 🛒
        function addToCart(productId, productName) {
            <?php if (!isset($_SESSION['user_id'])): ?>
                showToast('⚠️ يجب تسجيل الدخول أولاً');
                setTimeout(() => window.location.href = 'login.php', 1000);
                return;
            <?php endif; ?>

            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
                    updateCartBadge();
                } else {
                    showToast(data.message || 'حدث خطأ');
                }
            })
            .catch(() => showToast('حدث خطأ، حاول مرة أخرى'));
        }

        // إضافة/إزالة من المفضلة ❤️
        function toggleWishlist(productId, productName, button) {
            <?php if (!isset($_SESSION['user_id'])): ?>
                showToast('⚠️ يجب تسجيل الدخول أولاً');
                setTimeout(() => window.location.href = 'login.php', 1000);
                return;
            <?php endif; ?>

            const isActive = button.classList.contains('active');

            fetch('../api/wishlist/toggle.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'product_id=' + productId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.classList.toggle('active');
                    const icon = button.querySelector('svg path');
                    if (data.in_wishlist) {
                        showToast('❤️ تم إضافة ' + productName + ' إلى المفضلة');
                        icon.setAttribute('fill', 'currentColor');
                        button.setAttribute('title', 'إزالة من المفضلة');
                    } else {
                        showToast('💔 تم إزالة ' + productName + ' من المفضلة');
                        icon.setAttribute('fill', 'none');
                        button.setAttribute('title', 'إضافة للمفضلة');
                    }
                    // Update wishlist badge
                    updateWishlistBadge();
                } else {
                    showToast(data.message || 'حدث خطأ');
                }
            })
            .catch(() => showToast('حدث خطأ، حاول مرة أخرى'));
        }
        
        // Update wishlist badge
        function updateWishlistBadge() {
            fetch('../api/wishlist/count.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const badge = document.getElementById('wishlistBadge');
                        if (badge) {
                            if (data.count > 0) {
                                badge.textContent = data.count;
                                badge.style.display = 'flex';
                            } else {
                                badge.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(err => console.error('Error updating wishlist badge:', err));
        }
        
        // Initialize badges on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateWishlistBadge();
            updateCartBadge();
        });

        // Update cart badge
        function updateCartBadge() {
            fetch('../api/cart/count.php')
                .then(response => response.json())
                .then(data => {
                    const badge = document.getElementById('cartBadge');
                    if (badge) {
                        if (data.count > 0) {
                            badge.textContent = data.count;
                            badge.style.display = 'flex';
                        } else {
                            badge.style.display = 'none';
                        }
                    }
                })
                .catch(err => console.error('Error updating cart badge:', err));
        }

        // Search
        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>

    <script src="assets/js/store.js"></script>
</body>
</html>