<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'includes/header.php'; 
include 'includes/navbar.php'; 

// Auto-migrate tour_type column if missing
$check_type = $conn->query("SHOW COLUMNS FROM packages LIKE 'tour_type'");
if ($check_type && $check_type->num_rows == 0) {
    $conn->query("ALTER TABLE packages ADD COLUMN tour_type VARCHAR(20) DEFAULT 'group'");
}
?>

<!-- Premium Packages Hero -->
<div class="packages-hero" style="min-height: 60vh; background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), url('https://images.pexels.com/photos/3278215/pexels-photo-3278215.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'); background-size: cover; background-position: center; display: flex; align-items: center; justify-content: center; text-align: center; color: #fff; padding-top: 100px; padding-bottom: 150px;">
    <div class="container">
        <h6 class="reveal-up packages-subtitle" style="letter-spacing: 5px; text-transform: uppercase; color: var(--primary); font-size: 18px;">Adventure Awaits</h6>
        <h1 class="fw-bold reveal-up packages-title" style="letter-spacing: -2px; font-size: 80px;">TOUR PACKAGES</h1>
        <p class="lead reveal-up packages-text" style="max-width: 600px; margin: 20px auto 0;">Curated global experiences just for you. Explore the most iconic destinations with expert guidance and premium comfort.</p>
    </div>
</div>

<section class="py-5" style="background: #fdfcfb;">
    <div class="container">
        <!-- Filter -->
        <div class="row mb-5 justify-content-center reveal-up">
            <div class="col-md-10">
                <div style="background: #fff; padding: 30px; border-radius: 30px; box-shadow: 0 10px 40px rgba(0,0,0,0.05);">
                    <form action="packages.php" method="GET" class="row g-3">
                        <div class="col-md-4">
                            <select name="country" class="form-select border-0 bg-light py-3 px-4" style="border-radius: 15px;">
                                <option value="">All Destinations</option>
                                <?php
                                $dests = $conn->query("SELECT * FROM destinations ORDER BY name");
                                if($dests) {
                                    while($d = $dests->fetch_assoc()):
                                        $selected = (isset($_GET['country']) && $_GET['country'] == $d['id']) ? 'selected' : '';
                                        echo "<option value='{$d['id']}' $selected>".htmlspecialchars($d['name'])."</option>";
                                    endwhile;
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="type" class="form-select border-0 bg-light py-3 px-4" style="border-radius: 15px;">
                                <option value="">All Types</option>
                                <option value="group" <?= (isset($_GET['type']) && $_GET['type'] === 'group') ? 'selected' : '' ?>>Group Tour</option>
                                <option value="private" <?= (isset($_GET['type']) && $_GET['type'] === 'private') ? 'selected' : '' ?>>Private Tour</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="text" name="search" class="form-control border-0 bg-light py-3 px-4" style="border-radius: 15px;" placeholder="Search for your dream tour..." value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100 py-3 rounded-4 fw-bold"><i class="fas fa-search me-2"></i> Find</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Dynamic Packages Grid -->
        <div class="row g-4 justify-content-center">
            <?php
            $where = [];
            if (!empty($_GET['country'])) {
                $country_id = (int) $_GET['country'];
                $where[] = "p.country_id = $country_id";
            }
            if (!empty($_GET['type'])) {
                $type = sanitize($conn, $_GET['type']);
                $where[] = "p.tour_type = '$type'";
            }
            if (!empty($_GET['search'])) {
                $search = sanitize($conn, $_GET['search']);
                $where[] = "(p.title LIKE '%$search%' OR p.tour_name LIKE '%$search%')";
            }
            $whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
            $sql = "SELECT p.*, d.name as country_name FROM packages p JOIN destinations d ON p.country_id = d.id $whereClause ORDER BY p.sort_order DESC, p.id DESC";
            $pkgs = $conn->query($sql);

            if ($pkgs && $pkgs->num_rows > 0):
                while ($p = $pkgs->fetch_assoc()):
                    $wa_msg = urlencode("Hello Methsisila! I am interested in the " . $p['title'] . " package. Please provide more details.");
                    $wa_link = "https://wa.me/" . (!empty($settings['whatsapp_number']) ? $settings['whatsapp_number'] : '94771957420') . "?text=" . $wa_msg;
                    // === DYNAMIC IMAGE LOGIC ===
                    // Priority 1: Admin-uploaded main_image from DB
                    $db_img = $p['main_image'] ?? '';
                    if (strpos($db_img, 'uploads/') === 0) $db_img = substr($db_img, 8);
                    
                    if (!empty($db_img) && file_exists("uploads/" . $db_img)) {
                        $display_img = "uploads/" . $db_img;
                    } else {
                        // Priority 2: Scan uploads folder and assign by package index
                        $upload_files = array_values(array_filter(scandir("uploads/") ?? [], function($f) {
                            return preg_match('/\.(jpe?g|png|webp)$/i', $f);
                        }));
                        $idx = ($p['id'] - 1) % max(count($upload_files), 1);
                        $display_img = !empty($upload_files) ? "uploads/" . $upload_files[$idx] : "https://images.pexels.com/photos/1271619/pexels-photo-1271619.jpeg?auto=compress&cs=tinysrgb&w=600";
                    }
                    ?>
                    <div class="col-md-6 reveal-up">
                        <div class="card border-0 shadow-sm overflow-hidden h-100" style="border-radius: 35px; transition: 0.4s;">
                            <a href="package-details.php?id=<?= $p['id'] ?>" style="text-decoration: none; color: inherit;">
                                <div style="position: relative; height: 450px; overflow: hidden;">
                                    <img src="<?= str_replace(' ', '%20', $display_img) ?>?v=<?= time() ?>" class="w-100 h-100" style="object-fit: cover;" onerror="this.src='https://images.pexels.com/photos/1271619/pexels-photo-1271619.jpeg?auto=compress&cs=tinysrgb&w=600'">
                                    <div style="position: absolute; top: 20px; right: 20px; background: var(--primary); color: #fff; padding: 6px 18px; border-radius: 20px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px;"><?= htmlspecialchars($p['country_name']) ?></div>
                                </div>
                                <div class="card-body p-4 pb-0">
                                    <h4 class="fw-bold mb-3"><?= htmlspecialchars($p['title']) ?></h4>
                                    <div class="d-flex align-items-center mb-3 text-muted" style="font-size: 14px;">
                                        <span class="me-3"><i class="far fa-clock me-2 text-primary"></i> <?= htmlspecialchars($p['duration'] ?? '7 Days') ?></span>
                                        <span><i class="fas fa-users me-2 text-primary"></i> 
                                            <?php $ttype = $p['tour_type'] ?? 'group'; ?>
                                            <span class="badge <?= $ttype === 'private' ? 'bg-warning text-dark' : 'bg-success' ?> rounded-pill"><?= ucfirst($ttype) ?> Tour</span>
                                        </span>
                                    </div>
                                    <div class="mb-3">
                                        <span class="text-muted small d-block">Starting from</span>
                                        <h3 class="text-primary fw-bold mb-0">LKR <?= number_format($p['price'] ?? 0, 0) ?></h3>
                                    </div>
                                </div>
                            </a>
                            <div class="card-body p-4 pt-0 mt-auto">
                                <div class="d-flex gap-2">
                                    <a href="package-details.php?id=<?= $p['id'] ?>" class="btn btn-outline-primary rounded-pill flex-grow-1 py-2 fw-bold" style="font-size: 13px;">View Details</a>
                                    <a href="<?= $wa_link ?>" target="_blank" class="btn btn-success rounded-pill px-4 py-2 fw-bold" style="background: #25D366; border: none; font-size: 13px;">
                                        <i class="fab fa-whatsapp"></i> Inquiry
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <!-- Manual Cards for Group Tours as fallback -->
                <?php
                $group_tours = [
                    ['country' => 'INDIA', 'title' => '14 Days Dambadiwa Pilgrimage', 'period' => '14 Days/ 13 Nights', 'img' => 'assets/img 2/dambadiwa/2.jpeg'],
                    ['country' => 'EGYPT', 'title' => 'Pharaohs Discovery', 'period' => '10 Days/ 09 Nights', 'img' => 'assets/img 2/egypt/WhatsApp Image 2026-05-08 at 11.41.11 AM.jpeg'],
                    ['country' => 'THAILAND', 'title' => 'Bangkok & Phuket Tour', 'period' => '06 Days/ 05 Nights', 'img' => 'assets/img 2/thailand/2.jpeg'],
                    ['country' => 'SINGAPORE', 'title' => 'Singapore Duo Country', 'period' => '07 Days/ 06 Nights', 'img' => 'assets/img 2/singapore & malaysia/2.jpeg'],
                    ['country' => 'VIETNAM', 'title' => 'Vietnam Cultural Tour', 'period' => '08 Days/ 07 Nights', 'img' => 'assets/img 2/vietnam/2.jpeg'],
                    ['country' => 'AZERBAIJAN', 'title' => 'Fire & Ice Tour', 'period' => '07 Days/ 06 Nights', 'img' => 'assets/img 2/azerbaijan/1.jpeg'],
                ];
                
                foreach($group_tours as $gt):
                ?>
                <div class="col-md-6 reveal-up">
                    <div class="card border-0 shadow-sm overflow-hidden h-100" style="border-radius: 35px;">
                        <div style="position: relative; height: 450px; overflow: hidden;">
                            <img src="<?= $gt['img'] ?>?v=<?= time() ?>" class="w-100 h-100" style="object-fit: cover;">
                            <div style="position: absolute; top: 20px; right: 20px; background: var(--primary); color: #fff; padding: 6px 18px; border-radius: 20px; font-size: 11px; font-weight: 800;"><?= $gt['country'] ?></div>
                        </div>
                        <div class="card-body p-4">
                            <h4 class="fw-bold mb-3"><?= $gt['title'] ?></h4>
                            <div class="d-flex align-items-center mb-4 text-muted" style="font-size: 14px;">
                                <i class="far fa-clock me-2 text-primary"></i> <?= $gt['period'] ?>
                            </div>
                             <a href="https://wa.me/<?= (!empty($settings['whatsapp_number']) ? $settings['whatsapp_number'] : '94771957420') ?>?text=<?= urlencode('Interested in '.$gt['title']) ?>" target="_blank" class="btn btn-dark w-100 rounded-pill py-3 fw-bold">Inquiry on WhatsApp</a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- CSS Fix for Visibility -->
<style>
.reveal-up, .reveal-left, .reveal-right {
    opacity: 1 !important;
    transform: none !important;
    visibility: visible !important;
}
.card { transition: transform 0.4s ease, box-shadow 0.4s ease; }
.packages-title { font-size: 80px; }

@media (max-width: 768px) {
    .packages-hero {
        margin-top: 180px !important;
        padding-top: 50px !important;
        padding-bottom: 80px !important;
        min-height: auto !important;
    }
    .packages-title {
        font-size: 36px !important;
        line-height: 1.2;
    }
    .packages-subtitle {
        font-size: 14px !important;
        letter-spacing: 3px !important;
    }
    .packages-text {
        font-size: 16px !important;
    }
    .card div[style*="height: 450px"] {
        height: 250px !important;
    }
    .card .card-body {
        padding: 20px !important;
    }
    .card h4 {
        font-size: 20px !important;
    }
}
.card img {
    opacity: 1 !important;
}
/* Center rows and fix overflow */
.row {
    margin-left: 0 !important;
    margin-right: 0 !important;
    justify-content: center;
}
section {
    overflow: hidden;
}
</style>

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