<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';

$pageTitle = 'Shop | LOVE-U Essentials';
$pageDescription = 'Shop premium LOVE-U Essentials products with secure checkout, product filters, best sellers, and new arrivals.';

$categorySlug = trim($_GET['category'] ?? '');
$filter = trim($_GET['filter'] ?? '');
$search = trim($_GET['search'] ?? '');
$sort = trim($_GET['sort'] ?? 'latest');

$where = ["p.status = 'active'"];
$params = [];

$currentCategory = null;

if ($categorySlug !== '') {
    $stmt = $pdo->prepare("SELECT id, name, seo_title, seo_description FROM categories WHERE slug = ? AND status = 'active' LIMIT 1");
    $stmt->execute([$categorySlug]);
    $currentCategory = $stmt->fetch();

    if ($currentCategory) {
        $where[] = "p.category_id = ?";
        $params[] = $currentCategory['id'];

        $pageTitle = !empty($currentCategory['seo_title'])
            ? $currentCategory['seo_title']
            : $currentCategory['name'] . ' | LOVE-U Essentials';

        $pageDescription = !empty($currentCategory['seo_description'])
            ? $currentCategory['seo_description']
            : 'Shop ' . $currentCategory['name'] . ' products from LOVE-U Essentials.';
    }
}

if ($filter === 'best-sellers') {
    $where[] = "p.is_best_seller = 1";
    $pageTitle = 'Best Sellers | LOVE-U Essentials';
    $pageDescription = 'Shop the most loved LOVE-U Essentials best-selling products.';
}

if ($filter === 'new-arrivals') {
    $where[] = "p.is_new_arrival = 1";
    $pageTitle = 'New Arrivals | LOVE-U Essentials';
    $pageDescription = 'Discover the latest products from LOVE-U Essentials.';
}

if ($search !== '') {
    $where[] = "(p.product_name LIKE ? OR p.short_description LIKE ? OR p.description LIKE ? OR p.scent_family LIKE ?)";
    $likeSearch = '%' . $search . '%';
    $params[] = $likeSearch;
    $params[] = $likeSearch;
    $params[] = $likeSearch;
    $params[] = $likeSearch;

    $pageTitle = 'Search results for ' . $search . ' | LOVE-U Essentials';
}

$orderBy = "p.id DESC";

if ($sort === 'price-low') {
    $orderBy = "COALESCE(p.sale_price, p.regular_price) ASC";
} elseif ($sort === 'price-high') {
    $orderBy = "COALESCE(p.sale_price, p.regular_price) DESC";
} elseif ($sort === 'name-az') {
    $orderBy = "p.product_name ASC";
} elseif ($sort === 'name-za') {
    $orderBy = "p.product_name DESC";
}

$whereSql = implode(' AND ', $where);

$sql = "
    SELECT p.*, c.name AS category_name,
        (
            SELECT image_path
            FROM product_images
            WHERE product_id = p.id
            ORDER BY is_primary DESC, sort_order ASC, id ASC
            LIMIT 1
        ) AS primary_image
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE {$whereSql}
    ORDER BY {$orderBy}
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();

$categories = $pdo->query("
    SELECT id, name, slug
    FROM categories
    WHERE status = 'active'
    ORDER BY sort_order ASC, name ASC
")->fetchAll();

function shop_url($overrides = [])
{
    $query = array_merge($_GET, $overrides);

    foreach ($query as $key => $value) {
        if ($value === '' || $value === null) {
            unset($query[$key]);
        }
    }

    return BASE_URL . '/public/shop.php' . ($query ? '?' . http_build_query($query) : '');
}

function render_shop_product_card($product)
{
    $price = !empty($product['sale_price'])
        ? (float) $product['sale_price']
        : (float) $product['regular_price'];

    $isAvailable = ($product['stock_status'] ?? '') !== 'out_of_stock';
    ?>
    <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($product['slug']); ?>" class="product-card lue-shop-card">
        <?php if (!empty($product['badge'])): ?>
            <div class="badge"><?= e($product['badge']); ?></div>
        <?php elseif (!empty($product['is_new_arrival'])): ?>
            <div class="badge">New</div>
        <?php endif; ?>

        <div class="product-image lue-shop-card-image">
            <?php if (!empty($product['primary_image'])): ?>
                <img src="<?= e(BASE_URL . '/' . $product['primary_image']); ?>" alt="<?= e($product['product_name']); ?>">
            <?php else: ?>
                <div class="product-placeholder"><?= e($product['product_name']); ?></div>
            <?php endif; ?>
        </div>

        <div class="lue-shop-card-body">
            <div class="lue-shop-card-meta-row">
                <span><?= e($product['category_name'] ?? 'LOVE-U Essentials'); ?></span>

                <?php if ($isAvailable): ?>
                    <span class="lue-stock-dot">In stock</span>
                <?php else: ?>
                    <span class="lue-stock-dot lue-stock-dot-out">Out of stock</span>
                <?php endif; ?>
            </div>

            <h3 class="product-title"><?= e($product['product_name']); ?></h3>

            <?php if (!empty($product['scent_family'])): ?>
                <div class="product-meta"><?= e($product['scent_family']); ?></div>
            <?php endif; ?>

            <div class="lue-shop-card-bottom">
                <div class="product-price">
                    <?php if (!empty($product['sale_price'])): ?>
                        <span class="old-price"><?= e(format_price($product['regular_price'], $product['currency_code'])); ?></span>
                        <span class="sale-price"><?= e(format_price($product['sale_price'], $product['currency_code'])); ?></span>
                    <?php else: ?>
                        <?= e(format_price($price, $product['currency_code'])); ?>
                    <?php endif; ?>
                </div>

                <span class="lue-shop-view">View</span>
            </div>
        </div>
    </a>
    <?php
}

require_once __DIR__ . '/includes/header.php';
?>
<section class="lue-shop-hero">
    <div class="lue-shop-hero-orb"></div>

    <div class="container lue-shop-hero-inner">
        <div>
            <div class="eyebrow">Shop LOVE-U Essentials</div>

            <?php if ($currentCategory): ?>
                <h1><?= e($currentCategory['name']); ?></h1>
                <p>Explore premium products from the <?= e($currentCategory['name']); ?> collection.</p>
            <?php elseif ($filter === 'best-sellers'): ?>
                <h1>Best Sellers</h1>
                <p>Shop the LOVE-U Essentials products customers love most.</p>
            <?php elseif ($filter === 'new-arrivals'): ?>
                <h1>New Arrivals</h1>
                <p>Discover the latest self-care essentials added to the LOVE-U collection.</p>
            <?php elseif ($search !== ''): ?>
                <h1>Search Results</h1>
                <p>Showing results for “<?= e($search); ?>”.</p>
            <?php else: ?>
                <h1>Shop All</h1>
                <p>Discover soft body care, natural deodorants, accessories, and gift-ready essentials.</p>
            <?php endif; ?>
        </div>

        <div class="lue-shop-hero-card">
            <span><?= count($products); ?></span>
            <strong>product<?= count($products) === 1 ? '' : 's'; ?> found</strong>
            <p>Use filters to refine the collection.</p>
        </div>
    </div>
</section>

<section class="lue-shop-page">
    <div class="container">
        <form class="lue-shop-search-panel" method="GET" action="<?= e(BASE_URL); ?>/public/shop.php">
            <?php if ($categorySlug): ?>
                <input type="hidden" name="category" value="<?= e($categorySlug); ?>">
            <?php endif; ?>

            <?php if ($filter): ?>
                <input type="hidden" name="filter" value="<?= e($filter); ?>">
            <?php endif; ?>

            <?php if ($sort && $sort !== 'latest'): ?>
                <input type="hidden" name="sort" value="<?= e($sort); ?>">
            <?php endif; ?>

            <div class="lue-search-input-wrap">
                <span>Search</span>
                <input type="search" name="search" placeholder="Search body butter, deodorant, accessory..." value="<?= e($search); ?>">
            </div>

            <button type="submit">Search Products</button>

            <?php if ($search !== '' || $categorySlug !== '' || $filter !== '' || $sort !== 'latest'): ?>
                <a href="<?= e(BASE_URL); ?>/public/shop.php" class="lue-reset-link">Reset</a>
            <?php endif; ?>
        </form>

        <input type="checkbox" id="shopFilterToggle" class="shop-filter-checkbox">

        <div class="lue-mobile-shop-tools">
            <label for="shopFilterToggle" class="lue-filter-toggle">
                Filters
            </label>

            <form method="GET" class="lue-mobile-sort">
                <?php if ($categorySlug): ?>
                    <input type="hidden" name="category" value="<?= e($categorySlug); ?>">
                <?php endif; ?>

                <?php if ($filter): ?>
                    <input type="hidden" name="filter" value="<?= e($filter); ?>">
                <?php endif; ?>

                <?php if ($search): ?>
                    <input type="hidden" name="search" value="<?= e($search); ?>">
                <?php endif; ?>

                <select name="sort" onchange="this.form.submit()">
                    <option value="latest" <?= $sort === 'latest' ? 'selected' : ''; ?>>Latest</option>
                    <option value="price-low" <?= $sort === 'price-low' ? 'selected' : ''; ?>>Price: Low to High</option>
                    <option value="price-high" <?= $sort === 'price-high' ? 'selected' : ''; ?>>Price: High to Low</option>
                    <option value="name-az" <?= $sort === 'name-az' ? 'selected' : ''; ?>>Name: A to Z</option>
                    <option value="name-za" <?= $sort === 'name-za' ? 'selected' : ''; ?>>Name: Z to A</option>
                </select>
            </form>
        </div>

        <div class="shop-layout lue-shop-layout">
            <aside class="shop-sidebar lue-shop-sidebar">
                <div class="lue-filter-panel-head">
                    <div>
                        <span>Refine</span>
                        <h2>Filters</h2>
                    </div>

                    <label for="shopFilterToggle" class="lue-filter-close">×</label>
                </div>

                <div class="filter-group">
                    <h3>Collections</h3>

                    <a class="filter-link <?= $categorySlug === '' ? 'active' : ''; ?>" href="<?= e(shop_url(['category' => null])); ?>">
                        Shop All
                    </a>

                    <?php foreach ($categories as $category): ?>
                        <a
                            class="filter-link <?= $categorySlug === $category['slug'] ? 'active' : ''; ?>"
                            href="<?= e(shop_url(['category' => $category['slug']])); ?>"
                        >
                            <?= e($category['name']); ?>
                        </a>
                    <?php endforeach; ?>
                </div>

                <div class="filter-group">
                    <h3>Highlights</h3>

                    <a class="filter-link <?= $filter === 'best-sellers' ? 'active' : ''; ?>" href="<?= e(shop_url(['filter' => 'best-sellers'])); ?>">
                        Best Sellers
                    </a>

                    <a class="filter-link <?= $filter === 'new-arrivals' ? 'active' : ''; ?>" href="<?= e(shop_url(['filter' => 'new-arrivals'])); ?>">
                        New Arrivals
                    </a>

                    <?php if ($filter !== ''): ?>
                        <a class="filter-link" href="<?= e(shop_url(['filter' => null])); ?>">
                            Clear Highlight
                        </a>
                    <?php endif; ?>
                </div>

                <div class="filter-group lue-filter-note">
                    <h3>Shopping Note</h3>
                    <p>Choose your preferred collection, search by scent, or sort products by price and name.</p>
                </div>
            </aside>

            <div class="lue-shop-results">
                <div class="shop-topbar lue-shop-topbar">
                    <div>
                        <div class="shop-count">
                            <?= count($products); ?> product<?= count($products) === 1 ? '' : 's'; ?> found
                        </div>

                        <div class="lue-active-filters">
                            <?php if ($categorySlug !== ''): ?>
                                <span>Collection: <?= e($currentCategory['name'] ?? $categorySlug); ?></span>
                            <?php endif; ?>

                            <?php if ($filter === 'best-sellers'): ?>
                                <span>Best Sellers</span>
                            <?php elseif ($filter === 'new-arrivals'): ?>
                                <span>New Arrivals</span>
                            <?php endif; ?>

                            <?php if ($search !== ''): ?>
                                <span>Search: <?= e($search); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <form method="GET" class="shop-controls lue-desktop-sort">
                        <?php if ($categorySlug): ?>
                            <input type="hidden" name="category" value="<?= e($categorySlug); ?>">
                        <?php endif; ?>

                        <?php if ($filter): ?>
                            <input type="hidden" name="filter" value="<?= e($filter); ?>">
                        <?php endif; ?>

                        <?php if ($search): ?>
                            <input type="hidden" name="search" value="<?= e($search); ?>">
                        <?php endif; ?>

                        <label>
                            Sort by
                            <select name="sort" onchange="this.form.submit()">
                                <option value="latest" <?= $sort === 'latest' ? 'selected' : ''; ?>>Latest</option>
                                <option value="price-low" <?= $sort === 'price-low' ? 'selected' : ''; ?>>Price: Low to High</option>
                                <option value="price-high" <?= $sort === 'price-high' ? 'selected' : ''; ?>>Price: High to Low</option>
                                <option value="name-az" <?= $sort === 'name-az' ? 'selected' : ''; ?>>Name: A to Z</option>
                                <option value="name-za" <?= $sort === 'name-za' ? 'selected' : ''; ?>>Name: Z to A</option>
                            </select>
                        </label>
                    </form>
                </div>

                <?php if (!$products): ?>
                    <div class="empty-state lue-shop-empty">
                        <span>No match</span>
                        <h2>No products found</h2>
                        <p>Try changing your search, clearing filters, or browsing the full LOVE-U Essentials collection.</p>
                        <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn">Reset Filters</a>
                    </div>
                <?php else: ?>
                    <div class="product-grid lue-shop-grid">
                        <?php foreach ($products as $index => $product): ?>
                            <div class="reveal-up reveal-delay-<?= e(min($index, 2)); ?>">
                                <?php render_shop_product_card($product); ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>
<?php require_once __DIR__ . '/includes/footer.php'; ?>