<?php
include("include/header.php");

// default page title
$aluminium = $aluminium ?? ['title' => 'Home Decor - UPVC & Window Related'];

// helper: slugify (you already have it)
function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    return $text ?: 'n-a';
}

// canonical list of sections -> titles
$sections = [
    'kitchen-wardrobe' => 'Kitchen Wardrobe & TV Cabinet',
    'residential-doors' => 'Residential & Commercial Doors',
    'home-automation'  => 'Home Automation',
    // add other mappings as needed
];

// read incoming slug param (use GET or determine from route)
$sectionSlug = isset($_GET['section']) ? preg_replace('/[^a-z0-9\-]/', '', strtolower($_GET['section'])) : '';

// override title if slug matches
if ($sectionSlug && array_key_exists($sectionSlug, $sections)) {
    $aluminium['title'] = $sections[$sectionSlug];
}


// Static dataset: 6 products per category (replace with DB rows later)    assets\img\property-details\property-details_gal_1.jpg
$categories = [
    'Kitchen Wardrobe & TV Cabinet' => [
        'subcats' => ['UPVC Window Frames','Sliding UPVC Wardrobe','Corner TV Unit'],
        'products' => [
            ['title'=>'UPVC Sliding Wardrobe','desc'=>'Elegant UPVC sliding wardrobe—durable, low-maintenance finish.','img'=>'assets/img/property-details/property-details_gal_1.jpg'],
            ['title'=>'Modular TV Cabinet','desc'=>'Sleek modular TV cabinet, designed for modern living rooms.','img'=>'assets/img/property-details/property-details_gal_2.jpg'],
            ['title'=>'Corner Storage Unit','desc'=>'Space-saving corner storage with UPVC panels and soft-close drawers.','img'=>'assets/img/property-details/property-details_gal_3.jpg'],
            ['title'=>'Glass Front Kitchen Cabinet','desc'=>'Glass-front cabinet with UPVC frame for a premium look.','img'=>'assets/img/property-details/property-details_gal_4.jpg'],
            ['title'=>'UPVC Profile Handle','desc'=>'Durable profile handles made for UPVC wardrobe doors.','img'=>'assets/img/property-details/property-details_gal_5.jpg'],
            ['title'=>'Sliding Track System','desc'=>'Smooth, silent sliding track engineered for heavy-duty use.','img'=>'assets/img/property-details/property-details_gal_6.jpg'],
        ],
    ],
    'Residential & Commercial Doors' => [
        'subcats' => ['uPVC Entrance Doors','Glass UPVC Doors','Door Locks & Handles'],
        'products' => [
            ['title'=>'UPVC Front Door','desc'=>'Robust UPVC front door with thermal insulation properties.','img'=>'assets/img/property-details/property-details_gal_1.jpg'],
            ['title'=>'Glass Door with Frame','desc'=>'Modern glass door paired with a rigid UPVC frame.','img'=>'assets/img/property-details/property-details_gal_2.jpg'],
            ['title'=>'Panel Door Design','desc'=>'Multi-panel UPVC door with excellent sound dampening.','img'=>'assets/img/property-details/property-details_gal_3.jpg'],
            ['title'=>'Sliding Door System','desc'=>'High-performance sliding door system for balconies & offices.','img'=>'assets/img/property-details/property-details_gal_4.jpg'],
            ['title'=>'Door Seal Set','desc'=>'Weather-proof seal set for improved insulation and longevity.','img'=>'assets/img/property-details/property-details_gal_5.jpg'],
            ['title'=>'Commercial Lockset','desc'=>'Heavy-duty lockset compatible with UPVC frames.','img'=>'assets/img/property-details/property-details_gal_6.jpg'],
        ],
    ],
    'Home Automation' => [
        'subcats' => ['Smart Window Actuator','Automatic Door Closer','Sensors'],
        'products' => [
            ['title'=>'Smart Window Actuator','desc'=>'Automate windows for ventilation & remote control.','img'=>'assets/img/property-details/property-details_gal_1.jpg'],
            ['title'=>'Smart Door Lock','desc'=>'Fingerprint / keypad smart lock for UPVC doors.','img'=>'assets/img/property-details/property-details_gal_2.jpg'],
            ['title'=>'Window Motion Sensor','desc'=>'Reliable motion sensor for windows and small openings.','img'=>'assets/img/property-details/property-details_gal_3.jpg'],
            ['title'=>'Voice Control Switch','desc'=>'Voice-enabled switch for lighting and automation.','img'=>'assets/img/property-details/property-details_gal_4.jpg'],
            ['title'=>'Magnetic Window Contact','desc'=>'Security contact for UPVC windows and doors.','img'=>'assets/img/property-details/property-details_gal_5.jpg'],
            ['title'=>'Remote Handle Kit','desc'=>'Remote-activated handle kit for automated access.','img'=>'assets/img/property-details/property-details_gal_6.jpg'],
        ],
    ],
];

$firstCategory = array_key_first($categories);
?>
<style>
/* Layout: 30% sidebar / 70% main */
.page-wrapper {
    padding: 0 18px 60px;
}

.container-flex {
    display: flex;
    gap: 28px;
    align-items: flex-start;
    max-width: 1280px;
    margin: 28px auto;
}

/* sidebar = 30% */
.sidebar {
    width: 30%;
    min-width: 240px;
    background: #fff;
    border-radius: 10px;
    border: 1px solid #ececec;
    padding: 20px;
    box-shadow: 0 6px 18px rgba(12, 31, 52, 0.04);
}

.sidebar h3 {
    margin: 0 0 14px;
    font-size: 18px;
    color: #1f2937;
    font-weight: 700;
}

.accordion-item {
    margin-bottom: 10px;
}

.accordion-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    border-radius: 6px;
    background: #fbfbfb;
    cursor: pointer;
    border: 1px solid #eee;
    font-weight: 600;
    color: #22313a;
}

.accordion-header .caret {
    font-size: 12px;
    color: #6b7280;
}

.accordion-body {
    display: none;
    padding: 10px 8px 0 8px;
}

.product-list {
    list-style: none;
    margin: 0;
    padding: 0;
}

.product-list li {
    padding: 8px 10px;
    border-radius: 6px;
    margin-bottom: 8px;
    background: #fff;
    border: 1px solid #f0f0f0;
    cursor: pointer;
    font-size: 13px;
    color: #334155;
}

.product-list li:hover {
    background: #f6fbfb;
}

.product-list li.active {
    background: #e8f6ff;
    border-color: #cfeef9;
    color: #036b8f;
}

/* main = 70% */
.main-area {
    width: 70%;
}

.section-heading {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 25px;
}

.section-heading h2 {
    margin: 0;
    font-size: 20px;
    color: #0f172a;
    font-weight: 700;
}

.section-sub {
    color: #6b7280;
    font-size: 13px;
    margin-top: 6px;
}

/* Grid: 3 columns, show 6 items (auto-wrap) */
.products-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

.card {
    background: #fff;
    border-radius: 10px;
    border: 1px solid #eee;
    overflow: hidden;
    transition: transform .18s ease, box-shadow .18s ease;
    box-shadow: 0 6px 18px rgba(8, 20, 36, 0.04);
}

.card:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 30px rgba(8, 20, 36, 0.06);
}

.card img {
    width: 100%;
    height: 190px;
    object-fit: cover;
    display: block;
}

.card .info {
    padding: 12px 14px;
    text-align: center;
}

.card .info h4 {
    margin: 6px 0 8px;
    font-size: 15px;
    color: #0f172a;
    font-weight: 600;
}

.card .info p {
    margin: 0;
    font-size: 13px;
    color: #475569;
    line-height: 1.45;
}

/* Responsive */
@media (max-width:1100px) {
    .container-flex {
        gap: 18px;
        padding: 18px;
    }

    .products-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .sidebar {
        width: 32%;
    }

    .main-area {
        width: 68%;
    }
}

@media (max-width:780px) {
    .container-flex {
        flex-direction: column;
        padding: 12px;
    }

    .sidebar {
        width: 100%;
        order: 2;
    }

    .main-area {
        width: 100%;
        order: 1;
    }

    .products-grid {
        grid-template-columns: repeat(1, 1fr);
    }
}
</style>

<div class="breadcumb-wrapper" data-bg-src="<?php echo path() ?>/assets/img/hero/banner1.webp">
    <div class="container">
        <div class="breadcumb-content">
            <h1 class="breadcumb-title" id="<?php echo slugify($aluminium['title']); ?>">
                <?php echo htmlspecialchars($aluminium['title']); ?>
            </h1>
            <ul class="breadcumb-menu">
                <li><a href="<?php echo path() ?>/index.php">Home</a></li>
                <li><?php echo htmlspecialchars($aluminium['title']); ?></li>
            </ul>
        </div>
    </div>
</div>


<div class="page-wrapper">
    <div class="container-flex">
        <!-- LEFT: Sidebar (30%) -->
        <aside class="sidebar" id="sidebar">
            <h3>All Category</h3>

            <?php foreach ($categories as $catName => $data):
                $catSlug = slugify($catName);
            ?>
            <div class="accordion-item">
                <div class="accordion-header" role="button" aria-expanded="false"
                    data-cat="<?php echo htmlspecialchars($catSlug); ?>"
                    onclick="toggleAccordion('<?php echo htmlspecialchars($catSlug); ?>')">
                    <span><?php echo htmlspecialchars($catName); ?></span>
                    <span class="caret">&#9662;</span>
                </div>

                <div class="accordion-body" id="body-<?php echo htmlspecialchars($catSlug); ?>">
                    <ul class="product-list" id="list-<?php echo htmlspecialchars($catSlug); ?>">
                        <?php foreach ($data['products'] as $idx => $prod): ?>
                        <li data-idx="<?php echo $idx; ?>"
                            onclick="showCategory('<?php echo htmlspecialchars($catSlug); ?>', <?php echo $idx; ?>, this)">
                            <?php echo htmlspecialchars($prod['title']); ?>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
            <?php endforeach; ?>
        </aside>

        <!-- RIGHT: Main area (70%) -->
        <main class="main-area">
            <div class="section-heading">
                <div>
                    <h2 id="currentCategoryTitle"><?php echo htmlspecialchars($firstCategory); ?></h2>
                    <!-- <div class="section-sub">Showing top 6 items commonly used with UPVC & windows</div> -->
                </div>

                <div>
                    <!-- optional controls (left empty intentionally) -->
                </div>
            </div>

            <div class="products-grid" id="productsGrid">
                <?php
                // Render the firstCategory products (limit 6)
                $initial = $categories[$firstCategory]['products'];
                for ($i = 0; $i < min(6, count($initial)); $i++):
                    $p = $initial[$i];
                ?>
                <div class="card">
                    <img src="<?php echo htmlspecialchars(path() . $p['img']); ?>"
                        alt="<?php echo htmlspecialchars($p['title']); ?>"
                        onerror="this.src='<?php echo htmlspecialchars(path()); ?>/assets/img/placeholder.png'">
                    <div class="info">
                        <h4><?php echo htmlspecialchars($p['title']); ?></h4>
                        <p><?php echo htmlspecialchars($p['desc']); ?></p>
                    </div>
                </div>
                <?php endfor; // initial render ?>
            </div>
        </main>
    </div>
</div>

<script>
/* Mirror categories into JS with safe keys (slugs) */
const categories = <?php
    $js = [];
    foreach ($categories as $k => $v) {
        $slug = slugify($k);
        $js[$slug] = [
            'name' => $k,
            'products' => array_map(function($p){
                return ['title'=>$p['title'],'desc'=>$p['desc'],'img'=>$p['img']];
            }, $v['products'])
        ];
    }
    echo json_encode($js, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
?>;

/* small helper to escape html */
function js_escape() {
    /* placeholder for editor - not called */
}

/* Toggle accordion body open/close */
function toggleAccordion(catSlug) {
    // close all bodies first
    document.querySelectorAll('.accordion-body').forEach(b => b.style.display = 'none');
    document.querySelectorAll('.accordion-header').forEach(h => h.classList.remove('open'));
    const body = document.getElementById('body-' + catSlug);
    const header = document.querySelector('.accordion-header[data-cat="' + catSlug + '"]');
    if (!body) return;
    // toggle
    if (body.style.display === 'block') {
        body.style.display = 'none';
        if (header) header.classList.remove('open');
    } else {
        body.style.display = 'block';
        if (header) header.classList.add('open');
    }
}

/* Show category products (render up to 6 items). productIndex optional */
function showCategory(catSlug, productIndex = 0, clickedLi = null) {
    const cat = categories[catSlug];
    if (!cat) return;
    // Update heading
    document.getElementById('currentCategoryTitle').innerText = cat.name;

    // Mark clicked li active
    document.querySelectorAll('#sidebar .product-list li').forEach(li => li.classList.remove('active'));
    if (clickedLi) clickedLi.classList.add('active');
    else {
        // if no clicked element, mark first li of that list
        const list = document.getElementById('list-' + catSlug);
        if (list && list.children[0]) list.children[0].classList.add('active');
    }

    // Render up to 6 products of this category
    const grid = document.getElementById('productsGrid');
    grid.innerHTML = '';
    const prods = cat.products || [];
    for (let i = 0; i < Math.min(6, prods.length); i++) {
        const p = prods[i];
        const card = document.createElement('div');
        card.className = 'card';

        // Build absolute image path using PHP path()
        const imgSrc = '<?php echo path(); ?>' + p.img;

        card.innerHTML = `
            <img src="${imgSrc}" alt="${escapeHtml(p.title)}" onerror="this.src='<?php echo path(); ?>/assets/img/placeholder.png'">
            <div class="info">
                <h4>${escapeHtml(p.title)}</h4>
                <p>${escapeHtml(p.desc)}</p>
            </div>
        `;
        grid.appendChild(card);
    }

    // Ensure the category's accordion is open
    document.querySelectorAll('.accordion-body').forEach(b => b.style.display = 'none');
    const targetBody = document.getElementById('body-' + catSlug);
    if (targetBody) targetBody.style.display = 'block';
}

/* small HTML escape util */
function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>"']/g, function(m) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        } [m];
    });
}

/* Initialize: open first category and render its products */
document.addEventListener('DOMContentLoaded', function() {
    const firstSlug = Object.keys(categories)[0];
    if (!firstSlug) return;
    // open first accordion
    const firstBody = document.getElementById('body-' + firstSlug);
    if (firstBody) firstBody.style.display = 'block';
    // mark first product li active
    const firstList = document.getElementById('list-' + firstSlug);
    if (firstList && firstList.children[0]) firstList.children[0].classList.add('active');
    // show products
    showCategory(firstSlug, 0, firstList ? firstList.children[0] : null);
});
</script>

<?php include("include/footer.php"); ?>