<?php
include 'db.php';

// Get category and subcategory from URL
$category_id = isset($_GET['sector_id']) ? intval($_GET['sector_id']) : 0;
$subcategory_id = isset($_GET['subsector_id']) ? intval($_GET['subsector_id']) : 0;

// Get category info
$category = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM categories WHERE id = $category_id LIMIT 1"));
$pageTitle = $category ? $category['title'] : 'Products';

// Get subcategory info if viewing products
$subcategory = null;
if ($subcategory_id > 0) {
    $subcategory = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM subcategories WHERE id = $subcategory_id LIMIT 1"));
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Explore products in <?= htmlspecialchars($pageTitle) ?> category.">
  <link rel="icon" type="image/png" sizes="16x16" href="asset/images/mk logo1.png">
  <title><?= htmlspecialchars($subcategory ? $subcategory['title'] : $pageTitle) ?> - MK Trading Company</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/style.css">
  <style>
    /* Make subcategory boxes clickable */
    .product-category-link {
        display: block;
        text-decoration: none;
        color: inherit;
    }
    .product-category:hover {
        cursor: pointer;
        transform: scale(1.02);
        transition: 0.3s;
    }
  </style>
</head>

<body>
<?php include 'nav.php'; ?>

<!-- Page Header -->
<section class="page-header">
    <div class="container">
        <h1><?= htmlspecialchars($subcategory ? $subcategory['title'] : $pageTitle) ?></h1>
        <?php if ($subcategory): ?>
        <p><?= htmlspecialchars($subcategory['description'] ? substr($subcategory['description'], 0, 150) : '') ?></p>
        <?php endif; ?>
    </div>
</section>

<?php if ($subcategory_id == 0): 
    // Show subcategories using the electricals page style
    $stmt = $conn->prepare("
        SELECT s.*, c.title AS category_title 
        FROM subcategories s 
        JOIN categories c ON s.category_id = c.id 
        WHERE c.id = ? 
        ORDER BY s.id ASC
    ");
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0):
?>
<!-- Content Section for Subcategories -->
<section class="content-section" data-sector="<?= htmlspecialchars(strtolower(str_replace(' ', '-', $pageTitle))) ?>">
    <div class="container">
        <h2>Product Categories</h2>
        <div class="product-categories">
            <?php while ($row = $result->fetch_assoc()): ?>
            <a href="products.php?sector_id=<?= $category_id ?>&subsector_id=<?= $row['id'] ?>" class="product-category-link">
                <div class="product-category" data-category="<?= htmlspecialchars($row['title']) ?>" data-sector="<?= htmlspecialchars($pageTitle) ?>">
                    <h4><?= htmlspecialchars($row['title']) ?></h4>

                    <?php if ($row['image'] && file_exists("asset/images/".$row['image'])): ?>
                    <img src="asset/images/<?= htmlspecialchars($row['image']) ?>" alt="<?= htmlspecialchars($row['title']) ?>">
                    <?php endif; ?>

                    <?php if ($row['description']): ?>
                    <ul>
                        <?php
                        $items = preg_split("/[\r\n,]+/", $row['description']);
                        $count = 0;
                        foreach ($items as $item) {
                            if(trim($item) !== '' && $count < 4) {
                                echo '<li>' . htmlspecialchars(trim($item)) . '</li>';
                                $count++;
                            }
                        }
                        ?>
                    </ul>
                    <?php endif; ?>
                </div>
            </a>
            <?php endwhile; ?>
        </div>
    </div>
</section>
<?php else: ?>
    <section class="content-section">
        <div class="container">
            <p style="text-align:center; font-size:1.1rem; color:#555;">No subcategories found.</p>
        </div>
    </section>
<?php endif; ?>

<?php else:
    // Show products using the gallery page style
    $stmt = $conn->prepare("
        SELECT p.*, s.title AS subcategory_title, c.title AS category_title
        FROM products p
        JOIN subcategories s ON p.subcategory_id = s.id
        JOIN categories c ON s.category_id = c.id
        WHERE p.subcategory_id = ?
        ORDER BY p.id ASC
    ");
    $stmt->bind_param("i", $subcategory_id);
    $stmt->execute();
    $products = $stmt->get_result();

    if ($products->num_rows > 0):
?>
<!-- Product Gallery Section -->
<section class="product-gallery-section">
    <div class="container">
        <div class="product-grid">
            <?php while ($product = $products->fetch_assoc()): ?>
            <div class="product-card" 
                 data-product-id="product-<?= $product['id'] ?>" 
                 data-product-title="<?= htmlspecialchars($product['brand'] ?: $product['model_no']) ?>"
                 data-product-brand="<?= htmlspecialchars($product['brand']) ?>"
                 data-product-model="<?= htmlspecialchars($product['model_no']) ?>">
                <div class="product-image">
                    <?php if(!empty($product['image']) && file_exists("asset/images/".$product['image'])): ?>
                        <img src="asset/images/<?= htmlspecialchars($product['image']) ?>" 
                             alt="<?= htmlspecialchars($product['brand'] ?: $product['model_no']) ?>">
                    <?php else: ?>
                        <img src="assets/images/placeholder.jpg" 
                             alt="<?= htmlspecialchars($product['brand'] ?: $product['model_no']) ?>">
                    <?php endif; ?>
                </div>
                <div class="product-info">
                    <!-- <h3 class="product-title"><?= htmlspecialchars($product['brand'] ?: $product['model_no']) ?></h3>
                    <p class="product-type"><?= htmlspecialchars($product['category_title']) ?></p>
                    <p class="product-brand"><?= htmlspecialchars($product['brand']) ?></p> -->
                    <p class="product-model"><?= htmlspecialchars($product['model_no']) ?></p>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <div style="text-align:center; margin-top:3rem;">
            <a href="products.php?sector_id=<?= $category_id ?>" class="btn btn-primary">Back to Categories</a>
        </div>
    </div>
</section>
<?php else: ?>
    <section class="product-gallery-section">
        <div class="container">
            <p style="text-align:center; font-size:1.1rem; color:#555;">No products found in this category.</p>
            <div style="text-align:center; margin-top:2rem;">
                <a href="products.php?sector_id=<?= $category_id ?>" class="btn btn-primary">Back to Categories</a>
            </div>
        </div>
    </section>
<?php endif; ?>
<?php endif; ?>

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