<?php
// Include the data handler functions
require_once 'functions/data_handler.php';
require_once 'functions/visitor_identification.php';

// Track this visit
trackVisitor();

// Get unique visitor ID for this session
$visitorId = getCurrentVisitorId();

// Load products data using the function
$productsData = getProductsData();
$products = $productsData['products'];
$filters = $productsData['filters'];

// Get filter parameters from the URL
$selectedBrand = $_GET['brand'] ?? '';
$selectedModel = $_GET['model'] ?? '';
$selectedProcessor = $_GET['processor'] ?? '';
$selectedMemory = $_GET['memory'] ?? '';
$selectedCamera = $_GET['camera'] ?? '';
$selectedColor = $_GET['color'] ?? '';
$sortBy = $_GET['sort'] ?? 'name';

// Pagination parameters
$itemsPerPage = 24;
$currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// Filter products
$filteredProducts = $products;
// Updated filtering logic to match the flat structure of the JSON
if ($selectedBrand) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedBrand) {
        return isset($product['brand']) && $product['brand'] === $selectedBrand;
    });
}
if ($selectedModel) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedModel) {
        return isset($product['model']) && $product['model'] === $selectedModel;
    });
}
if ($selectedProcessor) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedProcessor) {
        return isset($product['processor']) && $product['processor'] === $selectedProcessor;
    });
}
if ($selectedMemory) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedMemory) {
        return isset($product['memory']) && $product['memory'] === $selectedMemory;
    });
}
if ($selectedCamera) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedCamera) {
        return isset($product['camera']) && $product['camera'] === $selectedCamera;
    });
}
if ($selectedColor) {
    $filteredProducts = array_filter($filteredProducts, function($product) use ($selectedColor) {
        return isset($product['color']) && $product['color'] === $selectedColor;
    });
}

// Sort products
switch ($sortBy) {
    case 'price_low':
        usort($filteredProducts, function($a, $b) { return $a['price'] <=> $b['price']; });
        break;
    case 'price_high':
        usort($filteredProducts, function($a, $b) { return $b['price'] <=> $a['price']; });
        break;
    case 'rating':
        usort($filteredProducts, function($a, $b) { return $b['rating'] <=> $a['rating']; });
        break;
    default:
        usort($filteredProducts, function($a, $b) { return strcmp($a['name'], $b['name']); });
}

// Pagination calculations
$totalProducts = count($filteredProducts);
$totalPages = ceil($totalProducts / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;

// Get products for the current page
$paginatedProducts = array_slice($filteredProducts, $offset, $itemsPerPage);

$pageTitle = 'iPhone iOS - Flanco';
?>

<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $pageTitle; ?></title>
<style>
/* ---------- Base / Reset ---------- */
*,*::before,*::after{box-sizing:border-box}
html,body{height:100%}
body{
  margin:0;
  font-family: "Segoe UI", Roboto, Arial, sans-serif;
  background:#f5f5f6;
  color:#222;
  -webkit-font-smoothing:antialiased;
  -moz-osx-font-smoothing:grayscale;
  line-height:1.35;
}

/* ---------- Page container ---------- */
.page {
  max-width:1180px;
  margin: 20px auto;
  padding: 0 18px;
}

/* ---------- Breadcrumb ---------- */
.breadcrumb {
  background: #fff;
  padding: 12px 20px;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.breadcrumb a {
  color: #004b9a;
  text-decoration: none;
}

.breadcrumb a:hover {
  text-decoration: underline;
}


/* ---------- Main Layout ---------- */
.container {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 20px;
  align-items: start;
}

/* ---------- Sidebar ---------- */
.sidebar {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  position: sticky;
  top: 20px;
  align-self: start;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border: 1px solid #e5e7eb;
}

.sidebar h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.filter-options {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.filter-option {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
}

.filter-option input[type="checkbox"] {
  accent-color: #004b9a;
}

/* ---------- Selected Filters ---------- */
.selected-filters {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.selected-filters h4 {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.selected-filter-tag {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  background: #004b9a;
  color: #fff;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin: 2px;
}

.selected-filter-remove {
  cursor: pointer;
  font-weight: bold;
}

.clear-all-filters {
  background: #dc2626;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin-top: 8px;
}

/* ---------- Products Section ---------- */
.products-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border: 1px solid #e5e7eb;
}

.products {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  grid-column: 2;
  grid-row: 2;
}

@media (max-width: 1200px) {
  .products {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 900px) {
  .products {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 600px) {
  .products {
    grid-template-columns: 1fr;
  }
}

.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;
  width: 100%;
  max-width: 300px;
  border: 1px solid #e5e7eb;
  min-height: 450px;
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.wishlist-icon {
  position: absolute;
  top: 12px;
  right: 12px;
  background: transparent;
  border: none;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 20px;
  color: #1e3a8a;
  z-index: 2;
  transition: all 0.2s ease;
}

.wishlist-icon:hover {
  color: #dc2626;
  transform: scale(1.1);
}

.card img {
  width: 100%;
  height: 280px;
  object-fit: cover;
  background: #f8f9fa;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.rating {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.stars {
  color: #d1d5db;
  margin-right: 5px;
  font-size: 22px;
}

.review-count {
  color: #6b7280;
  font-size: 12px;
}

.energy-label {
  margin-bottom: 12px;
  display: inline-block;
  width: 50px;
  height: 45px;
  overflow: visible;
}

.energy-label svg {
  width: 50px;
  height: 45px;
  overflow: visible;
}

/* Cart Badge Styling */
.cart-badge {
  background: #dc2626;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
  margin-left: 5px;
  min-width: 18px;
  text-align: center;
  display: inline-block;
}

.card-title {
  font-size: 13px;
  color: #374151;
  font-weight: 400;
  margin-bottom: 12px;
  line-height: 18px;
}

.price {
  font-weight: 700;
  font-size: 18px;
  color: #111827;
  margin-bottom: 8px;
  display: flex;
  align-items: baseline;
}

.price-superscript {
  font-size: 16px;
  vertical-align: super;
  font-weight: normal;
}

.monthly {
  font-size: 11px;
  color: #6b7280;
  margin-bottom: 10px;
}

.monthly-amount {
  color: #dc2626;
  font-weight: 600;
}

.status {
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 12px;
}

.status.preorder {
  color: #7c3aed;
}

.status.out-of-stock {
  color: #ea580c;
}

.status.limited-stock {
  color: #dc2626;
}

.catalog-btn {
  background: #fff;
  color: #dc2626;
  border: 1px solid #dc2626;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 12px;
  width: auto;
  max-width: 80%;
  align-self: flex-start;
  order: 999;
}

.catalog-btn:hover {
  background: #dc2626;
  color: #fff;
}

.add-btn {
  background-color: #fbbf24;
  color: #1e3a8a;
  border: none;
  padding: 12px 16px;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.add-btn:hover {
  background-color: #f59e0b;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
  transform: translateY(-1px);
}

.add-btn::before {
  content: "🛒";
  font-size: 16px;
}

.delivery {
  font-size: 11px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 4px;
  background: #f8f9fa;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 8px 10px;
  margin-top: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.delivery:hover {
  background: #f1f5f9;
  border-color: #d1d5db;
}

.delivery-icon {
  font-size: 14px;
  color: #6b7280;
  background: #e5e7eb;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}

/* ---------- Sort Section ---------- */
.sort-section {
  background: #f8f9fa;
  padding: 12px 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  grid-column: 2 / -1;
  align-self: start;
}

.sort-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-label {
  font-size: 14px;
  color: #6b7280;
}

.sort-select {
  padding: 6px 10px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: #fff;
  font-size: 14px;
  color: #374151;
}

/* ---------- Pagination ---------- */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 30px;
  padding: 20px 0;
}

.page-btn {
  background: #fff;
  border: 1px solid #d1d5db;
  color: #374151;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-btn:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.page-btn.active {
  background: #1e3a8a;
  color: #fff;
  border-color: #1e3a8a;
}

.page-ellipsis {
  padding: 8px 4px;
  color: #6b7280;
  font-size: 14px;
}

/* ---------- Responsive ---------- */
@media (max-width: 900px) {
  .container {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr;
  }
  
  .sidebar {
    display: none;
  }
  
  .products {
    grid-column: 1;
    grid-row: 2;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .sort-section {
    grid-column: 1;
    grid-row: 1;
  }
}

@media (max-width: 600px) {
  .products {
    grid-template-columns: repeat(2, 1fr) !important;
    gap: 6px;
  }
  
  .card {
    min-height: 400px;
    max-width: none;
  }
  
  .card img {
    height: 200px;
  }
  
  .card-content {
    padding: 12px;
  }
  
  .card-title {
    font-size: 12px;
    line-height: 16px;
  }
  
  .price {
  }
  
  .add-btn {
    padding: 10px 12px;
    font-size: 12px;
  }
}

/* Ensure 2 columns on all mobile devices */
@media (max-width: 768px) {
  .products {
    grid-template-columns: repeat(2, 1fr) !important;
    gap: 6px;
  }
}
</style>
</head>
<body>

<?php include 'includes/header.php'; ?>

<div class="page">
  <!-- Breadcrumb -->
  <div class="breadcrumb">
    <a href="/">Home</a> > <a href="/telefoane">Phones</a> > <span>iPhone iOS</span>
  </div>

  <!-- Main Content -->
  <div class="container">
    <!-- Sidebar -->
    <div class="sidebar">
      <div class="selected-filters">
        <h4>Selected Filters</h4>
        <div id="selected-filters-list">
          <?php if ($selectedBrand || $selectedModel || $selectedProcessor || $selectedMemory || $selectedCamera || $selectedColor): ?>
            <?php if ($selectedBrand): ?>
              <span class="selected-filter-tag">
                Brand: <?php echo htmlspecialchars($selectedBrand); ?>
                <span class="selected-filter-remove" onclick="removeFilter('brand')">×</span>
              </span>
            <?php endif; ?>
            <?php if ($selectedModel): ?>
              <span class="selected-filter-tag">
                Model: <?php echo htmlspecialchars($selectedModel); ?>
                <span class="selected-filter-remove" onclick="removeFilter('model')">×</span>
              </span>
            <?php endif; ?>
            <?php if ($selectedProcessor): ?>
              <span class="selected-filter-tag">
                Procesor: <?php echo htmlspecialchars($selectedProcessor); ?>
                <span class="selected-filter-remove" onclick="removeFilter('processor')">×</span>
              </span>
            <?php endif; ?>
            <?php if ($selectedMemory): ?>
              <span class="selected-filter-tag">
                Memorie: <?php echo htmlspecialchars($selectedMemory); ?>
                <span class="selected-filter-remove" onclick="removeFilter('memory')">×</span>
              </span>
            <?php endif; ?>
            <?php if ($selectedCamera): ?>
              <span class="selected-filter-tag">
                Camera: <?php echo htmlspecialchars($selectedCamera); ?>
                <span class="selected-filter-remove" onclick="removeFilter('camera')">×</span>
              </span>
            <?php endif; ?>
            <?php if ($selectedColor): ?>
              <span class="selected-filter-tag">
                Culoare: <?php echo htmlspecialchars($selectedColor); ?>
                <span class="selected-filter-remove" onclick="removeFilter('color')">×</span>
              </span>
            <?php endif; ?>
            <button class="clear-all-filters" onclick="clearAllFilters()">Clear All</button>
          <?php else: ?>
            <span style="color: #666; font-size: 13px;">No filters selected</span>
          <?php endif; ?>
        </div>
      </div>

      <h3>Filters</h3>
      
      <form method="GET" id="filter-form">
        <div class="filter-group">
          <label>Brand</label>
          <div class="filter-options">
            <?php if (isset($filters['brand']) && is_array($filters['brand'])): ?>
                <?php foreach ($filters['brand'] as $brand): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="brand" value="<?php echo htmlspecialchars($brand); ?>" 
                           <?php echo ($selectedBrand === $brand) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($brand); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <div class="filter-group">
          <label>Model</label>
          <div class="filter-options">
            <?php if (isset($filters['model']) && is_array($filters['model'])): ?>
                <?php foreach ($filters['model'] as $model): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="model" value="<?php echo htmlspecialchars($model); ?>" 
                           <?php echo ($selectedModel === $model) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($model); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <div class="filter-group">
          <label>Processor</label>
          <div class="filter-options">
            <?php if (isset($filters['processor']) && is_array($filters['processor'])): ?>
                <?php foreach ($filters['processor'] as $processor): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="processor" value="<?php echo htmlspecialchars($processor); ?>" 
                           <?php echo ($selectedProcessor === $processor) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($processor); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <div class="filter-group">
          <label>Memory</label>
          <div class="filter-options">
            <?php if (isset($filters['memory']) && is_array($filters['memory'])): ?>
                <?php foreach ($filters['memory'] as $memory): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="memory" value="<?php echo htmlspecialchars($memory); ?>" 
                           <?php echo ($selectedMemory === $memory) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($memory); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <div class="filter-group">
          <label>Camera</label>
          <div class="filter-options">
            <?php if (isset($filters['camera']) && is_array($filters['camera'])): ?>
                <?php foreach ($filters['camera'] as $camera): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="camera" value="<?php echo htmlspecialchars($camera); ?>" 
                           <?php echo ($selectedCamera === $camera) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($camera); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>

        <div class="filter-group">
          <label>Color</label>
          <div class="filter-options">
            <?php if (isset($filters['color']) && is_array($filters['color'])): ?>
                <?php foreach ($filters['color'] as $color): ?>
                  <label class="filter-option">
                    <input type="checkbox" name="color" value="<?php echo htmlspecialchars($color); ?>" 
                           <?php echo ($selectedColor === $color) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($color); ?>
                  </label>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </form>
    </div>

    <!-- Products Section -->
    <div class="products-section">
      <!-- Sort Section -->
      <div class="sort-section">
        <div class="sort-container">
          <span class="sort-label">Sort by:</span>
          <select class="sort-select" name="sort" id="sort" onchange="updateSort()">
            <option value="name" <?php echo ($sortBy === 'name') ? 'selected' : ''; ?>>Name</option>
            <option value="price_low" <?php echo ($sortBy === 'price_low') ? 'selected' : ''; ?>>Price: Low to High</option>
            <option value="price_high" <?php echo ($sortBy === 'price_high') ? 'selected' : ''; ?>>Price: High to Low</option>
            <option value="rating" <?php echo ($sortBy === 'rating') ? 'selected' : ''; ?>>Rating</option>
          </select>
        </div>
      </div>

      <!-- Products Grid -->
      <div class="products">
        <?php if (empty($paginatedProducts)): ?>
            <p style="grid-column: 1 / -1; text-align: center; padding: 20px; color: #666;">No products match the filtering criteria.</p>
        <?php else: ?>
            <?php foreach ($paginatedProducts as $product): ?>
              <?php
                // Add fallbacks for missing fields to prevent errors
                $productImage = $product['image'] ?? 'https://via.placeholder.com/280x280.png?text=No+Image';
                // Fix image path if it starts with '../'
                if (strpos($productImage, '../') === 0) {
                    $productImage = 'assets/' . substr($productImage, 3);
                }
                $productName = $product['name'] ?? 'Product Name';
                $productPrice = $product['price'] ?? 0;
                $productMonthlyPrice = $product['monthlyPrice'] ?? $productPrice / 24; // Fallback monthly price
                $productRating = $product['starRating'] ?? 4.5; // Use starRating for stars
                $productEnergyRating = $product['rating'] ?? 'A'; // Use rating for energy label
                $productReviews = $product['reviews'] ?? 0;
                $productEnergyLabel = $product['energyLabel'] ?? 'N/A';
                $productStatus = $product['status'] ?? 'in-stock';
                
                // Map status to expected values
                $statusClass = 'in-stock';
                $statusText = 'In Stock';
                if (strtolower($productStatus) === 'preorder') {
                    $statusClass = 'preorder';
                    $statusText = 'Pre-order';
                } elseif (strtolower($productStatus) === 'out of stock' || strtolower($productStatus) === 'out-of-stock') {
                    $statusClass = 'out-of-stock';
                    $statusText = 'Out of Stock';
                } elseif (strtolower($productStatus) === 'limited') {
                    $statusClass = 'limited-stock';
                    $statusText = 'Limited Stock';
                } elseif (strtolower($productStatus) === 'catalog') {
                    $statusClass = 'catalog';
                    $statusText = 'Catalog Product';
                }
              ?>
              <div class="card" onclick="showProductModal(<?php echo htmlspecialchars(json_encode($product)); ?>)">
                <button class="wishlist-icon">♡</button>
                <img src="<?php echo htmlspecialchars($productImage); ?>" alt="<?php echo htmlspecialchars($productName); ?>">
                <div class="card-content">
                  <div class="rating">
                    <span class="stars"><?php echo str_repeat('★', floor($productRating)); ?><?php echo str_repeat('☆', 5 - floor($productRating)); ?></span>
                    <span class="review-count">(<?php echo $productReviews; ?>)</span>
                  </div>
                  <div class="energy-label">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 283.46 283.46" style="width: 50px; height: 45px; overflow: visible;">
                      <!-- White left section -->
                      <rect x="1" y="60" width="80" height="170" style="fill:#ffffff;stroke:#231f20;stroke-width:0.8;"></rect>
                      <!-- Green right section -->
                      <polygon points="81,60 81,230 400,230 470,145 400,60" style="fill:#50b848;stroke:#231f20;stroke-width:0.8;"></polygon>
                      <!-- Large white A in green section -->
                      <text transform="translate(220 175)" style="isolation:isolate;font-size:116.06939697265625px;fill:#fff;font-family:Calibri-Bold, Calibri;font-weight:700"><?php echo htmlspecialchars($productEnergyRating); ?></text>
                      <!-- Small A in white section -->
                      <text transform="translate(16.58 114.28)" style="isolation:isolate;font-size:58.86238479614258px;fill:#231c1e;font-family:Calibri-Bold, Calibri;font-weight:700;"> A</text>
                      <!-- Arrow in white section -->
                      <line x1="34.46" y1="157.92" x2="34.46" y2="126.26" style="fill:none;stroke:#1c1a00;stroke-linecap:round;stroke-linejoin:round;stroke-width:2.2200000286102295px"></line>
                      <polyline points="42.85 134.49 34.46 126.1 26.04 134.49" style="fill:none;stroke:#1c1a00;stroke-linecap:round;stroke-linejoin:round;stroke-width:2.2200000286102295px"></polyline>
                      <!-- G in white section -->
                      <text transform="translate(18.01 206) scale(0.93 1)" style="isolation:isolate;font-size:58.034698486328125px;font-family:Calibri-Bold, Calibri;font-weight:700"> G</text>
                    </svg>
                  </div>
                  <div class="card-title"><?php echo htmlspecialchars($productName); ?></div>
                  <div class="price"><?php echo number_format($productPrice, 0, ',', '.'); ?>,<span class="price-superscript"><?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?></span> lei</div>
                  <div class="monthly">sau de la <span class="monthly-amount"><?php echo number_format($productMonthlyPrice, 2, ',', '.'); ?></span> RON / lună</div>
                  <?php if ($statusClass === 'preorder'): ?>
                    <div class="status preorder"><?php echo $statusText; ?></div>
                  <?php elseif ($statusClass === 'out-of-stock'): ?>
                    <div class="status out-of-stock"><?php echo $statusText; ?></div>
                  <?php elseif ($statusClass === 'limited-stock'): ?>
                    <div class="status limited-stock"><?php echo $statusText; ?></div>
                  <?php elseif ($statusClass === 'catalog'): ?>
                    <button class="catalog-btn"><?php echo $statusText; ?></button>
                  <?php endif; ?>
                  <?php if ($statusClass !== 'out-of-stock' && $statusClass !== 'catalog'): ?>
                    <button class="add-btn" onclick="event.stopPropagation(); addToCart(<?php echo htmlspecialchars(json_encode($product)); ?>)">Add to Cart</button>
                  <?php endif; ?>
                  <div class="delivery">
                    <span class="delivery-icon">🚚</span>
                    Starting Friday, October 24
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <!-- Pagination -->
      <div class="pagination">
        <?php if ($totalPages > 1): ?>
          <?php if ($currentPage > 1): ?>
            <button class="page-btn" onclick="goToPage(<?php echo $currentPage - 1; ?>)">‹</button>
          <?php endif; ?>
          
          <?php
          $startPage = max(1, $currentPage - 2);
          $endPage = min($totalPages, $currentPage + 2);
          
          if ($startPage > 1): ?>
            <button class="page-btn" onclick="goToPage(1)">1</button>
            <?php if ($startPage > 2): ?>
              <span class="page-ellipsis">...</span>
            <?php endif; ?>
          <?php endif; ?>
          
          <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
            <button class="page-btn <?php echo ($i == $currentPage) ? 'active' : ''; ?>" onclick="goToPage(<?php echo $i; ?>)">
              <?php echo $i; ?>
            </button>
          <?php endfor; ?>
          
          <?php if ($endPage < $totalPages): ?>
            <?php if ($endPage < $totalPages - 1): ?>
              <span class="page-ellipsis">...</span>
            <?php endif; ?>
            <button class="page-btn" onclick="goToPage(<?php echo $totalPages; ?>)"><?php echo $totalPages; ?></button>
          <?php endif; ?>
          
          <?php if ($currentPage < $totalPages): ?>
            <button class="page-btn next" onclick="goToPage(<?php echo $currentPage + 1; ?>)">›</button>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Add to Cart Modal -->
<div class="modal-overlay" id="modalOverlay" style="display: none;">
  <div class="modal">
    <div class="modal-header">
      <span>Product has been added to cart. Good choice!</span>
      <span class="close-btn" onclick="closeModal()">&times;</span>
    </div>
    <div class="product-info">
      <img id="modal-product-image" src="" alt="">
      <div class="details">
        <h4 id="modal-product-name"></h4>
        <div class="price" id="modal-product-price"></div>
      </div>
      <button class="cart-btn" onclick="goToCheckout()">View Cart (<span id="modal-cart-count">0</span> items)</button>
    </div>
    <div class="warranty-section">
      <h5>🛡️ Choose Express Warranty for your comfort</h5>
      <div class="warranty-options">
        <label class="option"><input type="checkbox"> Express <b>679,99 lei</b></label>
        <label class="option"><input type="checkbox"> Express +1 Year <b>739,99 lei</b></label>
        <label class="option selected"><input type="checkbox" checked> Express +2 Years <b>849,99 lei</b></label>
      </div>
      <ul class="features">
        <li>Priority repair within 5 business days</li>
        <li>Pickup at service center and return repaired product by courier</li>
        <li>Replace defective product with a new similar product</li>
      </ul>
      <button class="more-details">More details</button>
    </div>
    <div class="suggested">
      <h4>Frequently bought together</h4>
      <div class="carousel-container">
        <button class="carousel-arrow prev" onclick="prevSlide()">‹</button>
        <div class="products-carousel">
          <div class="product-card">
            <img src="https://picsum.photos/110/110?random=2" alt="">
            <p>Apple Mobile Phone</p>
            <div class="price">4.249,99 lei</div>
            <button>Add</button>
          </div>
          <div class="product-card">
            <img src="https://picsum.photos/110/110?random=3" alt="">
            <p>Apple Mobile Phone</p>
            <div class="price">8.699,99 lei</div>
            <button>Add</button>
          </div>
          <div class="product-card">
            <img src="https://picsum.photos/110/110?random=4" alt="">
            <p>Apple Mobile Phone</p>
            <div class="price">12.549,99 lei</div>
            <button>Add</button>
          </div>
          <div class="product-card">
            <img src="https://picsum.photos/110/110?random=5" alt="">
            <p>Apple Mobile Phone</p>
            <div class="price">5.399,99 lei</div>
            <button>Add</button>
          </div>
        </div>
        <button class="carousel-arrow next" onclick="nextSlide()">›</button>
      </div>
    </div>
  </div>
</div>

<script>
// Filter Management
function updateSort() {
  const sortValue = document.getElementById('sort').value;
  const url = new URL(window.location);
  url.searchParams.set('sort', sortValue);
  url.searchParams.delete('page'); // Reset to page 1 when sorting
  window.location.href = url.toString();
}

// Pagination Management
function goToPage(page) {
  const url = new URL(window.location);
  url.searchParams.set('page', page);
  window.location.href = url.toString();
}

function removeFilter(filterType) {
  const url = new URL(window.location);
  url.searchParams.delete(filterType);
  url.searchParams.delete('page'); // Reset to page 1 when removing filters
  window.location.href = url.toString();
}

function clearAllFilters() {
  const url = new URL(window.location);
  url.search = ''; // Clear all parameters
  window.location.href = url.toString();
}

// Cart Management
let cart = JSON.parse(localStorage.getItem('cart')) || [];

function addToCart(product) {
  // Check if product already exists in cart
  const existingItem = cart.find(item => item.id === product.id);
  
  if (existingItem) {
    // Increase quantity if product already exists
    existingItem.quantity += 1;
  } else {
    // Add new product to cart
    cart.push({
      ...product,
      quantity: 1
    });
  }
  
  // Save cart to localStorage
  localStorage.setItem('cart', JSON.stringify(cart));
  
  // Update cart badge
  updateCartBadge();
  
  // Show success message
  showCartMessage('Product added to cart!');
  
  // Show product modal
  showProductModal(product);
}

function removeFromCart(productId) {
  cart = cart.filter(item => item.id !== productId);
  localStorage.setItem('cart', JSON.stringify(cart));
  updateCartBadge();
}

function updateCartQuantity(productId, quantity) {
  const item = cart.find(item => item.id === productId);
  if (item) {
    if (quantity <= 0) {
      removeFromCart(productId);
    } else {
      item.quantity = quantity;
      localStorage.setItem('cart', JSON.stringify(cart));
      updateCartBadge();
    }
  }
}

function getCartTotal() {
  return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}

function getCartCount() {
  return cart.reduce((total, item) => total + item.quantity, 0);
}

function updateCartBadge() {
  const cartCount = getCartCount();
  const badge = document.querySelector('.cart-badge');
  if (badge) {
    badge.textContent = cartCount;
    badge.style.display = cartCount > 0 ? 'inline' : 'none';
  }
}

function showCartMessage(message) {
  // Create temporary notification
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #4CAF50;
    color: white;
    padding: 12px 20px;
    border-radius: 4px;
    z-index: 10000;
    font-weight: 500;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
  `;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  // Remove after 3 seconds
  setTimeout(() => {
    notification.remove();
  }, 3000);
}

function showProductModal(product) {
  // Show modal
  document.getElementById('modalOverlay').style.display = 'flex';
  
  // Populate modal with product data
  document.getElementById('modal-product-image').src = product.image;
  document.getElementById('modal-product-name').textContent = product.name;
  document.getElementById('modal-product-price').textContent = product.price + ' lei';
  
  // Update cart count in modal
  const cartCount = getCartCount();
  const modalCartCount = document.getElementById('modal-cart-count');
  if (modalCartCount) {
    modalCartCount.textContent = cartCount;
  }
}

function closeModal() {
  document.getElementById('modalOverlay').style.display = 'none';
  document.body.style.overflow = 'auto';
}

function goToCheckout() {
  window.location.href = 'checkout.php';
}

// Close modal when clicking outside
document.addEventListener('click', function(event) {
  if (event.target.id === 'modalOverlay') {
    closeModal();
  }
});

// Close modal with Escape key
document.addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    closeModal();
  }
});

// Initialize cart on page load
document.addEventListener('DOMContentLoaded', function() {
  // Load cart from localStorage
  cart = JSON.parse(localStorage.getItem('cart')) || [];
  
  // Update cart badge
  updateCartBadge();
});

// Global function for header cart link
function goToCheckout() {
  window.location.href = 'checkout.php';
}

// Carousel functionality
let currentSlide = 0;
const totalSlides = 4;
const itemsPerView = 4;

function nextSlide() {
  const carousel = document.querySelector('.products-carousel');
  const maxSlide = totalSlides - itemsPerView;
  
  if (currentSlide < maxSlide) {
    currentSlide++;
    updateCarousel();
  }
}

function prevSlide() {
  if (currentSlide > 0) {
    currentSlide--;
    updateCarousel();
  }
}

function updateCarousel() {
  const carousel = document.querySelector('.products-carousel');
  if (carousel) {
    const itemWidth = 155;
    carousel.style.transform = `translateX(-${currentSlide * itemWidth}px)`;
  }
}
</script>

<style>
/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background: rgba(0,0,0,0.5);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 999;
  animation: fadeIn 0.3s ease;
}

.modal {
  background: #fff;
  width: 90%;
  max-width: 850px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0,0,0,0.25);
  animation: slideUp 0.3s ease;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 25px;
  border-bottom: 1px solid #eee;
  font-size: 18px;
  font-weight: 500;
}

.close-btn {
  font-size: 22px;
  cursor: pointer;
  color: #555;
  transition: 0.2s;
}

.close-btn:hover {
  color: #000;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px 25px;
}

.product-info img {
  width: 80px;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.product-info .details {
  flex: 1;
}

.product-info .details h4 {
  font-size: 15px;
  margin-bottom: 5px;
}

.product-info .details .price {
  color: #d10000;
  font-weight: bold;
  font-size: 18px;
}

.cart-btn {
  background: #ffd200;
  border: none;
  padding: 10px 18px;
  font-weight: bold;
  border-radius: 5px;
  cursor: pointer;
}

.warranty-section {
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  padding: 20px 25px;
}

.warranty-section h5 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #004b9a;
  display: flex;
  align-items: center;
  gap: 6px;
}

.warranty-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.option {
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 10px 15px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: 0.2s;
}

.option:hover {
  border-color: #004b9a;
}

.option.selected {
  border-color: #004b9a;
  background: #eaf3ff;
}

.option input {
  accent-color: #004b9a;
}

.features {
  font-size: 13px;
  color: #333;
  display: grid;
  gap: 6px;
  margin-top: 8px;
}

.features li {
  list-style: none;
  position: relative;
  padding-left: 20px;
}

.features li::before {
  content: "✔";
  position: absolute;
  left: 0;
  color: #004b9a;
  font-size: 14px;
}

.more-details {
  margin-top: 10px;
  background: #001a5b;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.suggested {
  background: #f5f5f5;
  padding: 20px 25px;
}

.suggested h4 {
  font-size: 15px;
  margin-bottom: 15px;
}

.carousel-container {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
}

.carousel-arrow {
  background: #fff;
  border: 1px solid #ddd;
  color: #333;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 2;
}

.carousel-arrow:hover {
  background: #f0f0f0;
  border-color: #999;
  transform: scale(1.05);
}

.products-carousel {
  display: flex;
  gap: 15px;
  overflow: hidden;
  flex: 1;
  scroll-behavior: smooth;
}

.products-carousel .product-card {
  background: #fff;
  border-radius: 8px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
  min-width: 140px;
  flex-shrink: 0;
}

.products-carousel .product-card img {
  width: 100%;
  border-radius: 6px;
  margin-bottom: 8px;
}

.products-carousel .product-card p {
  font-size: 13px;
  min-height: 36px;
}

.products-carousel .product-card .price {
  color: #111;
  font-weight: bold;
  margin: 5px 0;
}

.products-carousel .product-card button {
  border: 1px solid #004b9a;
  color: #004b9a;
  background: none;
  padding: 6px 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: 0.2s;
}

.products-carousel .product-card button:hover {
  background: #004b9a;
  color: white;
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

@keyframes slideUp {
  from {transform: translateY(30px); opacity: 0;}
  to {transform: translateY(0); opacity: 1;}
}
</style>

<span class="flancons free-delivery"></span>

<?php include 'includes/footer.php'; ?>

</body>
</html>
