<?php
/**
 * Shop Catalog Page
 * Converted from shop-catalog-electronics.html
 * Displays products with filters and pagination
 */

$pageTitle = 'Cartzilla | Magazin Electronice - Catalog';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/product-card-helper.php';

// Initialize classes
$product = new Product();
$user = new User();

// Get filters from URL
$categorySlug = $_GET['category_slug'] ?? null;
$categoryId = null;
$category = null; // Initialize category variable
$search = $_GET['search'] ?? null;
$minPrice = $_GET['min_price'] ?? null;
$maxPrice = $_GET['max_price'] ?? null;
$orderBy = $_GET['order_by'] ?? 'created_at';
$orderDir = $_GET['order_dir'] ?? 'DESC';
$page = max(1, intval($_GET['page'] ?? 1));

// Get category ID if slug is provided
if ($categorySlug) {
    $category = $product->getCategoryBySlug($categorySlug);
    if ($category) {
        $categoryId = $category['id'];
    }
}

// Get user B2B group for pricing
$userId = $auth->getUserId();
$b2bGroup = $userId ? $user->getB2BGroup($userId) : null;

// Build filters
$filters = [
    'category_id' => $categoryId,
    'search' => $search,
    'min_price' => $minPrice,
    'max_price' => $maxPrice,
    'order_by' => $orderBy,
    'order_dir' => $orderDir,
    'page' => $page,
    'per_page' => PRODUCTS_PER_PAGE
];

// Get products
$products = $product->getProducts($filters);
$totalProducts = $product->getProductsCount($filters);
$totalPages = ceil($totalProducts / PRODUCTS_PER_PAGE);

// Get categories for sidebar
$categories = $product->getCategories();
?>

    <!-- Page content -->
    <main class="content-wrapper">

      <!-- Breadcrumb -->
      <nav class="container pt-3 my-3 my-md-4" aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/">Acasă</a></li>
          <li class="breadcrumb-item active" aria-current="page">Catalog<?php echo $category ? ' - ' . htmlspecialchars($category['name']) : ''; ?></li>
        </ol>
      </nav>


      <!-- Page title -->
      <h1 class="h3 container mb-4">Catalog produse</h1>


      <!-- Banners that are turned into collaspse on screens < 768px wide (sm breakpoint) -->
      <section class="accordion container pb-4 pb-md-5 mb-xl-3">
        <div class="accordion-item border-0">
          <div class="accordion-header d-md-none" id="offersHeading">
            <button type="button" class="accordion-button w-auto fw-medium collapsed border border-dashed border-danger border-opacity-50 rounded py-2 px-3" data-bs-toggle="collapse" data-bs-target="#offers" aria-expanded="false" aria-controls="offers">
              <span class="d-inline-flex ci-percent fs-lg text-danger rounded-circle me-2"></span>
              <span class="me-2">Vezi ofertele</span>
            </button>
          </div>
          <div class="accordion-collapse collapse d-md-block" id="offers" aria-labelledby="offersHeading">
            <div class="row g-3 g-lg-4 pt-3 pt-md-0">
              <div class="col-md-7">
                <div class="position-relative d-flex flex-column flex-sm-row align-items-center h-100 rounded-5 overflow-hidden px-5 px-sm-0 pe-sm-4">
                  <span class="position-absolute top-0 start-0 w-100 h-100 d-none-dark rtl-flip" style="background: linear-gradient(90deg, #accbee 0%, #e7f0fd 100%)"></span>
                  <span class="position-absolute top-0 start-0 w-100 h-100 d-none d-block-dark rtl-flip" style="background: linear-gradient(90deg, #1b273a 0%, #1f2632 100%)"></span>
                  <div class="position-relative z-1 text-center text-sm-start pt-4 pt-sm-0 ps-xl-4 mt-2 mt-sm-0 order-sm-2">
                    <h2 class="h3 mb-2">iPhone 14</h2>
                    <p class="fs-sm text-light-emphasis mb-sm-4">Apple iPhone 14 128GB Blue</p>
                    <a class="btn btn-primary" href="/produs/iphone-14">
                      From 899 RON
                      <i class="ci-arrow-up-right fs-base ms-1 me-n1"></i>
                    </a>
                  </div>
                  <div class="position-relative z-1 w-100 align-self-end order-sm-1" style="max-width: 416px">
                    <div class="ratio rtl-flip" style="--cz-aspect-ratio: calc(320 / 416 * 100%)">
                      <img src="assets/img/shop/electronics/banners/iphone-1.png" alt="iPhone 14">
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-5">
                <div class="position-relative d-flex flex-column align-items-center justify-content-between h-100 rounded-5 overflow-hidden pt-3">
                  <span class="position-absolute top-0 start-0 w-100 h-100 d-none-dark rtl-flip" style="background: linear-gradient(90deg, #fdcbf1 0%, #fdcbf1 1%, #ffecfa 100%)"></span>
                  <span class="position-absolute top-0 start-0 w-100 h-100 d-none d-block-dark rtl-flip" style="background: linear-gradient(90deg, #362131 0%, #322730 100%)"></span>
                  <div class="position-relative z-1 text-center pt-3 mx-4">
                    <i class="ci-apple text-body-emphasis fs-3 mb-3"></i>
                    <p class="fs-sm text-light-emphasis mb-1">Deal of the week</p>
                    <h2 class="h3 mb-4">iPad Pro M1</h2>
                  </div>
                  <a class="position-relative z-1 d-block w-100" href="/catalog">
                    <div class="ratio" style="--cz-aspect-ratio: calc(159 / 525 * 100%)">
                      <img src="assets/img/shop/electronics/banners/ipad.png" width="525" alt="iPad">
                    </div>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>


      <!-- Selected filters + Sorting -->
      <section class="container mb-4">
        <div class="row">
          <div class="col-lg-9">
            <div class="d-md-flex align-items-start">
                  <div class="h6 fs-sm fw-normal text-nowrap translate-middle-y mt-3 mb-0 me-4">Găsite <span class="fw-semibold"><?php echo $totalProducts; ?></span> produse</div>
              <?php if ($search || $categoryId || $minPrice || $maxPrice): ?>
              <div class="d-flex flex-wrap gap-2">
                <?php if ($search): ?>
                <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='?<?php echo http_build_query(array_filter(['category_id' => $categoryId, 'min_price' => $minPrice, 'max_price' => $maxPrice, 'order_by' => $orderBy, 'order_dir' => $orderDir])); ?>'">
                  <i class="ci-close fs-sm ms-n1 me-1"></i>
                  Căutare: <?php echo htmlspecialchars($search); ?>
                </button>
                <?php endif; ?>
                <?php if ($categoryId): ?>
                <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='?<?php echo http_build_query(array_filter(['search' => $search, 'min_price' => $minPrice, 'max_price' => $maxPrice, 'order_by' => $orderBy, 'order_dir' => $orderDir])); ?>'">
                  <i class="ci-close fs-sm ms-n1 me-1"></i>
                  Categorie
                </button>
                <?php endif; ?>
                <?php if ($minPrice || $maxPrice): ?>
                <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='?<?php echo http_build_query(array_filter(['search' => $search, 'category_id' => $categoryId, 'order_by' => $orderBy, 'order_dir' => $orderDir])); ?>'">
                  <i class="ci-close fs-sm ms-n1 me-1"></i>
                  Preț: <?php echo $minPrice ? number_format($minPrice, 0) : '0'; ?> - <?php echo $maxPrice ? number_format($maxPrice, 0) : '∞'; ?> RON
                </button>
                <?php endif; ?>
                <button type="button" class="btn btn-sm btn-secondary bg-transparent border-0 text-decoration-underline px-0 ms-2" onclick="window.location.href='/catalog'">
                  Șterge toate
                </button>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <div class="col-lg-3 mt-3 mt-lg-0">
            <div class="d-flex align-items-center justify-content-lg-end text-nowrap">
                  <label class="form-label fw-semibold mb-0 me-2">Sortează după:</label>
              <div style="width: 190px">
                <select class="form-select border-0 rounded-0 px-1" onchange="handleSortChange(this.value)">
                  <option value="created_at:DESC" <?php echo ($orderBy == 'created_at' && $orderDir == 'DESC') ? 'selected' : ''; ?>>Cele mai noi</option>
                  <option value="price:ASC" <?php echo ($orderBy == 'price' && $orderDir == 'ASC') ? 'selected' : ''; ?>>Preț: Crescător</option>
                  <option value="price:DESC" <?php echo ($orderBy == 'price' && $orderDir == 'DESC') ? 'selected' : ''; ?>>Preț: Descrescător</option>
                  <option value="name:ASC" <?php echo ($orderBy == 'name' && $orderDir == 'ASC') ? 'selected' : ''; ?>>Nume: A-Z</option>
                </select>
              </div>
            </div>
          </div>
        </div>
        <hr class="d-lg-none my-3">
      </section>


      <!-- Products grid + Sidebar with filters -->
      <section class="container pb-5 mb-sm-2 mb-md-3 mb-lg-4 mb-xl-5">
        <div class="row">

          <!-- Filter sidebar that turns into offcanvas on screens < 992px wide (lg breakpoint) -->
          <aside class="col-lg-3">
            <div class="offcanvas-lg offcanvas-start" id="filterSidebar">
              <div class="offcanvas-header py-3">
                <h5 class="offcanvas-title">Filter and sort</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" data-bs-target="#filterSidebar" aria-label="Close"></button>
              </div>
              <div class="offcanvas-body flex-column pt-2 py-lg-0">

                <!-- Categories -->
                <div class="w-100 border rounded p-3 p-xl-4 mb-3 mb-xl-4">
                  <h4 class="h6 mb-2">Categories</h4>
                  <ul class="list-unstyled d-block m-0">
                    <li class="nav d-block pt-2 mt-1">
                      <a class="nav-link animate-underline fw-normal p-0 <?php echo !$categoryId ? 'active' : ''; ?>" href="/catalog">
                        <span class="animate-target text-truncate me-3">Toate categoriile</span>
                      </a>
                    </li>
                    <?php foreach ($categories as $cat): ?>
                    <li class="nav d-block pt-2 mt-1">
                      <a class="nav-link animate-underline fw-normal p-0 <?php echo ($categoryId == $cat['id']) ? 'active' : ''; ?>" href="/catalog/<?php echo htmlspecialchars($cat['slug']); ?>">
                        <span class="animate-target text-truncate me-3"><?php echo htmlspecialchars($cat['name']); ?></span>
                      </a>
                    </li>
                    <?php endforeach; ?>
                  </ul>
                </div>

                    <!-- Price range -->
                    <div class="w-100 border rounded p-3 p-xl-4 mb-3 mb-xl-4">
                      <h4 class="h6 mb-2" id="slider-label">Preț</h4>
                  <form method="GET" action="/catalog">
                    <?php if ($categorySlug): ?>
                    <input type="hidden" name="category_slug" value="<?php echo htmlspecialchars($categorySlug); ?>">
                    <?php endif; ?>
                    <?php if ($search): ?>
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                    <?php endif; ?>
                    <div class="d-flex align-items-center">
                      <div class="position-relative w-50">
                        <i class="ci-dollar-sign position-absolute top-50 start-0 translate-middle-y ms-3"></i>
                        <input type="number" name="min_price" class="form-control form-icon-start" min="0" placeholder="Min" value="<?php echo htmlspecialchars($minPrice ?? ''); ?>">
                      </div>
                      <i class="ci-minus text-body-emphasis mx-2"></i>
                      <div class="position-relative w-50">
                        <i class="ci-dollar-sign position-absolute top-50 start-0 translate-middle-y ms-3"></i>
                        <input type="number" name="max_price" class="form-control form-icon-start" min="0" placeholder="Max" value="<?php echo htmlspecialchars($maxPrice ?? ''); ?>">
                      </div>
                    </div>
                    <button type="submit" class="btn btn-sm btn-primary mt-2 w-100">Apply</button>
                  </form>
                </div>

              </div>
            </div>
          </aside>


          <!-- Product grid -->
          <div class="col-lg-9">
            <div class="row row-cols-2 row-cols-md-3 g-4 pb-3 mb-3">

              <?php if (empty($products)): ?>
              <div class="col-12">
                <div class="text-center py-5">
                  <p class="fs-lg text-body-secondary">No products found.</p>
                  <a href="/catalog" class="btn btn-primary">View All Products</a>
                </div>
              </div>
              <?php else: ?>
              <?php foreach ($products as $prod): ?>
              <?php echo renderProductCard($prod, $b2bGroup); ?>
              <?php endforeach; ?>
              <?php endif; ?>

            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <nav class="border-top mt-4 pt-3" aria-label="Catalog pagination">
              <ul class="pagination pagination-lg pt-2 pt-md-3">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?> me-auto">
                  <a class="page-link d-flex align-items-center h-100 fs-lg px-2" href="?<?php echo http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)])); ?>" aria-label="Previous page">
                    <i class="ci-chevron-left mx-1"></i>
                  </a>
                </li>
                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);
                for ($i = $startPage; $i <= $endPage; $i++):
                ?>
                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>" <?php echo $i == $page ? 'aria-current="page"' : ''; ?>>
                  <?php if ($i == $page): ?>
                  <span class="page-link">
                    <?php echo $i; ?>
                    <span class="visually-hidden">(current)</span>
                  </span>
                  <?php else: ?>
                  <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                  <?php endif; ?>
                </li>
                <?php endfor; ?>
                <?php if ($endPage < $totalPages): ?>
                <li class="page-item">
                  <span class="page-link pe-none">...</span>
                </li>
                <li class="page-item">
                  <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $totalPages])); ?>"><?php echo $totalPages; ?></a>
                </li>
                <?php endif; ?>
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?> ms-auto">
                  <a class="page-link d-flex align-items-center h-100 fs-lg px-2" href="?<?php echo http_build_query(array_merge($_GET, ['page' => min($totalPages, $page + 1)])); ?>" aria-label="Next page">
                    <i class="ci-chevron-right mx-1"></i>
                  </a>
                </li>
              </ul>
            </nav>
            <?php endif; ?>
          </div>
        </div>
      </section>

    </main>

<script>
function handleSortChange(value) {
    const [orderBy, orderDir] = value.split(':');
    const url = new URL(window.location.href);
    url.searchParams.set('order_by', orderBy);
    url.searchParams.set('order_dir', orderDir);
    url.searchParams.set('page', '1');
    window.location.href = url.toString();
}

// Add to cart functionality
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.add-to-cart').forEach(btn => {
        btn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            fetch('/api/cart.php?action=add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({product_id: productId, quantity: 1})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    // Show success message or update cart badge
                    location.reload();
                }
            });
        });
    });
    
    // Add to wishlist functionality
    document.querySelectorAll('.add-to-wishlist').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.getAttribute('data-product-id');
            fetch('/api/wishlist.php?action=add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({product_id: productId})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    alert('Product added to wishlist!');
                } else {
                    alert(data.message || 'Please login to add to wishlist');
                }
            });
        });
    });
});
</script>

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

