
<?php

require_once __DIR__ . "/site_content.php";
$siteContent = loadSiteContent();

/* =========================================================
   DATABASE CONNECTION
========================================================== */

try {
    require_once dirname(__DIR__) . "/app/database.php";
    $pdo = kwithu_database();

} catch (Throwable $e) {

    $pdo = null;
    $products = [];
    $categories = [];

}


/* =========================================================
   CURRENCY SETTINGS
   ---------------------------------------------------------
   Prices can be entered per currency in the admin panel.
   Missing ZAR/USD prices use the conversion rates below.

   Example:
   1 MWK = 0.00052 ZAR
   1 MWK = 0.00058 USD

   These are configurable display rates, not live rates.
========================================================== */

$currencyRates = [

    "MWK" => 1,

    "ZAR" => 0.00052,

    "USD" => 0.00058

];


/* =========================================================
   CURRENCY SYMBOLS
========================================================== */

$currencySymbols = [

    "MWK" => "MK",

    "ZAR" => "R",

    "USD" => "$"

];


/* =========================================================
   FETCH ACTIVE PRODUCTS
========================================================== */

if ($pdo !== null) {

    try {

        $productQuery = $pdo->query("
            SELECT
                id,
                name,
                category,
                collection,
                description,
                price,
                price_zar,
                price_usd,
                image,
                status,
                created_at
            FROM products
            WHERE status = 'active'
            ORDER BY created_at DESC, id DESC
        ");

        $products = $productQuery->fetchAll();

        $additionalImageQuery = $pdo->query("
            SELECT product_id, image
            FROM product_images
            ORDER BY id
        ");
        $additionalImagesByProduct = [];
        foreach ($additionalImageQuery->fetchAll() as $additionalImage) {
            $additionalImagesByProduct[(int)$additionalImage["product_id"]][] =
                $additionalImage["image"];
        }
        foreach ($products as &$product) {
            $product["additional_images"] =
                $additionalImagesByProduct[(int)$product["id"]] ?? [];
        }
        unset($product);


        /* =====================================================
           GET UNIQUE CATEGORIES
        ====================================================== */

        $categoryQuery = $pdo->query("
            SELECT DISTINCT category
            FROM products
            WHERE status = 'active'
              AND category IS NOT NULL
              AND TRIM(category) != ''
            ORDER BY category ASC
        ");

        $categories = $categoryQuery->fetchAll();

    } catch (PDOException $e) {

        $products = [];
        $categories = [];

    }

}


/* =========================================================
   PRODUCT COUNT
========================================================== */

$productCount = count($products);


/* =========================================================
   HELPER FUNCTION
========================================================== */

function e($value)
{
    return htmlspecialchars(
        (string) $value,
        ENT_QUOTES,
        "UTF-8"
    );
}

?>

<!DOCTYPE html>

<html lang="en">

<head>


<!-- =========================================================
     BASIC META
========================================================== -->

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0">

<meta name="theme-color"
      content="#1D1C1A">

<meta name="description"
      content="Explore the Kwithu Furniture collection of handcrafted, contemporary and sustainable furniture made in Malawi. Discover sofas, dining furniture, chairs, tables, bedroom furniture and more.">

<meta name="keywords"
      content="Kwithu Furniture collection, furniture Malawi, sofas Malawi, dining furniture Malawi, chairs Malawi, handcrafted furniture Blantyre, sustainable furniture Malawi, custom furniture">

<meta name="author"
      content="Kwithu Furniture">

<meta name="robots"
      content="index, follow">

<link rel="canonical"
      href="https://kwithumw.com/collection">


<!-- =========================================================
     TITLE
========================================================== -->

<title>Our Collection | Kwithu Furniture Malawi</title>


<!-- =========================================================
     FAVICON
========================================================== -->

<link rel="icon"
      type="image/png"
      href="images/logo.png">


<!-- =========================================================
     GOOGLE FONTS
========================================================== -->

<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=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@500;600;700&display=swap"
      rel="stylesheet">


<!-- =========================================================
     SWIPER
========================================================== -->

<link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css">


<!-- =========================================================
     AOS
========================================================== -->

<link rel="stylesheet"
      href="https://unpkg.com/aos@2.3.1/dist/aos.css">


<!-- =========================================================
     FONT AWESOME
========================================================== -->

<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">


<!-- =========================================================
     MAIN CSS
========================================================== -->

<link rel="stylesheet"
      href="style.css">


</head>


<body>


<!-- =========================================================
     SITE HEADER
========================================================== -->

<header class="site-header"
        id="siteHeader">

    <div class="header-container">


        <!-- LOGO -->

        <a href="index"
           class="brand-logo"
           aria-label="Kwithu Furniture Home">

            <img src="images/logo.png"
                 alt="Kwithu Furniture"
                 loading="eager">

        </a>


        <!-- DESKTOP NAVIGATION -->

        <nav class="main-navigation"
             id="mainNavigation"
             aria-label="Main navigation">


            <a href="index"
               class="nav-link">

                Home

            </a>


            <a href="about"
               class="nav-link">

                Our Story

            </a>


            <a href="collection"
               class="nav-link active"
               aria-current="page">

                Collection

            </a>


            <a href="custom-furniture"
               class="nav-link">

                Custom Furniture

            </a>


            <a href="gallery"
               class="nav-link">

                Gallery

            </a>


            <a href="contact"
               class="nav-link">

                Contact

            </a>

        </nav>


        <!-- HEADER CTA -->

        <a href="contact"
           class="header-cta">

            <span>
                Enquire
            </span>

            <i class="fa-solid fa-arrow-up-right-from-square"></i>

        </a>


        <!-- MOBILE MENU BUTTON -->

        <button class="menu-toggle"
                id="menuToggle"
                type="button"
                aria-label="Open navigation"
                aria-expanded="false"
                aria-controls="mobileMenu">

            <span></span>
            <span></span>

        </button>

    </div>

</header>


<!-- =========================================================
     MOBILE MENU
========================================================== -->

<div class="mobile-menu"
     id="mobileMenu"
     aria-hidden="true">


    <div class="mobile-menu-inner">


        <!-- MOBILE MENU TOP -->

        <div class="mobile-menu-top">

            <span>
                Explore Kwithu
            </span>


            <button class="mobile-menu-close"
                    id="mobileMenuClose"
                    type="button"
                    aria-label="Close navigation">

                <i class="fa-solid fa-xmark"></i>

            </button>

        </div>


        <!-- MOBILE NAVIGATION -->

        <nav class="mobile-navigation"
             aria-label="Mobile navigation">


            <a href="index">

                <span>01</span>

                Home

            </a>


            <a href="about">

                <span>02</span>

                Our Story

            </a>


            <a href="collection"
               class="active">

                <span>03</span>

                Collection

            </a>


            <a href="custom-furniture">

                <span>04</span>

                Custom Furniture

            </a>


            <a href="gallery">

                <span>05</span>

                Gallery

            </a>


            <a href="contact">

                <span>06</span>

                Contact

            </a>

        </nav>


        <!-- MOBILE MENU BOTTOM -->

        <div class="mobile-menu-bottom">

            <p>

                Handcrafted furniture,
                thoughtfully made in Malawi.

            </p>


            <a href="https://wa.me/265990816801"
               target="_blank"
               rel="noopener"
               class="mobile-whatsapp">

                Start a Conversation

                <i class="fa-brands fa-whatsapp"></i>

            </a>

        </div>

    </div>

</div>


<!-- =========================================================
     COLLECTION HERO
========================================================== -->

<section class="collection-hero">


    <div class="collection-hero-background"<?php if ($siteContent["collection_hero_image"] !== ""): ?> style="background-image:url('<?= e($siteContent["collection_hero_image"]) ?>');background-size:cover;background-position:center"<?php endif; ?>></div>


    <div class="collection-hero-overlay"></div>


    <div class="collection-hero-content page-container">


        <div class="section-label light">

            <span class="label-line"></span>

            <?= e($siteContent["collection_hero_label"]) ?>

        </div>


        <h1>

            <?= e($siteContent["collection_hero_title"]) ?>
            <em><?= e($siteContent["collection_hero_emphasis"]) ?></em>

        </h1>


        <p>

            <?= e($siteContent["collection_hero_copy"]) ?>

        </p>

    </div>


    <div class="collection-hero-bottom page-container">

        <span>
            Handcrafted in Malawi
        </span>

        <span>
            Designed for living
        </span>

        <span>
            Customisable
        </span>

    </div>

</section>


<!-- =========================================================
     COLLECTION INTRO
========================================================== -->

<section class="collection-intro">

    <div class="page-container">


        <div class="collection-intro-grid">


            <div class="collection-intro-heading"
                 data-aos="fade-up">

                <div class="section-label">

                    <span class="label-line"></span>

                    THE COLLECTION

                </div>


                <h2>

                    Pieces made to
                    <em>belong.</em>

                </h2>

            </div>


            <div class="collection-intro-copy"
                 data-aos="fade-up"
                 data-aos-delay="100">

                <p>

                    Every Kwithu piece is created with a
                    balance of contemporary design,
                    practical comfort and honest craftsmanship.

                </p>


                <p>

                    Explore our collection and find something
                    that fits your space — or speak with us
                    about making it your own.

                </p>

            </div>

        </div>

    </div>

</section>


<!-- =========================================================
     COLLECTION SECTION
========================================================== -->

<section class="collection-section"
         id="collection">


    <div class="page-container">


        <!-- =================================================
             COLLECTION CONTROLS
        ================================================== -->

        <div class="collection-controls"
             data-aos="fade-up">


            <!-- CATEGORY FILTER -->

            <div class="collection-filter-wrap">


                <div class="collection-filter-label">

                    Explore by category

                </div>


                <div class="collection-filters"
                     id="collectionFilters"
                     role="tablist"
                     aria-label="Furniture categories">


                    <!-- ALL -->

                    <button class="collection-filter-btn active"
                            type="button"
                            data-filter="all"
                            role="tab"
                            aria-selected="true">

                        All

                    </button>


                    <!-- DATABASE CATEGORIES -->

                    <?php foreach ($categories as $categoryRow): ?>

                        <?php

                        $categoryName =
                            trim($categoryRow["category"] ?? "");

                        if ($categoryName === "") {
                            continue;
                        }

                        ?>

                        <button class="collection-filter-btn"
                                type="button"
                                data-filter="<?php echo e(strtolower($categoryName)); ?>"
                                role="tab"
                                aria-selected="false">

                            <?php echo e($categoryName); ?>

                        </button>

                    <?php endforeach; ?>


                </div>

            </div>


            <!-- =================================================
                 SEARCH
            ================================================== -->

            <div class="collection-search">

                <label for="collectionSearch"
                       class="sr-only">

                    Search furniture

                </label>


                <i class="fa-solid fa-magnifying-glass"></i>


                <input
                    type="search"
                    id="collectionSearch"
                    placeholder="Search our collection..."
                    autocomplete="off"
                    spellcheck="false"
                >

            </div>


        </div>


        <!-- =================================================
             CURRENCY BAR
        ================================================== -->

        <div class="collection-currency-bar"
             data-aos="fade-up">


            <div class="currency-info">

                <span class="currency-label">

                    <i class="fa-solid fa-coins"></i>

                    Display prices in

                </span>


                <span class="currency-note">

                    Prices are based on Malawi Kwacha.

                </span>

            </div>


            <div class="currency-switcher"
                 id="currencySwitcher"
                 role="group"
                 aria-label="Choose currency">


                <button class="currency-btn active"
                        type="button"
                        data-currency="MWK"
                        aria-pressed="true">

                    <span class="currency-code">
                        MWK
                    </span>

                    <span class="currency-name">
                        Kwacha
                    </span>

                </button>


                <button class="currency-btn"
                        type="button"
                        data-currency="ZAR"
                        aria-pressed="false">

                    <span class="currency-code">
                        ZAR
                    </span>

                    <span class="currency-name">
                        Rand
                    </span>

                </button>


                <button class="currency-btn"
                        type="button"
                        data-currency="USD"
                        aria-pressed="false">

                    <span class="currency-code">
                        USD
                    </span>

                    <span class="currency-name">
                        Dollar
                    </span>

                </button>


            </div>

        </div>


        <!-- =================================================
             COLLECTION SUMMARY
        ================================================== -->

        <div class="collection-results-meta">


            <span id="collectionResultsCount">

                <?php echo $productCount; ?>

                <?php echo $productCount === 1
                    ? "piece"
                    : "pieces"; ?>

            </span>


            <span class="collection-current-currency"
                  id="collectionCurrentCurrency">

                Prices in MWK

            </span>

        </div>


        <!-- =================================================
             DATABASE PRODUCT GRID
        ================================================== -->

        <div id="collectionGrid"
             class="collection-grid">


            <?php if (!empty($products)): ?>


                <?php foreach ($products as $index => $product): ?>


                    <?php

                    $productId =
                        (int) ($product["id"] ?? 0);


                    $productName =
                        trim($product["name"] ?? "Kwithu Furniture");


                    $category =
                        trim($product["category"] ?? "");


                    $collection =
                        trim($product["collection"] ?? "");


                    $description =
                        trim($product["description"] ?? "");


                    $mwkPrice =
                        (float) ($product["price"] ?? 0);

                    $zarPrice =
                        $product["price_zar"] ?? "";

                    $usdPrice =
                        $product["price_usd"] ?? "";

                    $image =
                        trim($product["image"] ?? "");


                    /*
                     * Product images uploaded through the
                     * admin panel are stored here.
                     */

                    $imagePath = "";

                    if ($image !== "") {

                        $imagePath =
                            "admin/uploads/products/" .
                            rawurlencode(basename($image));

                    }

                    $productImages = [];
                    foreach (array_merge(
                        $image !== "" ? [$image] : [],
                        $product["additional_images"]
                    ) as $productImage) {
                        $productImages[] =
                            "admin/uploads/products/" .
                            rawurlencode(basename($productImage));
                    }


                    /*
                     * Safe category used by JavaScript filters.
                     */

                    $filterCategory =
                        strtolower($category);


                    ?>


                    <!-- =================================================
                         PRODUCT CARD
                    ================================================== -->

                    <article class="collection-card"
                             data-product-id="<?php echo $productId; ?>"
                             data-category="<?php echo e($filterCategory); ?>"
                             data-name="<?php echo e(strtolower($productName)); ?>"
                             data-collection="<?php echo e(strtolower($collection)); ?>"
                             data-price-mwk="<?php echo e($mwkPrice); ?>"
                             data-price-zar="<?php echo e((string)$zarPrice); ?>"
                             data-price-usd="<?php echo e((string)$usdPrice); ?>"
                             data-description="<?php echo e($description); ?>"
                             data-images="<?php echo e(json_encode($productImages, JSON_UNESCAPED_SLASHES)); ?>"
                             data-category-label="<?php echo e($category); ?>"
                             data-collection-label="<?php echo e($collection); ?>"
                             data-aos="fade-up"
                             data-aos-delay="<?php echo ($index % 4) * 70; ?>">


                        <!-- PRODUCT IMAGE -->

                        <div class="collection-card-image">


                            <?php if ($imagePath !== ""): ?>


                                <img
                                    src="<?php echo e($imagePath); ?>"
                                    alt="<?php echo e($productName); ?>"
                                    loading="lazy"
                                >


                            <?php else: ?>


                                <div class="collection-card-no-image">

                                    <i class="fa-regular fa-image"></i>

                                    <span>
                                        Image unavailable
                                    </span>

                                </div>


                            <?php endif; ?>


                            <!-- IMAGE OVERLAY -->

                            <div class="collection-card-overlay">

                                <button type="button" class="collection-details-trigger">
                                    View Details
                                </button>

                                <i class="fa-solid fa-arrow-up-right"></i>

                            </div>


                        </div>


                        <!-- PRODUCT CONTENT -->

                        <div class="collection-card-content">


                            <!-- CATEGORY -->

                            <?php if ($category !== ""): ?>

                                <span class="collection-card-category">

                                    <?php echo e($category); ?>

                                </span>

                            <?php endif; ?>


                            <!-- NAME -->

                            <h3>

                                <?php echo e($productName); ?>

                            </h3>


                            <!-- COLLECTION -->

                            <?php if ($collection !== ""): ?>

                                <span class="collection-card-collection">

                                    <?php echo e($collection); ?>

                                </span>

                            <?php endif; ?>


                            <!-- DESCRIPTION -->

                            <?php if ($description !== ""): ?>

                                <p class="collection-card-description">

                                    <?php echo e($description); ?>

                                </p>

                            <?php endif; ?>


                            <!-- PRICE -->

                            <div class="collection-card-bottom">


                                <div class="collection-card-price"
                                     data-price-mwk="<?php echo e($mwkPrice); ?>"
                                     data-price-zar="<?php echo e((string)$zarPrice); ?>"
                                     data-price-usd="<?php echo e((string)$usdPrice); ?>">

                                    <span class="currency-symbol">
                                        MK
                                    </span>

                                    <span class="converted-price">

                                        <?php echo number_format(
                                            $mwkPrice,
                                            2
                                        ); ?>

                                    </span>

                                </div>


                                <!-- ENQUIRE -->

                                <a
                                    href="https://wa.me/265990816801?text=<?php echo rawurlencode(
                                        "Hello Kwithu Furniture, I would like to enquire about " .
                                        $productName .
                                        "."
                                    ); ?>"
                                    target="_blank"
                                    rel="noopener"
                                    class="collection-card-enquire"
                                    aria-label="Enquire about <?php echo e($productName); ?>">

                                    <i class="fa-brands fa-whatsapp"></i>

                                    Enquire

                                </a>


                            </div>


                        </div>


                    </article>


                <?php endforeach; ?>


            <?php endif; ?>


        </div>


        <!-- =================================================
             NO PRODUCTS / NO SEARCH RESULTS
        ================================================== -->

        <div class="collection-empty"
             id="collectionEmpty"
             <?php echo !empty($products)
                 ? 'style="display:none;"'
                 : ''; ?>>


            <div class="collection-empty-icon">

                <i class="fa-regular fa-images"></i>

            </div>


            <h3 id="collectionEmptyTitle">

                <?php echo empty($products)
                    ? "Our collection is coming soon"
                    : "No furniture found"; ?>

            </h3>


            <p id="collectionEmptyText">

                <?php echo empty($products)
                    ? "Furniture pieces uploaded by Kwithu Furniture will appear here."
                    : "Try another category or search term."; ?>

            </p>


        </div>


    </div>

</section>

<div class="product-details-modal" id="productDetailsModal" aria-hidden="true">
    <div class="product-details-backdrop" data-close-product-details></div>
    <section class="product-details-dialog" role="dialog" aria-modal="true" aria-labelledby="productDetailsTitle">
        <button type="button" class="product-details-close" aria-label="Close product details" data-close-product-details>&times;</button>
        <div class="product-details-gallery">
            <div class="product-details-main-image">
                <img id="productDetailsMainImage" src="" alt="">
            </div>
            <div class="product-details-thumbnails" id="productDetailsGallery" aria-label="Additional product images"></div>
        </div>
        <div class="product-details-copy">
            <span class="product-details-category" id="productDetailsCategory"></span>
            <h2 id="productDetailsTitle"></h2>
            <p class="product-details-collection" id="productDetailsCollection"></p>
            <div class="product-details-description">
                <h3>About this piece</h3>
                <p id="productDetailsDescription"></p>
            </div>
            <div class="product-details-bottom">
                <div class="collection-card-price product-details-price" id="productDetailsPrice">
                    <span class="currency-symbol">MK</span>
                    <span class="converted-price">0.00</span>
                </div>
                <a id="productDetailsEnquire" target="_blank" rel="noopener" class="collection-card-enquire product-details-enquire">
                    <i class="fa-brands fa-whatsapp"></i> Enquire about this piece
                </a>
            </div>
        </div>
    </section>
</div>


<!-- =========================================================
     COLLECTION CUSTOM NOTE
========================================================== -->

<section class="collection-custom-note">


    <div class="page-container">


        <div class="collection-custom-grid">


            <div class="collection-custom-content"
                 data-aos="fade-left">


                <div class="section-label">

                    <span class="label-line"></span>

                    MAKE IT YOURS

                </div>


                <h2>

                    Looking for something
                    <em>different?</em>

                </h2>


                <p>

                    Our collection is a starting point.
                    Kwithu Furniture can work with you on
                    selected sizes, finishes, fabrics and
                    design details to create furniture suited
                    to your space.

                </p>


                <a href="custom-furniture"
                   class="light-link">

                    Explore Custom Furniture

                    <i class="fa-solid fa-arrow-right"></i>

                </a>


            </div>

        </div>

    </div>

</section>


<!-- =========================================================
     COLLECTION CTA
========================================================== -->

<section class="collection-final">


    <div class="collection-final-background"></div>


    <div class="collection-final-overlay"></div>


    <div class="collection-final-content page-container">


        <div class="section-label light">

            <span class="label-line"></span>

            FIND YOUR PIECE

        </div>


        <h2>

            See something
            <em>you love?</em>

        </h2>


        <p>

            Ask us about availability, pricing,
            customisation or placing an order.

        </p>


        <div class="collection-final-actions">


            <a href="https://wa.me/265990816801?text=Hello%20Kwithu%20Furniture%2C%20I%20would%20like%20to%20enquire%20about%20your%20furniture%20collection."
               target="_blank"
               rel="noopener"
               class="btn btn-gold">

                <i class="fa-brands fa-whatsapp"></i>

                Enquire on WhatsApp

            </a>


            <a href="contact"
               class="btn btn-light">

                Contact Kwithu

                <i class="fa-solid fa-arrow-right"></i>

            </a>


        </div>

    </div>

</section>


<!-- =========================================================
     FOOTER
========================================================== -->

<footer class="site-footer">


    <div class="page-container">


        <!-- FOOTER TOP -->

        <div class="footer-top">


            <!-- FOOTER BRAND -->

            <div class="footer-brand">


                <a href="index"
                   class="footer-logo">

                    <img src="images/logo.png"
                         alt="Kwithu Furniture"
                         loading="lazy">

                </a>


                <p>

                    Handcrafted furniture designed
                    around the way you live.

                </p>


                <a href="https://wa.me/265990816801"
                   target="_blank"
                   rel="noopener"
                   class="footer-whatsapp">

                    <i class="fa-brands fa-whatsapp"></i>

                    +265 990 816 801

                </a>

            </div>


            <!-- FOOTER NAV -->

            <div class="footer-column">

                <h3>
                    Explore
                </h3>


                <a href="index">
                    Home
                </a>


                <a href="about">
                    Our Story
                </a>


                <a href="collection">
                    Collection
                </a>


                <a href="custom-furniture">
                    Custom Furniture
                </a>

            </div>


            <!-- FOOTER DISCOVER -->

            <div class="footer-column">

                <h3>
                    Discover
                </h3>


                <a href="gallery">
                    Gallery
                </a>


                <a href="contact">
                    Contact
                </a>


                <a href="collection">
                    Sofas
                </a>


                <a href="collection">
                    Dining
                </a>

            </div>


            <!-- FOOTER CONTACT -->

            <div class="footer-column footer-contact">

                <h3>
                    Visit
                </h3>


                <p>

                    Kittermaster Road
                    <br>
                    Blantyre, Malawi

                </p>


                <a href="https://www.google.com/maps/search/?api=1&query=Kittermaster+Road+Blantyre+Malawi"
                   target="_blank"
                   rel="noopener">

                    Get Directions

                    <i class="fa-solid fa-arrow-up-right"></i>

                </a>

            </div>

        </div>


        <!-- FOOTER BOTTOM -->

        <div class="footer-bottom">


            <p>

                © <span id="currentYear"></span>
                Kwithu Furniture.
                All rights reserved.

            </p>


            <div class="footer-socials">


                <a href="#"
                   aria-label="Facebook">

                    <i class="fa-brands fa-facebook-f"></i>

                </a>


                <a href="#"
                   aria-label="Instagram">

                    <i class="fa-brands fa-instagram"></i>

                </a>


                <a href="#"
                   aria-label="LinkedIn">

                    <i class="fa-brands fa-linkedin-in"></i>

                </a>


            </div>


            <p class="footer-credit">

                Crafted with intention.

            </p>

        </div>

    </div>

</footer>


<!-- =========================================================
     FLOATING WHATSAPP
========================================================== -->

<a href="https://wa.me/265990816801"
   class="floating-whatsapp"
   target="_blank"
   rel="noopener"
   aria-label="Chat with Kwithu Furniture on WhatsApp">

    <i class="fa-brands fa-whatsapp"></i>

    <span>
        Chat with us
    </span>

</a>


<!-- =========================================================
     SWIPER JS
========================================================== -->

<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>


<!-- =========================================================
     AOS JS
========================================================== -->

<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>


<!-- =========================================================
     COLLECTION PAGE JAVASCRIPT
========================================================== -->

<script>

document.addEventListener("DOMContentLoaded", function () {


    /* =========================================================
       AOS
    ========================================================== */

    if (typeof AOS !== "undefined") {

        AOS.init({

            duration: 800,

            once: true,

            offset: 70

        });

    }


    /* =========================================================
       ELEMENTS
    ========================================================== */

    const filterButtons =
        document.querySelectorAll(
            ".collection-filter-btn"
        );


    const productCards =
        document.querySelectorAll(
            ".collection-card"
        );

    const detailsModal = document.getElementById("productDetailsModal");
    const detailsTitle = document.getElementById("productDetailsTitle");
    const detailsCategory = document.getElementById("productDetailsCategory");
    const detailsCollection = document.getElementById("productDetailsCollection");
    const detailsDescription = document.getElementById("productDetailsDescription");
    const detailsGallery = document.getElementById("productDetailsGallery");
    const detailsMainImage = document.getElementById("productDetailsMainImage");
    const detailsEnquire = document.getElementById("productDetailsEnquire");
    const detailsPrice = document.getElementById("productDetailsPrice");

    function closeProductDetails() {
        if (!detailsModal) return;
        detailsModal.classList.remove("is-open");
        detailsModal.setAttribute("aria-hidden", "true");
        document.body.classList.remove("modal-open");
    }

    productCards.forEach(function (card) {
        card.setAttribute("tabindex", "0");
        card.setAttribute("role", "button");

        function openDetails() {
            if (!detailsModal) return;
            const name = card.querySelector("h3")?.textContent.trim() || "";
            detailsTitle.textContent = name;
            detailsCategory.textContent = card.dataset.categoryLabel || "";
            detailsDescription.textContent = card.dataset.description || "";
            detailsCollection.textContent = card.dataset.collectionLabel || "";
            detailsCollection.hidden = !detailsCollection.textContent;
            detailsDescription.parentElement.hidden = !detailsDescription.textContent;
            detailsPrice.dataset.priceMwk = card.dataset.priceMwk || "0";
            detailsPrice.dataset.priceZar = card.dataset.priceZar || "";
            detailsPrice.dataset.priceUsd = card.dataset.priceUsd || "";
            detailsEnquire.href =
                "https://wa.me/265990816801?text=" +
                encodeURIComponent("Hello Kwithu Furniture, I would like to enquire about " + name + ".");

            detailsGallery.replaceChildren();
            detailsMainImage.removeAttribute("src");
            detailsMainImage.alt = "";
            let images = [];
            try {
                images = JSON.parse(card.dataset.images || "[]");
            } catch (error) {
                console.error("Product image list could not be loaded.", error);
            }
            images.forEach(function (src, index) {
                const thumbnail = document.createElement("button");
                thumbnail.type = "button";
                thumbnail.className = "product-details-thumbnail";
                thumbnail.setAttribute("aria-label", "Show " + name + " image " + (index + 1));
                thumbnail.setAttribute("aria-pressed", index === 0 ? "true" : "false");

                const image = document.createElement("img");
                image.src = src;
                image.alt = index === 0 ? name : name + " detail " + (index + 1);
                image.loading = index === 0 ? "eager" : "lazy";
                thumbnail.appendChild(image);
                thumbnail.addEventListener("click", function () {
                    detailsMainImage.src = src;
                    detailsMainImage.alt = image.alt;
                    detailsGallery.querySelectorAll(".product-details-thumbnail").forEach(function (button) {
                        const selected = button === thumbnail;
                        button.classList.toggle("is-active", selected);
                        button.setAttribute("aria-pressed", selected ? "true" : "false");
                    });
                });
                detailsGallery.appendChild(thumbnail);
            });
            if (images.length) {
                detailsMainImage.src = images[0];
                detailsMainImage.alt = name;
                detailsGallery.querySelector(".product-details-thumbnail").classList.add("is-active");
            } else {
                detailsGallery.innerHTML = '<span class="product-details-no-images">No additional photos available</span>';
            }

            detailsModal.classList.add("is-open");
            detailsModal.setAttribute("aria-hidden", "false");
            document.body.classList.add("modal-open");
            updatePrices(activeCurrency);
            detailsModal.querySelector(".product-details-close").focus();
        }

        card.addEventListener("click", function (event) {
            if (event.target.closest("a")) return;
            openDetails();
        });
        card.addEventListener("keydown", function (event) {
            if (event.target.closest("a")) return;
            if (event.key === "Enter" || event.key === " ") {
                event.preventDefault();
                openDetails();
            }
        });
    });

    if (detailsModal) {
        detailsModal.querySelectorAll("[data-close-product-details]").forEach(function (button) {
            button.addEventListener("click", closeProductDetails);
        });
        document.addEventListener("keydown", function (event) {
            if (event.key === "Escape") closeProductDetails();
        });
    }


    const searchInput =
        document.getElementById(
            "collectionSearch"
        );


    const emptyBox =
        document.getElementById(
            "collectionEmpty"
        );


    const emptyTitle =
        document.getElementById(
            "collectionEmptyTitle"
        );


    const emptyText =
        document.getElementById(
            "collectionEmptyText"
        );


    const resultCount =
        document.getElementById(
            "collectionResultsCount"
        );


    const currentCurrency =
        document.getElementById(
            "collectionCurrentCurrency"
        );


    /* =========================================================
       CURRENT FILTER
    ========================================================== */

    let currentFilter = "all";


    /* =========================================================
       CURRENCY CONFIG
       PHP passes the configured rates to JavaScript.
    ========================================================== */

    const currencyRates = <?php
        echo json_encode(
            $currencyRates,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        );
    ?>;


    const currencySymbols = <?php
        echo json_encode(
            $currencySymbols,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        );
    ?>;


    /* =========================================================
       CURRENCY NAMES
    ========================================================== */

    const currencyNames = {

        MWK: "MWK",

        ZAR: "ZAR",

        USD: "USD"

    };

    let activeCurrency = "MWK";

    /* =========================================================
       FORMAT PRICE
    ========================================================== */

    function formatPrice(value) {

        return new Intl.NumberFormat(
            "en-US",
            {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }
        ).format(value);

    }


    /* =========================================================
       UPDATE PRODUCT PRICES
    ========================================================== */

    function updatePrices(currency) {

        activeCurrency = currency;

        const rate =
            Number(currencyRates[currency]) || 1;


        const symbol =
            currencySymbols[currency] || currency;


        document
            .querySelectorAll(
                ".collection-card-price, .product-details-price"
            )
            .forEach(function (priceElement) {


                const mwkPrice =
                    Number(
                        priceElement.getAttribute(
                            "data-price-mwk"
                        )
                    ) || 0;


                const manualPrice =
                    priceElement.getAttribute(
                        "data-price-" + currency.toLowerCase()
                    );

                const convertedPrice =
                    manualPrice !== null && manualPrice !== ""
                        ? Number(manualPrice)
                        : mwkPrice * rate;


                const symbolElement =
                    priceElement.querySelector(
                        ".currency-symbol"
                    );


                const priceValue =
                    priceElement.querySelector(
                        ".converted-price"
                    );


                if (symbolElement) {

                    symbolElement.textContent =
                        symbol;

                }


                if (priceValue) {

                    priceValue.textContent =
                        formatPrice(
                            convertedPrice
                        );

                }

            });


        if (currentCurrency) {

            currentCurrency.textContent =
                "Prices in " +
                currencyNames[currency];

        }


        /* =====================================================
           SAVE USER PREFERENCE
        ====================================================== */

        try {

            localStorage.setItem(
                "kwithuCurrency",
                currency
            );

        } catch (error) {

            /* Local storage unavailable */

        }

    }


    /* =========================================================
       CURRENCY SWITCHER
    ========================================================== */

    const currencyButtons =
        document.querySelectorAll(
            ".currency-btn"
        );


    currencyButtons.forEach(function (button) {


        button.addEventListener(
            "click",
            function () {


                const currency =
                    this.getAttribute(
                        "data-currency"
                    );


                currencyButtons.forEach(
                    function (btn) {

                        btn.classList.remove(
                            "active"
                        );

                        btn.setAttribute(
                            "aria-pressed",
                            "false"
                        );

                    }
                );


                this.classList.add(
                    "active"
                );


                this.setAttribute(
                    "aria-pressed",
                    "true"
                );


                updatePrices(
                    currency
                );

            }
        );

    });


    /* =========================================================
       RESTORE SAVED CURRENCY
    ========================================================== */

    let savedCurrency = "MWK";


    try {

        const stored =
            localStorage.getItem(
                "kwithuCurrency"
            );


        if (
            stored &&
            Object.prototype.hasOwnProperty.call(
                currencyRates,
                stored
            )
        ) {

            savedCurrency = stored;

        }

    } catch (error) {

        savedCurrency = "MWK";

    }


    currencyButtons.forEach(
        function (button) {

            const buttonCurrency =
                button.getAttribute(
                    "data-currency"
                );


            if (
                buttonCurrency ===
                savedCurrency
            ) {

                button.classList.add(
                    "active"
                );

                button.setAttribute(
                    "aria-pressed",
                    "true"
                );

            } else {

                button.classList.remove(
                    "active"
                );

                button.setAttribute(
                    "aria-pressed",
                    "false"
                );

            }

        }
    );


    updatePrices(
        savedCurrency
    );


    /* =========================================================
       FILTER + SEARCH
    ========================================================== */

    function filterProducts() {


        const searchTerm =
            searchInput
                ? searchInput.value
                    .trim()
                    .toLowerCase()
                : "";


        let visibleProducts = 0;


        productCards.forEach(
            function (card) {


                const category =
                    (
                        card.getAttribute(
                            "data-category"
                        ) || ""
                    ).toLowerCase();


                const name =
                    (
                        card.getAttribute(
                            "data-name"
                        ) || ""
                    ).toLowerCase();


                const collection =
                    (
                        card.getAttribute(
                            "data-collection"
                        ) || ""
                    ).toLowerCase();


                const matchesCategory =
                    currentFilter === "all" ||
                    category === currentFilter;


                const matchesSearch =
                    searchTerm === "" ||
                    name.includes(searchTerm) ||
                    category.includes(searchTerm) ||
                    collection.includes(searchTerm);


                if (
                    matchesCategory &&
                    matchesSearch
                ) {

                    card.style.display = "";

                    visibleProducts++;

                } else {

                    card.style.display = "none";

                }

            }
        );


        /* =====================================================
           UPDATE COUNT
        ====================================================== */

        if (resultCount) {

            resultCount.textContent =
                visibleProducts +
                (
                    visibleProducts === 1
                        ? " piece"
                        : " pieces"
                );

        }


        /* =====================================================
           EMPTY STATE
        ====================================================== */

        if (emptyBox) {


            if (visibleProducts === 0) {


                emptyBox.style.display =
                    "block";


                if (emptyTitle) {

                    emptyTitle.textContent =
                        "No furniture found";

                }


                if (emptyText) {

                    emptyText.textContent =
                        "Try another category or search term.";

                }


            } else {


                emptyBox.style.display =
                    "none";

            }

        }


        if (typeof AOS !== "undefined") {

            AOS.refresh();

        }

    }


    /* =========================================================
       CATEGORY FILTER EVENTS
    ========================================================== */

    filterButtons.forEach(
        function (button) {


            button.addEventListener(
                "click",
                function () {


                    currentFilter =
                        (
                            this.getAttribute(
                                "data-filter"
                            ) || "all"
                        ).toLowerCase();


                    filterButtons.forEach(
                        function (btn) {

                            btn.classList.remove(
                                "active"
                            );

                            btn.setAttribute(
                                "aria-selected",
                                "false"
                            );

                        }
                    );


                    this.classList.add(
                        "active"
                    );


                    this.setAttribute(
                        "aria-selected",
                        "true"
                    );


                    filterProducts();

                }
            );

        }
    );


    /* =========================================================
       SEARCH EVENT
    ========================================================== */

    if (searchInput) {


        searchInput.addEventListener(
            "input",
            function () {

                filterProducts();

            }
        );

    }


    /* =========================================================
       CURRENT YEAR
    ========================================================== */

    const currentYear =
        document.getElementById(
            "currentYear"
        );


    if (currentYear) {

        currentYear.textContent =
            new Date().getFullYear();

    }


    /* =========================================================
       MOBILE MENU
    ========================================================== */

    const menuToggle =
        document.getElementById(
            "menuToggle"
        );


    const mobileMenu =
        document.getElementById(
            "mobileMenu"
        );


    const mobileMenuClose =
        document.getElementById(
            "mobileMenuClose"
        );


    if (
        menuToggle &&
        mobileMenu
    ) {


        menuToggle.addEventListener(
            "click",
            function () {


                const isOpen = mobileMenu.classList.contains("active");
                mobileMenu.classList.toggle("active", !isOpen);
                document.body.classList.toggle("mobile-menu-open", !isOpen);
                mobileMenu.setAttribute("aria-hidden", String(isOpen));
                menuToggle.classList.toggle("active", !isOpen);
                menuToggle.setAttribute("aria-expanded", String(!isOpen));
                menuToggle.setAttribute(
                    "aria-label",
                    isOpen ? "Open navigation" : "Close navigation"
                );

            }
        );

    }


    if (
        mobileMenuClose &&
        mobileMenu
    ) {


        mobileMenuClose.addEventListener(
            "click",
            function () {


                mobileMenu.classList.remove("active");
                document.body.classList.remove("mobile-menu-open");
                mobileMenu.setAttribute("aria-hidden", "true");

                if (menuToggle) {
                    menuToggle.classList.remove("active");
                    menuToggle.setAttribute(
                        "aria-expanded",
                        "false"
                    );
                    menuToggle.setAttribute(
                        "aria-label",
                        "Open navigation"
                    );

                }

            }
        );

    }

    if (mobileMenu && menuToggle) {
        mobileMenu.querySelectorAll(".mobile-navigation a").forEach(
            function (link) {
                link.addEventListener("click", function () {
                    mobileMenu.classList.remove("active");
                    mobileMenu.setAttribute("aria-hidden", "true");
                    document.body.classList.remove("mobile-menu-open");
                    menuToggle.classList.remove("active");
                    menuToggle.setAttribute("aria-expanded", "false");
                    menuToggle.setAttribute("aria-label", "Open navigation");
                });
            }
        );
    }


});

</script>


</body>

</html>
