<?php
// --- DATABASE INTEGRATION ---
// IMPORTANT: Ensure 'db.php' contains your PDO connection logic.
// NOTE: This script assumes 'db.php' provides a PDO connection object named $pdo.
include "db.php"; 

// Initialize variables for product and error handling
$latest_products = [];
$categories = [];
$products_by_category = []; 
$db_error = false;

// --- STATIC BANNER CONFIGURATION (UPDATED IMAGE URL) ---
$static_banner = [
    'image' => 'https://lalitavarahifoods.com/uploads/Untitled%20design%20%281%29.png', // <-- NEW BANNER URL
    'link' => '#featured-collection' // Link to the latest products section or a promo page
];

// Function to safely execute DB queries
function safeDbQuery($pdo, $sql) {
    try {
        $stmt = $pdo->query($sql);
        return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    } catch (PDOException $e) {
        error_log("Database Error: " . $e->getMessage());
        return [];
    }
}

// Helper function to format raw DB data for the frontend
$formatProduct = function($p) {
    // Attempt to decode JSON data safely
    $price_variants = @json_decode($p['price_variants'], true) ?: [];
    $images = @json_decode($p['images'], true) ?: [];
    
    $base_price = 'N/A';
    // Logic to extract price from the first variant
    if (!empty($price_variants)) {
        $first_size_prices = [];
        // Prioritize '250g' or the first variant group
        if (isset($price_variants['250g'])) {
             $first_size_prices = $price_variants['250g'];
        } elseif (is_array(reset($price_variants)) && !empty(reset($price_variants))) {
            $first_size_prices = reset($price_variants);
        }

        // Extract price from 'with' key in the selected variant
        if (!empty($first_size_prices) && isset($first_size_prices['with'])) {
            $base_price = is_numeric($first_size_prices['with']) 
                        ? $first_size_prices['with'] 
                        : floatval(str_replace(['Rs.', ','], '', $first_size_prices['with']));
        }
    }

    $image_url = (!empty($images) && count($images) > 0) 
                         ? $images[0] 
                         : 'https://placehold.co/600x400/CCCCCC/333333?text=Product+Image';

    return [
        'id' => $p['id'],
        'name' => $p['product_name'],
        'category_id' => $p['category_id'] ?? null, 
        'category' => 'Pickle', 
        'price' => $base_price,
        'image' => $image_url,
        // Truncate description for card view
        'description' => substr($p['description'], 0, 100) . (strlen($p['description']) > 100 ? '...' : ''), 
        // Mock a random rating for display
        'rating' => round(4.0 + (rand(0, 10) / 10), 1) 
    ];
};


// 1. Fetch ALL Product Data with category_id
$all_db_products = safeDbQuery($pdo, "SELECT id, product_name, category_id, description, price_variants, images, created_at FROM products ORDER BY created_at DESC");

$all_products_formatted = array_map($formatProduct, $all_db_products);

// 2. Extract Latest Products (e.g., first 10 for the New Arrivals section)
if (!empty($all_products_formatted)) {
    $latest_products = array_slice($all_products_formatted, 0, 10); // Grab up to 10 latest
} else {
    $db_error = true;
    $fallback_product = ['id' => uniqid(), 'name' => 'Fallback Product', 'price' => 250.00, 'image' => 'https://placehold.co/400x300/475569/ffffff?text=Fallback', 'description' => 'A placeholder item.', 'rating' => 4.5];
    $latest_products = array_fill(0, 8, $fallback_product);
}


// 3. Fetch Category Data 
$categories_data = safeDbQuery($pdo, "SELECT id, category_name AS name, image_path FROM categories ORDER BY category_name ASC");
$categories = [];

foreach ($categories_data as $cat) {

    $raw_img = trim($cat['image_path']);

    // Build full URL for image
    if (!empty($raw_img)) {

        // If image path does NOT already contain http, add domain
        if (strpos($raw_img, 'http') === false) {
            $cat_image = "https://lalitavarahifoods.com/lbfood/uploads/categories/" . $raw_img;
        } else {
            $cat_image = $raw_img;
        }

    } else {
        // Default fallback image
        $cat_image = "https://placehold.co/400x300/475569/ffffff?text=Category";
    }

    $categories[] = [
        'id' => $cat['id'],
        'name' => $cat['name'],
        'link' => 'products.php?cat=' . $cat['id'],
        'image_path' => $cat_image
    ];

    // Initialize products array
    $products_by_category[$cat['id']] = [
        'name'  => $cat['name'],
        'products' => []
    ];
}


// 4. Group Products by Category
foreach ($all_products_formatted as $product) {
    $category_id = $product['category_id'];
    if ($category_id !== null && isset($products_by_category[$category_id])) {
        $products_by_category[$category_id]['products'][] = $product;
    }
}

// Filter out categories that have no products after grouping
$products_by_category = array_filter($products_by_category, function($category) {
    return !empty($category['products']);
});


/**
 * Renders a product list, either as a centered grid or a scrollable slider.
 * @param array $products_to_display The list of products.
 * @param string $container_id A unique ID for the container (needed for scroll functions).
 */
function renderProductList($products_to_display, $container_id) {
    $count = count($products_to_display);
    $is_scrollable = $count > 4;
    $list_class = $is_scrollable ? 'product-scroll-container' : 'product-center-container';

    // Output the container wrapper for alignment/scroll
    echo '<div id="' . $container_id . '" class="relative">';
    
    // Output the scroll left button (only if scrollable)
    if ($is_scrollable) {
        echo '<button onclick="scrollProducts(\'' . $container_id . '\', -280)" class="scroll-button absolute left-0 top-1/2 transform -translate-y-1/2 bg-white bg-opacity-70 text-gray-800 p-2 rounded-full shadow-lg hover:bg-opacity-100 transition z-30 ml-2">';
        echo '<i class="fas fa-chevron-left"></i>';
        echo '</button>';
    }

    // Output the product list container
    echo '<div class="' . $list_class . '">';
    
    if (empty($products_to_display)) {
        echo '<div class="w-full text-center text-gray-500 py-10 border-2 border-dashed border-gray-300 rounded-lg">No products found.</div>';
    } else {
        foreach ($products_to_display as $product) {
            $card_class = $is_scrollable ? 'product-card' : 'product-card-grid';
            ?>
            <div class="bg-white rounded-xl shadow-lg hover:shadow-2xl transition duration-300 overflow-hidden transform hover:-translate-y-1 <?= $card_class ?>">
                <a href="product.php?id=<?= $product['id'] ?>" class="relative block overflow-hidden card-image">
                    <img src="<?= htmlspecialchars($product['image']) ?>" 
                        onerror="this.src='https://placehold.co/400x300/475569/ffffff?text=<?= urlencode($product['name']) ?>'"
                        alt="<?= htmlspecialchars($product['name']) ?>" 
                        class="w-full h-full object-cover"> 
                    <?php if ($container_id === 'latest-products-list'): ?>
                    <span class="absolute top-3 left-3 bg-yellow-500 text-blue-900 text-xs font-bold px-3 py-1 rounded-full shadow-md z-20">
                        NEW
                    </span>
                    <?php endif; ?>
                </a>

                <div class="p-5">
                    <a href="product.php?id=<?= $product['id'] ?>"><h3 class="text-xl font-semibold mb-1 truncate hover:text-blue-600 transition"><?= htmlspecialchars($product['name']) ?></h3></a>
                    <p class="text-gray-500 text-sm mb-3 h-10 overflow-hidden"><?= htmlspecialchars($product['description']) ?></p>
                    <div class="flex justify-between items-center mb-4">
                        <span class="text-2xl font-bold text-blue-900"> 
                            <?php if ($product['price'] !== 'N/A'): ?>
                                Rs. <?= number_format($product['price'], 2) ?>
                            <?php else: ?>
                                Price Varies
                            <?php endif; ?>
                        </span>
                        <div class="flex items-center text-yellow-500">
                            <i class="fas fa-star text-sm"></i>
                            <span class="ml-1 text-sm font-semibold text-gray-700"><?= htmlspecialchars($product['rating']) ?></span>
                        </div>
                    </div>
                    <a href="product.php?id=<?= $product['id'] ?>" class="block w-full text-center py-2 rounded-full font-medium btn-secondary">
                        <i class="fas fa-eye mr-2"></i> View Details
                    </a>
                </div>
            </div>
            <?php
        }
    }

    // Close the product list container
    echo '</div>'; 
    
    // Output the scroll right button (only if scrollable)
    if ($is_scrollable) {
        echo '<button onclick="scrollProducts(\'' . $container_id . '\', 280)" class="scroll-button absolute right-0 top-1/2 transform -translate-y-1/2 bg-white bg-opacity-70 text-gray-800 p-2 rounded-full shadow-lg hover:bg-opacity-100 transition z-30 mr-2">';
        echo '<i class="fas fa-chevron-right"></i>';
        echo '</button>';
    }

    // Close the container wrapper
    echo '</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pickle Store Home - Authentic Indian Pickles</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Define a clean color palette for a professional look */
        :root {
            --primary-color: #004488; 
            --secondary-color: #e27d60; 
            --background-light: #fdfdfd; 
            --section-background: #f0f4f8; 
        }

        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        body {
            font-family: 'Poppins', sans-serif; 
            background-color: var(--background-light); 
        }

        /* --- STATIC BANNER STYLES (MODIFIED FOR FULL-WIDTH AND TALLER HEIGHT) --- */
        .static-banner-container {
            width: 100%;
            overflow: hidden;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            /* Set a fixed height for desktop views */
            height: 400px; 
        }
        .static-banner-container a {
            height: 100%; 
            display: block;
        }
        .static-banner-container img {
            width: 100%;
            height: 100%; /* Image now fills 100% of the container height */
            object-fit: cover; /* Ensures the image covers the area without distortion */
            display: block; 
        }

        /* Media Query for Mobile Height Adjustment */
        @media (max-width: 768px) {
            .static-banner-container {
                height: 200px; /* Shorter height for better mobile viewing */
            }
        }

        /* --- CATEGORY TABS STYLES (Horizontal Scroll) --- */
 /* --- CATEGORY TABS STYLES (Horizontal Scroll) --- */
.category-tabs-container {
    display: flex;
    justify-content: center;     /* <-- Center align horizontally */
    gap: 2rem;
    overflow-x: auto;
    white-space: nowrap;
    -ms-overflow-style: none;
    scrollbar-width: none;
    scroll-behavior: smooth;
    padding: 1rem 0;
}

.category-tabs-container::-webkit-scrollbar {
    display: none;
}

/* Round category image */
.category-tab {
    width: 120px;
    flex-shrink: 0;
    text-align: center;
}

.category-tab .circle {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-size: cover;
    background-position: center;
    margin: 0 auto 10px auto;
    box-shadow: 0 6px 15px rgba(0,0,0,0.15);
    transition: transform 0.3s ease;
}

.category-tab:hover .circle {
    transform: scale(1.05);
}

/* Category Name */
.category-tab .cat-name {
    font-size: 15px;
    font-weight: 600;
    color: #333;
    display: block;
    margin-top: 5px;
}


        /* --- PRODUCT DISPLAY STYLES --- */
        
        /* 1. SCROLLABLE CONTAINER (> 4 products) */
        .product-scroll-container {
            display: flex;
            gap: 1rem; 
            overflow-x: auto;
            padding: 0 40px; 
            padding-bottom: 1rem; 
            -ms-overflow-style: none;
            scrollbar-width: none;
            scroll-behavior: smooth;
        }
        .product-scroll-container::-webkit-scrollbar {
            display: none; 
        }
        .product-scroll-container .product-card {
            min-width: 280px; 
            max-width: 280px;
            flex-shrink: 0;
        }
        
        /* 2. CENTERED CONTAINER (<= 4 products) */
        .product-center-container {
            display: flex;
            flex-wrap: wrap; 
            justify-content: center; 
            gap: 1rem; 
        }
        .product-center-container .product-card-grid {
            width: calc(25% - 0.75rem); 
            min-width: 280px; 
        }
        @media (max-width: 1024px) {
            .product-center-container .product-card-grid {
                width: calc(50% - 0.5rem); 
            }
        }
        @media (max-width: 640px) {
            .product-center-container .product-card-grid {
                width: 100%; 
            }
        }

        /* --- PRODUCT CARD STYLES --- */
        .card-image {
            height: 14rem; 
            overflow: hidden;
            display: flex; 
            justify-content: center;
            align-items: center;
            background-color: #eee; 
            padding: 0; 
        }
        .card-image img {
            width: 100%;
            height: 100%;
            object-fit: cover; 
            transition: transform 0.5s ease;
        }
        .card-image:hover img {
            transform: scale(1.05);
        }

        /* --- SCROLL BUTTONS --- */
        .scroll-button {
            height: 40px;
            width: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
        }
        
        /* --- BUTTON STYLES --- */
        .btn-primary {
            background-color: var(--primary-color);
            border: 2px solid var(--primary-color);
            color: white;
            transition: background-color 0.3s, color 0.3s;
        }
        .btn-primary:hover {
            background-color: white;
            color: var(--primary-color);
        }
        .btn-secondary {
            border: 2px solid var(--primary-color);
            color: var(--primary-color);
            transition: background-color 0.3s, color 0.3s;
        }
        .btn-secondary:hover {
            background-color: var(--primary-color);
            color: white;
        }

    </style>
</head>
<body class="text-gray-800">
<?php include "header.php"; ?>

    <main class="relative"> 
        
        <section class="static-banner-container">
            <a href="<?= htmlspecialchars($static_banner['link']) ?>" class="block">
                <img src="<?= htmlspecialchars($static_banner['image']) ?>" 
                    alt="Featured Promotional Banner" 
                    class="w-full shadow-md rounded-lg">
            </a>
        </section>
        
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> 

            <section class="mb-16">
                <h2 class="text-3xl font-bold text-center mb-8 text-gray-900">
                    Explore Our Range
                </h2>
                
                <div class="category-tabs-container shadow-inner bg-white rounded-xl p-4">
                    
                    <?php if (empty($categories)): ?>
                        <div class="w-full text-center text-gray-500 py-4">
                            No categories found.
                        </div>
                    <?php endif; ?>

                    <?php foreach ($categories as $category): ?>
                       <a href="<?= htmlspecialchars($category['link']) ?>" class="category-tab">
    <div class="circle" style="background-image:url('<?= $category['image_path'] ?>');"></div>
    <span class="cat-name"><?= htmlspecialchars($category['name']) ?></span>
</a>

                    <?php endforeach; ?>

                </div>
            </section>
            
            <hr class="mb-16 border-gray-200">

            <section class="mb-16" id="featured-collection">
                <h2 class="text-3xl font-extrabold text-center mb-10 text-gray-900 relative">
                    ✨ New Arrivals
                </h2>
                
                <?php renderProductList($latest_products, 'latest-products-list'); ?>
                
            </section>
            
            <hr class="mb-16 border-gray-200">
            
            <?php 
            if (!empty($products_by_category)):
                foreach ($products_by_category as $category_id => $category_data):
                    $products_to_display = $category_data['products'];

                    if (empty($products_to_display)) continue;
            ?>
            <section class="mb-16">
                <h2 class="text-3xl font-extrabold text-center mb-10 text-gray-900 relative">
                    <?= htmlspecialchars($category_data['name']) ?>
                </h2>
                
                <?php renderProductList($products_to_display, 'category-' . $category_id . '-list'); ?>
                
            </section>
            
            <hr class="mb-16 border-gray-200">

            <?php
                endforeach;
            endif;
            ?>
        </div> 
    </main>

    <?php 
    // TEMPORARY FOOTER FOR DEMO 
    echo '<footer class="bg-gray-800 text-white mt-10">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-center">
                    <p>&copy; 2025 Pickle Store. All rights reserved.</p>
                </div>
            </footer>';
    ?>

    <script>
        // --- Conditional Product Scroll Logic ---
        /**
         * Scrolls the product container left or right.
         * @param {string} containerId - The ID of the parent container element.
         * @param {number} scrollAmount - The amount of pixels to scroll (e.g., 280 or -280).
         */
        function scrollProducts(containerId, scrollAmount) {
            // Target the actual scrollable div inside the wrapper
            const container = document.querySelector(`#${containerId} .product-scroll-container`);
            if (container) {
                container.scrollBy({
                    left: scrollAmount,
                    behavior: 'smooth'
                });
            }
        }
    </script>

</body>
</html>