<?php
declare(strict_types=1);
session_start();
$loggedIn = isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0;
$role = $loggedIn ? (string)($_SESSION['role'] ?? 'Buyer') : 'Buyer';
$action = isset($_GET['action']) ? (string)$_GET['action'] : '';

if ($action === 'home_images') {
    $dbHost = getenv('DB_HOST') ?: 'localhost';
    $dbUser = getenv('DB_USER') ?: 'root';
    $dbPass = getenv('DB_PASSWORD') ?: '';
    $dbName = 'listbnb';
    try {
        $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    } catch (Throwable $e) {
        header('Content-Type: application/json');
        echo json_encode(['items' => []]);
        exit;
    }
    try { $pdo->exec('CREATE TABLE IF NOT EXISTS home_images (id INT AUTO_INCREMENT PRIMARY KEY, image_path VARCHAR(255) NOT NULL, sort_order TINYINT UNSIGNED NOT NULL DEFAULT 1, active TINYINT(1) NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); } catch (Throwable $e) {}
    $rows = [];
    try { $rows = $pdo->query('SELECT image_path FROM home_images WHERE active=1 ORDER BY sort_order ASC LIMIT 10')->fetchAll(); } catch (Throwable $e) { $rows = []; }
    $items = [];
    foreach ($rows as $r) { if (!empty($r['image_path'])) { $items[] = (string)$r['image_path']; } }
    header('Content-Type: application/json');
    echo json_encode(['items' => $items]);
    exit;
}
$file = __DIR__ . DIRECTORY_SEPARATOR . 'index-2.html';
$html = @file_get_contents($file);
if ($html === false) {
    header('Location: index-2.html');
    exit;
}
if ($loggedIn) {
    $html = str_replace('<a href="login.html"><i class="fa-light fa-user"></i>Sign In</a>', '<a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i>Logout</a>', $html);
    $html = str_replace('href="listing-ads.html"', ($role === 'Admin' ? 'href="admin-add-product.php"' : 'href="listing-ads.html"'), $html);
    $html = str_replace('href="index-2.html"', 'href="index-2.php"', $html);
} else {
    $html = str_replace('href="listing-ads.html"', 'href="login.html"', $html);
}

// Reduce spacing between slider and category, and change subtitle text
$html = str_replace('tp-category-3-area pt-120 pb-90', 'tp-category-3-area pt-30 pb-60', $html);
$html = str_replace('tp-category-3-area pt-30 pb-60', 'tp-category-3-area pt-10 pb-40', $html);
$html = str_replace('tp-category-3-title-box pb-70', 'tp-category-3-title-box pb-20', $html);
$html = str_replace('Hand-Picked Category', 'Category', $html);
$html = str_replace('row row-cols-xl-4 row-cols-lg-4 row-cols-md-3 row-cols-sm-2 row-cols-1 justify-content-center', 'row row-cols-xl-4 row-cols-lg-4 row-cols-md-3 row-cols-sm-2 row-cols-1', $html);
$html = str_replace('row row-cols-xl-4 row-cols-lg-4 row-cols-md-3 row-cols-sm-2 row-cols-1', 'row row-cols-xl-5 row-cols-lg-5 row-cols-md-4 row-cols-sm-2 row-cols-1', $html);

// Insert "Track Order" nav item for logged-in users only, between Categories and About Us
$needle = "                                 </ul>\n                              </li>\n                              <li>\n                                 <a href=\"about-us.html\">About Us</a";
if ($loggedIn && strpos($html, $needle) !== false) {
    $orderLink = '<li><a href="my-orders.php">Track Order</a></li>';
    $html = str_replace($needle, "                                 </ul>\n                              </li>\n                              {$orderLink}\n                              <li>\n                                 <a href=\"about-us.html\">About Us</a", $html);
}

// Insert slider section just below nav (at start of <main>)
$sliderSection = <<<HTML

    <section class="tp-home-slider-area">
      <style>
        .tp-home-slider-area{padding-top:0;padding-bottom:0;margin-top:92px}
        .home-slider{border-radius:0;overflow:hidden}
        .home-slider .slide{position:relative}
        .home-slider img{width:100%;height:380px;object-fit:cover;display:block}
        .tp-hero-2-bg{background-image:none!important}
        .tp-hero-2-area{display:none!important}
        #header-sticky, .tp-header-area{background:#0f0f10!important;border-bottom:1px solid #1b1b1b!important}
        .tp-main-menu-content > ul > li > a{color:#fff!important}
        .tp-header-logo a{color:#fff!important}
        .tp-header-logo .brand-text{color:transparent!important;-webkit-text-stroke:1.5px #ff3b8f}
        .tp-header-right a{color:#fff!important}
        .tp-header-btn .tp-btn-white, .tp-header-btn .tp-btn-white span, .tp-header-btn .tp-btn-white i{color:#111!important}
        .tp-header-ptb{padding-top:16px!important;padding-bottom:12px!important}
        .header-sticky .tp-header-main-menu nav ul li > a{padding:18px 0!important}
        .tp-header-style-2 .tp-header-menu > nav > ul > li > a{padding:18px 0!important}
        .tp-category-3-area .row.justify-content-center{justify-content:flex-start!important}
        .tp-category-3-area .col.mb-30{margin-bottom:16px!important}
        .tp-category-3-item{height:60px!important;padding:12px 16px!important;width:100%!important}
        .tp-category-3-text{flex:1;min-width:0}
        .tp-category-3-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        
        .home-slider .slick-prev, .home-slider .slick-next{position:absolute;top:50%;transform:translateY(-50%);z-index:5;background:rgba(0,0,0,.45);color:#fff;border:none;width:42px;height:42px;border-radius:999px;display:flex;align-items:center;justify-content:center}
        .home-slider .slick-prev{left:14px}
        .home-slider .slick-next{right:14px}
        .home-slider .slick-prev i, .home-slider .slick-next i{font-size:18px}
        .home-slider .slick-dots{bottom:10px}
        .home-slider .slick-dots li{margin:0 4px;list-style:none}
        .home-slider .slick-dots li button{width:10px;height:10px;border-radius:50%;background:#fff;opacity:.5;font-size:0;line-height:0;color:transparent;border:none}
        .home-slider .slick-dots li.slick-active button{opacity:1}
        .home-slider .slick-dots li button:before{content:''}
        .floating-whatsapp{position:fixed;bottom:22px;right:22px;width:56px;height:56px;background:#25D366;color:#fff;border-radius:999px;display:flex;align-items:center;justify-content:center;box-shadow:0 10px 24px rgba(0,0,0,.15);z-index:9999;cursor:pointer}
        .floating-whatsapp i{font-size:26px}
        .floating-whatsapp:hover{transform:scale(1.05)}
        @media (max-width:767px){ .floating-whatsapp{bottom:14px;right:14px;width:52px;height:52px} }
      </style>
      <div class="home-slider"></div>
      <a class="floating-whatsapp" href="https://wa.me/?text=Hello%20from%20ReWear" target="_blank" aria-label="WhatsApp"><i class="fa-brands fa-whatsapp"></i></a>
    </section>

HTML;
$html = str_replace('<main>', '<main>' . $sliderSection, $html);

// Script to populate and initialize slider from DB
$inject = <<<JS

    <script>
    (function(){
      function init(images){
        if(!images || !images.length) return;
        var cont = document.querySelector('.home-slider');
        if(!cont) return;
        var html = "";
        for(var i=0;i<images.length;i++){
          html += '<div class="slide"><img src="' + images[i] + '" alt="slide"/></div>';
        }
        cont.innerHTML = html;
        if(window.jQuery && typeof jQuery.fn.slick === 'function'){
          jQuery('.home-slider').slick({
            dots:true,
            arrows:true,
            autoplay:true,
            autoplaySpeed:4000,
            customPaging:function(){ return '<button type="button"></button>'; },
            prevArrow:'<button type="button" class="slick-prev" aria-label="Previous"><i class="fa-solid fa-chevron-left"></i></button>',
            nextArrow:'<button type="button" class="slick-next" aria-label="Next"><i class="fa-solid fa-chevron-right"></i></button>'
          });
        }
      }
      try{
        fetch('index-2.php?action=home_images').then(function(r){return r.json()}).then(function(d){ init(d && d.items ? d.items : []); }).catch(function(){});
      }catch(e){}
    })();
    </script>

JS;
$html = str_replace('</body>', $inject . '</body>', $html);
echo $html;
