<?php
// Show errors locally only
$_host_check = strtolower(explode(':', $_SERVER['HTTP_HOST'] ?? 'localhost')[0]);
if (in_array($_host_check, ['localhost', '127.0.0.1', '::1'])) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
}
unset($_host_check);

// Define BASE_URL if not already defined
if (!defined('BASE_URL')) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    define('BASE_URL', $scheme . '://' . $host . (in_array(strtolower(explode(':', $host)[0]), ['localhost', '127.0.0.1', '::1']) ? '/fivelake' : ''));
    unset($scheme, $host);
}

// Simple routing
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($request_uri, PHP_URL_PATH);

// Remove /fivelake from the beginning if present
if (strpos($path, '/fivelake') === 0) {
    $path = substr($path, 9); // Remove '/fivelake'
}

// Handle routing
if ($path === '/admin' || $path === '/admin/' || $path === '/admin/index.php') {
    include 'admin/login.php';
    exit;
} elseif ($path === '/user' || $path === '/user/' || $path === '/user/login') {
    include 'user/login.php';
    exit;
} elseif ($path === '/user/register' || $path === '/user/register.php') {
    include 'user/register.php';
    exit;
} elseif ($path === '/packages' || $path === '/packages.php') {
    include 'pages/packages.php';
    exit;
} elseif ($path === '/about' || $path === '/about.php') {
    include 'pages/about.php';
    exit;
} elseif ($path === '/contact' || $path === '/contact.php') {
    include 'pages/contact.php';
    exit;
} elseif ($path === '/hotels' || $path === '/hotels.php') {
    include 'pages/hotels_list.php';
    exit;
} elseif ($path === '/checkout' || $path === '/checkout.php') {
    include 'pages/checkout.php';
    exit;
} elseif (preg_match('#^/hotels/(\d+)/([a-z0-9-]+)$#i', $path, $m)) {
    $_GET['hotel'] = $m[1];
    include 'pages/hotels_list.php';
    exit;
} elseif (preg_match('#^/hotels/(\d+)$#', $path, $m)) {
    $_GET['hotel'] = $m[1];
    include 'pages/hotels_list.php';
    exit;
} elseif ($path === '/pay/paypal') {
    include 'pages/payments/paypal.php';
    exit;
} elseif ($path === '/pay/esewa') {
    include 'pages/payments/esewa.php';
    exit;
}

// Load packages for homepage display
require_once __DIR__ . '/admin/pages/packages_storage.php';
$packages = load_packages();
// Load hotels for homepage
require_once __DIR__ . '/admin/pages/hotels_storage.php';
$hotels = function_exists('load_hotels') ? load_hotels() : [];

// Read global hotels_enabled toggle
$__sf = __DIR__ . '/admin/pages/settings.json';
$__ss = is_file($__sf) ? (json_decode(file_get_contents($__sf), true) ?: []) : [];
$hotels_enabled = $__ss['hotels_enabled'] ?? true;
unset($__sf, $__ss);

// Home page content settings (admin-managed)
require_once __DIR__ . '/admin/pages/home_storage.php';
$home = load_home_settings();

// Featured packages (count from settings)
$featured_packages = array_filter($packages, fn($p) => !empty($p['featured']));
$featured_packages = empty($featured_packages)
    ? array_slice($packages, 0, (int)$home['packages_count'])
    : array_slice($featured_packages, 0, (int)$home['packages_count']);
$hotels_display = array_slice($hotels, 0, (int)$home['hotels_count']);

// Page meta
$page_title       = "Adventure Awaits in the Himalayas";
$page_description = "Experience the world's most spectacular trekking routes with Five Lake Trekking. Professional guides, safety first, unforgettable memories.";
$current_page     = "home";

include 'includes/modern_header.php';
?>

<!-- ============================ HERO ============================ -->
<section class="hero hero-home min-h-[88vh] flex items-center">
    <div class="container-narrow py-24" data-aos="fade-up">
        <?php if (!empty($home['hero_badge'])): ?><span class="badge-soft mb-5"><i class="fas fa-mountain-sun"></i> <?= htmlspecialchars($home['hero_badge']) ?></span><?php endif; ?>
        <h1 class="font-heading text-4xl md:text-6xl font-bold leading-tight max-w-3xl">
            <?= htmlspecialchars($home['hero_title']) ?> <span class="text-accent"><?= htmlspecialchars($home['hero_highlight']) ?></span>
        </h1>
        <p class="mt-5 text-lg text-white/85 max-w-2xl">
            <?= htmlspecialchars($home['hero_subtitle']) ?>
        </p>
        <div class="mt-8 flex flex-wrap gap-4">
            <a href="<?= htmlspecialchars($home['cta_link'] ?: BASE_URL . '/packages') ?>" class="btn-accent text-base"><i class="fas fa-hiking"></i> <?= htmlspecialchars($home['cta_label'] ?: 'Explore Packages') ?></a>
            <a href="#contact" class="btn-brand-outline text-base !text-white !border-white hover:!bg-white hover:!text-secondary"><i class="fas fa-phone"></i> Talk to an Expert</a>
        </div>

        <div class="mt-12 grid grid-cols-2 sm:grid-cols-4 gap-6 max-w-2xl">
            <?php
            $stats = [
                ['15+', 'Years guiding'],
                ['120+', 'Trek routes'],
                ['8K+', 'Happy trekkers'],
                ['4.9★', 'Avg. rating'],
            ];
            foreach ($stats as [$n, $l]): ?>
                <div>
                    <div class="font-heading text-3xl font-bold text-white"><?= $n ?></div>
                    <div class="text-sm text-white/70"><?= $l ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<!-- ===================== FEATURED PACKAGES ===================== -->
<?php if ($home['show_packages']): ?>
<section class="section">
    <div class="container-narrow">
        <div class="text-center max-w-2xl mx-auto mb-12" data-aos="fade-up">
            <span class="badge-soft mb-3"><i class="fas fa-fire"></i> Most popular</span>
            <h2 class="font-heading text-3xl md:text-4xl font-bold text-secondary">Featured Trekking Packages</h2>
            <p class="text-slate-500 mt-3">Discover Nepal's most loved trekking destinations, handpicked by our guides.</p>
        </div>

        <?php if (empty($featured_packages)): ?>
            <div class="text-center py-16">
                <i class="fas fa-mountain text-5xl text-slate-300 mb-4"></i>
                <h4 class="font-heading text-xl font-semibold text-slate-600">No packages available yet</h4>
                <p class="text-slate-400 mb-6">Please check back soon or contact us for custom trips.</p>
                <a href="<?= BASE_URL ?>/packages" class="btn-brand">Explore Packages</a>
            </div>
        <?php else: ?>
            <div class="grid gap-7 sm:grid-cols-2 lg:grid-cols-3">
                <?php foreach ($featured_packages as $i => $p):
                    $cover = (!empty($p['gallery'][0]))
                        ? BASE_URL . '/public/images/packages/' . htmlspecialchars($p['gallery'][0])
                        : BASE_URL . '/public/images/default-package.jpg';
                    $slug  = $p['slug'] ?? '';
                    $blurb = $p['short_description'] ?? $p['description'] ?? '';
                ?>
                <article class="card-soft flex flex-col" data-aos="fade-up" data-aos-delay="<?= ($i % 3) * 100 ?>">
                    <div class="relative h-56 overflow-hidden">
                        <img src="<?= $cover ?>" alt="<?= htmlspecialchars($p['title']) ?>" class="w-full h-full object-cover transition duration-500 hover:scale-110">
                        <div class="absolute top-3 left-3 flex gap-2">
                            <?php if (!empty($p['featured'])): ?>
                                <span class="badge-soft !bg-accent !text-white"><i class="fas fa-star"></i> Featured</span>
                            <?php endif; ?>
                            <span class="badge-soft !bg-secondary !text-white"><?= htmlspecialchars($p['difficulty'] ?? 'Easy') ?></span>
                        </div>
                    </div>
                    <div class="p-5 flex flex-col flex-1">
                        <h3 class="font-heading text-lg font-semibold text-secondary mb-2"><?= htmlspecialchars($p['title']) ?></h3>
                        <p class="text-sm text-slate-500 mb-4 flex-1"><?= htmlspecialchars(mb_strimwidth($blurb, 0, 110, '…')) ?></p>
                        <div class="flex items-center gap-4 text-sm text-slate-600 mb-4">
                            <span><i class="fas fa-calendar-day text-primary mr-1"></i><?= intval($p['duration'] ?? 0) ?> days</span>
                            <span><i class="fas fa-user-group text-primary mr-1"></i><?= htmlspecialchars($p['group_size'] ?? '—') ?></span>
                        </div>
                        <div class="flex items-center justify-between pt-4 border-t border-slate-100">
                            <div>
                                <?php if ($p['show_price'] ?? true): ?>
                                <span class="text-xs text-slate-400">from</span>
                                <span class="font-heading text-xl font-bold text-primary">$<?= number_format(floatval($p['price'] ?? 0)) ?></span>
                                <?php else: ?>
                                <span class="font-heading text-base font-bold text-primary">On Request</span>
                                <?php endif; ?>
                            </div>
                            <a href="<?= BASE_URL ?>/package.php?slug=<?= urlencode($slug) ?>" class="btn-brand text-sm">View Details</a>
                        </div>
                    </div>
                </article>
                <?php endforeach; ?>
            </div>

            <div class="text-center mt-12" data-aos="fade-up">
                <a href="<?= BASE_URL ?>/packages" class="btn-brand-outline text-base"><i class="fas fa-hiking"></i> Explore All Packages</a>
            </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>

<!-- ========================= WHY US ========================== -->
<?php if ($home['show_why_us']): ?>
<section class="section bg-white">
    <div class="container-narrow">
        <div class="text-center max-w-2xl mx-auto mb-12" data-aos="fade-up">
            <span class="badge-soft mb-3"><i class="fas fa-shield-heart"></i> Why Five Lake</span>
            <h2 class="font-heading text-3xl md:text-4xl font-bold text-secondary">Trek with total confidence</h2>
        </div>
        <div class="grid gap-7 sm:grid-cols-2 lg:grid-cols-4">
            <?php
            $features = [
                ['fa-user-shield', 'Expert Local Guides', 'Licensed, experienced guides who know every trail and culture.'],
                ['fa-heart-pulse', 'Safety First', 'First-aid trained teams, oxygen on high routes, 24/7 support.'],
                ['fa-hand-holding-dollar', 'Fair Pricing', 'Transparent costs, no hidden fees, best value guaranteed.'],
                ['fa-leaf', 'Responsible Travel', 'Eco-friendly treks that support local communities.'],
            ];
            foreach ($features as [$icon, $title, $desc]): ?>
                <div class="card-soft p-6 text-center" data-aos="fade-up">
                    <div class="w-14 h-14 mx-auto grid place-items-center rounded-2xl bg-primary-50 text-primary text-2xl mb-4">
                        <i class="fas <?= $icon ?>"></i>
                    </div>
                    <h3 class="font-heading font-semibold text-secondary mb-2"><?= $title ?></h3>
                    <p class="text-sm text-slate-500"><?= $desc ?></p>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<?php endif; ?>

<!-- ===================== RECOMMENDED HOTELS ==================== -->
<?php if ($hotels_enabled && $home['show_hotels'] && !empty($hotels_display)): ?>
<section class="section">
    <div class="container-narrow">
        <div class="flex items-end justify-between mb-10" data-aos="fade-up">
            <div>
                <span class="badge-soft mb-3"><i class="fas fa-bed"></i> Where to stay</span>
                <h2 class="font-heading text-3xl md:text-4xl font-bold text-secondary">Recommended Hotels</h2>
                <p class="text-slate-500 mt-2">Comfortable stays to complement your trek.</p>
            </div>
            <a href="<?= BASE_URL ?>/hotels" class="btn-brand-outline text-sm hidden sm:inline-flex">View More</a>
        </div>
        <div class="grid gap-7 sm:grid-cols-2 lg:grid-cols-3">
            <?php foreach ($hotels_display as $h):
                $img = !empty($h['gallery'][0])
                    ? BASE_URL . '/public/images/hotels/' . htmlspecialchars($h['gallery'][0])
                    : BASE_URL . '/public/images/default-hotel.jpg';
            ?>
            <article class="card-soft flex flex-col" data-aos="fade-up">
                <img src="<?= $img ?>" alt="<?= htmlspecialchars($h['name']) ?>" class="w-full h-52 object-cover">
                <div class="p-5 flex flex-col flex-1">
                    <h3 class="font-heading text-lg font-semibold text-secondary"><?= htmlspecialchars($h['name']) ?></h3>
                    <p class="text-xs text-primary font-medium mb-2"><i class="fas fa-location-dot mr-1"></i><?= htmlspecialchars($h['location'] ?? '') ?></p>
                    <p class="text-sm text-slate-500 flex-1"><?= htmlspecialchars(mb_strimwidth($h['description'] ?? '', 0, 90, '…')) ?></p>
                    <div class="flex gap-2 mt-4 pt-4 border-t border-slate-100">
                        <a href="<?= BASE_URL ?>/hotels/<?= $h['id'] ?>/<?= trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($h['name'] ?? 'hotel')), '-') ?>" class="btn-brand-outline text-sm flex-1 justify-center">View</a>
                        <a href="<?= BASE_URL ?>/checkout?hotel=<?= $h['id'] ?>" class="btn-brand text-sm flex-1 justify-center">Book</a>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ========================= CTA BANNER ======================= -->
<?php if ($home['show_cta']): ?>
<section class="py-16 bg-hero-gradient">
    <div class="container-narrow text-center text-white" data-aos="zoom-in">
        <h2 class="font-heading text-3xl md:text-4xl font-bold mb-3"><?= htmlspecialchars($home['cta_title']) ?></h2>
        <p class="text-white/80 max-w-xl mx-auto mb-7"><?= htmlspecialchars($home['cta_text']) ?></p>
        <a href="<?= BASE_URL ?>/packages" class="btn-accent text-base"><i class="fas fa-compass"></i> Browse All Treks</a>
    </div>
</section>
<?php endif; ?>

<?php include 'includes/modern_footer.php'; ?>
