<?php
require_once __DIR__ . '/config/config.php';
$pageTitle = 'Home';
$pdo = getDB();
$stmt = $pdo->query("SELECT content FROM pages WHERE slug = 'home' AND is_active = 1 LIMIT 1");
$homeContent = $stmt->fetch(PDO::FETCH_ASSOC);
$content = $homeContent ? $homeContent['content'] : '';
$assetBase = (BASE_URL && BASE_URL !== '/') ? rtrim(BASE_URL, '/') . '/' : '';
$heroSlides = [];
$heroSlidesSupported = true;
try {
    $heroSlides = $pdo->query("SELECT id, eyebrow, title, subtitle, description, button_text, button_url, image FROM home_hero_slides WHERE is_active = 1 ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $heroSlides = []; $heroSlidesSupported = false; }

$heroSlidesFiltered = [];
foreach ($heroSlides as $s) {
    if (empty($s['image'])) continue;
    if (!is_file(BASE_PATH . '/uploads/home/' . $s['image'])) continue;
    $heroSlidesFiltered[] = $s;
}

function heroResolveUrl($assetBase, $url) {
    $url = trim((string)$url);
    if ($url === '') return '';
    if (preg_match('/^(https?:\/\/|mailto:|tel:|#)/i', $url)) return $url;
    return $assetBase . ltrim($url, '/');
}

$heroImageSrc = '';
$heroBanner = getSetting('hero_banner_image', '');
if ($heroBanner && is_file(BASE_PATH . '/uploads/home/' . $heroBanner)) {
    $heroImageSrc = $assetBase . 'uploads/home/' . rawurlencode($heroBanner);
} elseif ($content && preg_match('/<img[^>]+src=[\"\\\']([^\"\\\']+)[\"\\\'][^>]*>/i', $content, $m)) {
    $heroImageSrc = $m[1];
    $content = preg_replace('/<img[^>]+src=[\"\\\']' . preg_quote($heroImageSrc, '/') . '[\"\\\'][^>]*>\\s*/i', '', $content, 1);
}

// About company (for home section)
$aboutDir = BASE_PATH . '/uploads/about/';
$company = ['company_name' => 'Crimson Uni Quepack Pvt. Ltd.', 'company_details' => 'We are a leading manufacturer of mono cartons and corrugated packaging solutions, serving businesses across industries. Our facility combines precision printing with robust packaging to deliver products that protect your goods and elevate your brand.', 'image' => null, 'image_position' => 'right', 'tagline' => 'Premium Printing & Packaging Solutions'];
try {
    $stmt = $pdo->query("SELECT company_name, company_details, image, image_position, tagline FROM about_company WHERE is_active = 1 LIMIT 1");
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) $company = array_merge($company, $row);
} catch (Exception $e) {}
$companyImageSrc = null;
if (!empty($company['image']) && is_file($aboutDir . $company['image'])) {
    $companyImageSrc = $assetBase . 'uploads/about/' . rawurlencode($company['image']);
}

// Owner (for home section)
$owner = ['name' => 'Leadership', 'designation' => 'Founder & Managing Director', 'description' => 'Our leadership brings decades of experience in packaging and print. Under their guidance, we have built a culture of quality, innovation, and customer-first delivery.', 'image' => null];
try {
    $stmt = $pdo->query("SELECT name, designation, description, image FROM about_owner WHERE is_active = 1 LIMIT 1");
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) $owner = array_merge($owner, $row);
} catch (Exception $e) {}
$ownerImageSrc = null;
if (!empty($owner['image']) && is_file($aboutDir . $owner['image'])) {
    $ownerImageSrc = $assetBase . 'uploads/about/' . rawurlencode($owner['image']);
}

// Featured products (4 for home)
$featuredProducts = [];
try {
    $stmt = $pdo->query("SELECT p.id, p.name, p.slug, p.description, p.image, c.name AS category_name FROM products p LEFT JOIN product_categories c ON p.category_id = c.id WHERE p.is_active = 1 ORDER BY p.sort_order, p.id LIMIT 3");
    $featuredProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}
$placeholderProduct = $assetBase . 'assets/images/placeholder-product.svg';

require_once __DIR__ . '/includes/header.php';
?>
<?php if (!empty($heroSlidesFiltered)): ?>
<!-- Hero: Slider banners -->
<section class="hero-slider" aria-label="Hero banners">
    <div class="hero-slider-track js-hero-slider" data-autoplay="1" data-interval="5500">
        <?php foreach ($heroSlidesFiltered as $i => $s):
            $img = $assetBase . 'uploads/home/' . rawurlencode($s['image']);
            $href = (!empty($s['button_url'])) ? heroResolveUrl($assetBase, $s['button_url']) : '';
        ?>
        <article class="hero-slide<?php echo $i === 0 ? ' is-active' : ''; ?>" style="--hero-bg:url('<?php echo htmlspecialchars($img); ?>')">
            <div class="hero-slide-media" aria-hidden="true">
                <img class="hero-slide-img" src="<?php echo htmlspecialchars($img); ?>" alt="" loading="<?php echo $i === 0 ? 'eager' : 'lazy'; ?>" decoding="async">
            </div>
            <div class="container hero-slide-inner">
                <div class="hero-slide-panel">
                <div class="hero-slide-copy">
                    <?php if (!empty($s['eyebrow'])): ?>
                        <span class="hero-slide-eyebrow"><?php echo htmlspecialchars($s['eyebrow']); ?></span>
                    <?php endif; ?>
                    <h1 class="hero-slide-title"><?php echo htmlspecialchars($s['title'] ?? ''); ?></h1>
                    <?php if (!empty($s['subtitle'])): ?>
                        <p class="hero-slide-subtitle"><?php echo htmlspecialchars($s['subtitle']); ?></p>
                    <?php endif; ?>
                    <?php if (!empty($s['description'])): ?>
                        <p class="hero-slide-desc"><?php echo htmlspecialchars($s['description']); ?></p>
                    <?php endif; ?>
                    <?php if (!empty($s['button_text']) && $href !== ''): ?>
                        <a class="btn-glow btn-primary-modern hero-slide-btn" href="<?php echo htmlspecialchars($href); ?>">
                            <?php echo htmlspecialchars($s['button_text']); ?>
                        </a>
                    <?php endif; ?>
                </div>
                </div>
            </div>
        </article>
        <?php endforeach; ?>
    </div>
    <button type="button" class="hero-slider-nav hero-slider-prev" aria-label="Previous slide" data-hero-prev>‹</button>
    <button type="button" class="hero-slider-nav hero-slider-next" aria-label="Next slide" data-hero-next>›</button>
    <div class="hero-slider-dots" aria-label="Slide navigation" data-hero-dots></div>
</section>
<?php else: ?>
<!-- Hero: fallback (no slider yet) -->
<section class="hero-modern hero-packaging" aria-label="Welcome">
    <div class="hero-modern-bg" aria-hidden="true"></div>
    <div class="hero-corrugated-pattern" aria-hidden="true"></div>
    <div class="hero-modern-pattern" aria-hidden="true"></div>
    <div class="container hero-modern-inner">
        <div class="hero-modern-copy">
            <span class="hero-eyebrow hero-eyebrow--box">📦 Trusted packaging partner</span>
            <h1 class="hero-heading"><?php echo htmlspecialchars(getSetting('site_name', 'CRIMSON')); ?></h1>
            <p class="hero-tagline"><?php echo htmlspecialchars(getSetting('tagline', 'Manufacturer of Corrugated Boxes')); ?></p>
            <p class="hero-lead">Durable, eco‑friendly corrugated boxes for shipping, storage &amp; retail—built for industries that can’t afford damage.</p>
            <div class="hero-btns">
                <a href="<?php echo htmlspecialchars($assetBase); ?>products.php" class="btn-glow btn-primary-modern">Our Products</a>
                <a href="<?php echo htmlspecialchars($assetBase); ?>enquiry.php" class="btn-glow btn-white-outline">Get a Quote</a>
            </div>
            <?php if ($content): ?>
            <div class="hero-welcome-line"><?php echo $content; ?></div>
            <?php endif; ?>
        </div>
        <div class="hero-modern-visual">
            <?php if ($heroImageSrc): ?>
                <div class="hero-image-frame">
                    <img src="<?php echo htmlspecialchars($heroImageSrc); ?>" alt="" class="hero-image-main">
                </div>
            <?php else: ?>
                <div class="hero-card-stack" aria-hidden="true">
                    <div class="stack-card stack-card-1"></div>
                    <div class="stack-card stack-card-2"></div>
                    <div class="stack-card stack-card-3"></div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- About Our Company + Our Leadership — 2 rows: image + content each -->
<section class="section-home-about-leadership" aria-labelledby="home-about-title">
    <div class="container home-two-rows">
        <h2 id="home-about-title" class="section-title">About Our Company</h2>
        <p class="section-sub"><?php echo htmlspecialchars($company['tagline']); ?></p>
        <!-- Row 1: About Company — content left, image right -->
        <div class="home-row home-row-about about-image-<?php echo $company['image_position'] === 'left' ? 'left' : 'right'; ?>">
            <div class="home-row-copy">
                <h3 class="home-row-title"><?php echo htmlspecialchars($company['company_name']); ?></h3>
                <div class="home-row-text"><?php echo nl2br(htmlspecialchars($company['company_details'])); ?></div>
                <a href="<?php echo htmlspecialchars($assetBase); ?>about.php" class="btn-glow btn-primary-modern">Learn more</a>
            </div>
            <div class="home-row-media">
                <?php if ($companyImageSrc): ?>
                <img src="<?php echo htmlspecialchars($companyImageSrc); ?>" alt="<?php echo htmlspecialchars($company['company_name']); ?>" loading="lazy">
                <?php else: ?>
                <div class="home-row-placeholder">Company</div>
                <?php endif; ?>
            </div>
        </div>

        <h2 id="home-owner-title" class="section-title home-row-section-title">Our Leadership</h2>
        <p class="section-sub">The people behind our quality and your trust.</p>
        <!-- Row 2: Leadership — image left, content right -->
        <div class="home-row home-row-leadership">
            <div class="home-row-media">
                <?php if ($ownerImageSrc): ?>
                <img src="<?php echo htmlspecialchars($ownerImageSrc); ?>" alt="<?php echo htmlspecialchars($owner['name']); ?>" loading="lazy">
                <?php else: ?>
                <div class="home-row-placeholder">Leadership</div>
                <?php endif; ?>
            </div>
            <div class="home-row-copy">
                <h3 class="home-row-title"><?php echo htmlspecialchars($owner['name']); ?></h3>
                <p class="home-row-meta"><?php echo htmlspecialchars($owner['designation']); ?></p>
                <div class="home-row-text"><?php echo nl2br(htmlspecialchars($owner['description'])); ?></div>
                <a href="<?php echo htmlspecialchars($assetBase); ?>about.php" class="btn-glow btn-white-outline">About us</a>
            </div>
        </div>
    </div>
</section>

<?php include __DIR__ . '/includes/features_section.php'; ?>

<?php include __DIR__ . '/includes/client_section.php'; ?>

<?php include __DIR__ . '/includes/our_clients_section.php'; ?>

<!-- Featured Products (after Trusted / Our clients) -->
<section class="section-home-products section-home-block" aria-labelledby="home-products-title">
    <div class="container">
        <h2 id="home-products-title" class="section-title">Featured Products</h2>
        <p class="section-sub">Durable corrugated boxes and packaging solutions for every industry.</p>
        <p class="home-products-cta-wrap">
            <a href="<?php echo htmlspecialchars($assetBase); ?>products.php" class="btn-glow btn-primary-modern">View all products</a>
        </p>
        <?php if (!empty($featuredProducts)): ?>
        <div class="products-grid home-products-grid">
            <?php foreach ($featuredProducts as $p):
                $imgSrc = !empty($p['image']) ? $assetBase . UPLOAD_URL . 'products/' . $p['image'] : $placeholderProduct;
            ?>
            <article class="product-tile">
                <a href="<?php echo htmlspecialchars($assetBase); ?>product-detail.php?slug=<?php echo urlencode($p['slug']); ?>" class="product-tile-link">
                    <div class="product-tile-media">
                        <img src="<?php echo htmlspecialchars($imgSrc); ?>" alt="" loading="lazy" onerror="this.src='<?php echo htmlspecialchars($placeholderProduct); ?>'">
                        <?php if (!empty($p['category_name'])): ?>
                        <span class="product-tile-badge"><?php echo htmlspecialchars($p['category_name']); ?></span>
                        <?php endif; ?>
                        <span class="product-tile-overlay">
                            <span class="product-tile-cta">View details</span>
                        </span>
                    </div>
                    <div class="product-tile-body">
                        <h2 class="product-tile-title"><?php echo htmlspecialchars($p['name']); ?></h2>
                        <?php if (!empty($p['description'])): ?>
                        <p class="product-tile-excerpt"><?php echo htmlspecialchars(mb_substr(strip_tags($p['description']), 0, 110)); ?><?php echo mb_strlen(strip_tags($p['description'])) > 110 ? '…' : ''; ?></p>
                        <?php else: ?>
                        <p class="product-tile-excerpt product-tile-excerpt--muted">Durable corrugated packaging. Click for full details.</p>
                        <?php endif; ?>
                    </div>
                </a>
            </article>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <p class="home-products-empty">No products yet. <a href="<?php echo htmlspecialchars($assetBase); ?>enquiry.php">Send an enquiry</a> for custom requirements.</p>
        <?php endif; ?>
    </div>
</section>

<?php include __DIR__ . '/includes/why_choose_section.php'; ?>

<section class="section-cta">
    <div class="container cta-inner">
        <h2>Ready to order?</h2>
        <p>Browse our range or send requirements—we’ll respond quickly.</p>
        <a href="<?php echo htmlspecialchars($assetBase); ?>products.php" class="btn-glow btn-cta-big">View All Products</a>
    </div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
