<?php
require_once 'includes/functions.php';

$slug = $_GET['slug'] ?? '';
if (empty($slug)) {
    redirect(BASE_URL . 'packages.php');
}

$package = getPackageBySlug($slug);
if (!$package) {
    redirect(BASE_URL . 'packages.php');
}

$images = getPackageImages($package['id']);
$itinerary = getPackageItinerary($package['id']);
$pageTitle = $package['title'];

// Get related packages
$db = getDBConnection();
$stmt = $db->prepare("
    SELECT p.*, pl.name as place_name,
    (SELECT pi.image FROM package_images pi WHERE pi.package_id = p.id AND pi.is_primary = 1 LIMIT 1) as primary_image
    FROM packages p 
    JOIN places pl ON p.place_id = pl.id 
    WHERE p.place_id = ? AND p.id != ? AND p.status = 'active' LIMIT 3
");
$stmt->execute([$package['place_id'], $package['id']]);
$relatedPackages = $stmt->fetchAll();

$effectivePrice = $package['offer_price'] ?: $package['price_per_person'];

require_once 'includes/header.php';
?>

<!-- Package Hero -->
<div class="package-hero">
    <?php $heroImage = !empty($images) ? $images[0]['image'] : ''; ?>
    <img src="<?= getImageUrl($heroImage, 'packages') ?>" alt="<?= sanitize($package['title']) ?>">
    <div class="hero-overlay"></div>
    <div class="package-hero-content">
        <div class="container">
            <div class="breadcrumb" style="margin-bottom:10px;">
                <a href="<?= BASE_URL ?>" style="color:rgba(255,255,255,0.8);">Home</a>
                <span class="separator" style="color:rgba(255,255,255,0.5);"><i class="fas fa-chevron-right"></i></span>
                <a href="<?= BASE_URL ?>packages.php" style="color:rgba(255,255,255,0.8);">Packages</a>
                <span class="separator" style="color:rgba(255,255,255,0.5);"><i class="fas fa-chevron-right"></i></span>
                <span style="color:#fff;"><?= sanitize($package['title']) ?></span>
            </div>
            <h1 style="color:#fff;font-size:2.2rem;margin-bottom:10px;"><?= sanitize($package['title']) ?></h1>
            <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap;">
                <span style="color:rgba(255,255,255,0.9);display:flex;align-items:center;gap:6px;">
                    <i class="fas fa-map-marker-alt" style="color:var(--primary);"></i> <?= sanitize($package['place_name']) ?>
                </span>
                <span style="color:rgba(255,255,255,0.9);display:flex;align-items:center;gap:6px;">
                    <i class="fas fa-clock" style="color:var(--primary);"></i> <?= $package['duration_days'] ?> Days / <?= $package['duration_nights'] ?> Nights
                </span>
                <span style="color:rgba(255,255,255,0.9);display:flex;align-items:center;gap:6px;">
                    <i class="fas fa-users" style="color:var(--primary);"></i> Min <?= $package['min_people'] ?> People
                </span>
            </div>
        </div>
    </div>
</div>

<!-- Package Detail -->
<section class="package-detail">
    <div class="container">
        <div class="detail-grid">
            <!-- Left Content -->
            <div class="detail-content">
                <!-- Gallery -->
                <?php if (count($images) > 1): ?>
                <div class="package-gallery">
                    <?php foreach ($images as $img): ?>
                        <div class="gallery-item">
                            <img src="<?= getImageUrl($img['image'], 'packages') ?>" alt="<?= sanitize($package['title']) ?>">
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- Quick Info Cards -->
                <div class="package-info-cards">
                    <div class="info-card">
                        <i class="fas fa-calendar-alt"></i>
                        <span class="info-label">Duration</span>
                        <span class="info-value"><?= $package['duration_days'] ?>D / <?= $package['duration_nights'] ?>N</span>
                    </div>
                    <div class="info-card">
                        <i class="fas fa-users"></i>
                        <span class="info-label">Group Size</span>
                        <span class="info-value"><?= $package['min_people'] ?> - <?= $package['max_people'] ?></span>
                    </div>
                    <div class="info-card">
                        <i class="fas fa-plane-departure"></i>
                        <span class="info-label">Start Date</span>
                        <span class="info-value"><?= $package['start_date'] ? formatDate($package['start_date']) : 'Flexible' ?></span>
                    </div>
                    <div class="info-card">
                        <i class="fas fa-tag"></i>
                        <span class="info-label">Price</span>
                        <span class="info-value"><?= formatCurrency($effectivePrice) ?></span>
                    </div>
                </div>

                <!-- Description -->
                <div class="admin-card">
                    <div class="card-header">
                        <h3><i class="fas fa-info-circle text-primary"></i> Overview</h3>
                    </div>
                    <div class="card-body">
                        <p style="color:var(--gray);line-height:1.8;font-size:0.95rem;">
                            <?= nl2br(sanitize($package['description'])) ?>
                        </p>
                    </div>
                </div>

                <!-- Itinerary -->
                <?php if (!empty($itinerary)): ?>
                <div class="itinerary-section">
                    <h2 style="margin-bottom:25px;"><i class="fas fa-route text-primary"></i> Day-wise Itinerary</h2>
                    
                    <?php foreach ($itinerary as $day): ?>
                        <div class="itinerary-item">
                            <div class="day-marker">D<?= $day['day_number'] ?></div>
                            <div class="day-content">
                                <h4 class="day-title" style="cursor:pointer;">
                                    <i class="fas fa-sun text-primary" style="font-size:0.9rem;margin-right:5px;"></i>
                                    Day <?= $day['day_number'] ?>: <?= sanitize($day['title']) ?>
                                </h4>
                                <p class="day-description"><?= nl2br(sanitize($day['description'])) ?></p>
                                <div class="day-meta">
                                    <?php if ($day['meals']): ?>
                                        <span><i class="fas fa-utensils"></i> <?= sanitize($day['meals']) ?></span>
                                    <?php endif; ?>
                                    <?php if ($day['accommodation']): ?>
                                        <span><i class="fas fa-bed"></i> <?= sanitize($day['accommodation']) ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- Inclusions & Exclusions -->
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:30px;">
                    <?php if ($package['inclusions']): ?>
                    <div class="admin-card">
                        <div class="card-header">
                            <h3><i class="fas fa-check-circle text-success"></i> Inclusions</h3>
                        </div>
                        <div class="card-body">
                            <ul style="list-style:none;">
                                <?php foreach (explode("\n", $package['inclusions']) as $item): ?>
                                    <?php if (trim($item)): ?>
                                        <li style="padding:6px 0;color:var(--gray);display:flex;align-items:flex-start;gap:8px;">
                                            <i class="fas fa-check" style="color:var(--success);margin-top:4px;font-size:0.8rem;"></i>
                                            <?= sanitize(trim($item)) ?>
                                        </li>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($package['exclusions']): ?>
                    <div class="admin-card">
                        <div class="card-header">
                            <h3><i class="fas fa-times-circle text-danger"></i> Exclusions</h3>
                        </div>
                        <div class="card-body">
                            <ul style="list-style:none;">
                                <?php foreach (explode("\n", $package['exclusions']) as $item): ?>
                                    <?php if (trim($item)): ?>
                                        <li style="padding:6px 0;color:var(--gray);display:flex;align-items:flex-start;gap:8px;">
                                            <i class="fas fa-times" style="color:var(--danger);margin-top:4px;font-size:0.8rem;"></i>
                                            <?= sanitize(trim($item)) ?>
                                        </li>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Booking Sidebar -->
            <div class="booking-sidebar">
                <div class="booking-card">
                    <div class="price-section">
                        <?php if ($package['offer_price'] && $package['offer_price'] < $package['price_per_person']): ?>
                            <span class="offer-price"><?= formatCurrency($package['offer_price']) ?></span>
                            <span class="original-price"><?= formatCurrency($package['price_per_person']) ?></span>
                            <span class="discount-badge"><?= calculateDiscount($package['price_per_person'], $package['offer_price']) ?>% OFF</span>
                        <?php else: ?>
                            <span class="offer-price"><?= formatCurrency($package['price_per_person']) ?></span>
                        <?php endif; ?>
                        <span class="per-person">per person</span>
                    </div>

                    <?php if (isLoggedIn()): ?>
                        <form class="booking-form" action="<?= BASE_URL ?>book.php" method="POST" data-validate>
                            <input type="hidden" name="package_id" value="<?= $package['id'] ?>">
                            <input type="hidden" id="price_per_person" value="<?= $effectivePrice ?>">
                            
                            <div class="form-group">
                                <label>Travel Date <span style="color:var(--danger);">*</span></label>
                                <input type="date" name="travel_date" class="form-control" required 
                                       min="<?= date('Y-m-d', strtotime('+3 days')) ?>"
                                       max="<?= $package['end_date'] ?: date('Y-m-d', strtotime('+1 year')) ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>Number of People <span style="color:var(--danger);">*</span></label>
                                <input type="number" name="num_people" id="num_people" class="form-control" 
                                       value="<?= $package['min_people'] ?>" 
                                       min="<?= $package['min_people'] ?>" 
                                       max="<?= $package['max_people'] ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label>Special Requests</label>
                                <textarea name="special_requests" class="form-control" rows="3" placeholder="Any special requirements..."></textarea>
                            </div>
                            
                            <div class="total-section">
                                <div class="total-row">
                                    <span>Price per person</span>
                                    <span><?= formatCurrency($effectivePrice) ?></span>
                                </div>
                                <div class="total-row">
                                    <span>People</span>
                                    <span id="people_count"><?= $package['min_people'] ?></span>
                                </div>
                                <div class="total-row final">
                                    <span>Total Amount</span>
                                    <span id="total_amount_display"><?= formatCurrency($effectivePrice * $package['min_people']) ?></span>
                                </div>
                                <input type="hidden" name="total_amount" id="total_amount" value="<?= $effectivePrice * $package['min_people'] ?>">
                            </div>
                            
                            <button type="submit" class="btn btn-primary btn-block btn-lg">
                                <i class="fas fa-calendar-check"></i> Book Now
                            </button>
                        </form>
                    <?php else: ?>
                        <div style="text-align:center;padding:20px 0;">
                            <p style="color:var(--gray);margin-bottom:15px;">Please login to book this package</p>
                            <a href="<?= BASE_URL ?>login.php?redirect=<?= urlencode($_SERVER['REQUEST_URI']) ?>" class="btn btn-primary btn-block">
                                <i class="fas fa-sign-in-alt"></i> Login to Book
                            </a>
                            <p style="margin-top:10px;font-size:0.85rem;color:var(--gray);">
                                Don't have an account? <a href="<?= BASE_URL ?>register.php" style="color:var(--primary);font-weight:600;">Register</a>
                            </p>
                        </div>
                    <?php endif; ?>

                    <!-- Enquiry Form -->
                    <div style="margin-top:20px;padding-top:20px;border-top:1px solid var(--gray-lighter);">
                        <h4 style="font-size:1rem;margin-bottom:15px;font-family:var(--font-primary);">
                            <i class="fas fa-question-circle text-primary"></i> Have a Question?
                        </h4>
                        <form action="<?= BASE_URL ?>enquiry.php" method="POST" data-validate>
                            <input type="hidden" name="package_id" value="<?= $package['id'] ?>">
                            <div class="form-group">
                                <input type="text" name="name" class="form-control" placeholder="Your Name" required>
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" class="form-control" placeholder="Your Email" required>
                            </div>
                            <div class="form-group">
                                <input type="tel" name="phone" class="form-control" placeholder="Your Phone">
                            </div>
                            <div class="form-group">
                                <textarea name="message" class="form-control" rows="3" placeholder="Your Message" required></textarea>
                            </div>
                            <button type="submit" class="btn btn-outline btn-block">
                                <i class="fas fa-paper-plane"></i> Send Enquiry
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Related Packages -->
        <?php if (!empty($relatedPackages)): ?>
        <div style="margin-top:60px;">
            <h2 style="margin-bottom:25px;">Related Packages</h2>
            <div class="packages-grid">
                <?php foreach ($relatedPackages as $pkg): ?>
                    <div class="package-card">
                        <a href="<?= BASE_URL ?>package.php?slug=<?= $pkg['slug'] ?>" class="card-image">
                            <img src="<?= getImageUrl($pkg['primary_image'], 'packages') ?>" alt="<?= sanitize($pkg['title']) ?>" loading="lazy">
                            <div class="card-badges">
                                <span class="badge badge-duration"><i class="fas fa-clock"></i> <?= $pkg['duration_days'] ?>D/<?= $pkg['duration_nights'] ?>N</span>
                            </div>
                        </a>
                        <div class="card-body">
                            <div class="card-location">
                                <i class="fas fa-map-marker-alt"></i> <?= sanitize($pkg['place_name']) ?>
                            </div>
                            <a href="<?= BASE_URL ?>package.php?slug=<?= $pkg['slug'] ?>" class="card-title"><?= sanitize($pkg['title']) ?></a>
                            <div class="card-footer">
                                <div class="card-price">
                                    <?php if ($pkg['offer_price'] && $pkg['offer_price'] < $pkg['price_per_person']): ?>
                                        <div class="price-container">
                                            <span class="original-price"><?= formatCurrency($pkg['price_per_person']) ?></span>
                                            <span class="offer-price"><?= formatCurrency($pkg['offer_price']) ?> <small class="per-person">/ person</small></span>
                                            <span class="discount-badge"><?= calculateDiscount($pkg['price_per_person'], $pkg['offer_price']) ?>% OFF</span>
                                        </div>
                                    <?php else: ?>
                                        <span class="current-price"><?= formatCurrency($pkg['price_per_person']) ?> <small class="per-person">/ person</small></span>
                                    <?php endif; ?>
                                </div>
                                <a href="<?= BASE_URL ?>package.php?slug=<?= $pkg['slug'] ?>" class="btn btn-sm btn-primary">View Details</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<script>
// Update people count display
document.getElementById('num_people')?.addEventListener('input', function() {
    document.getElementById('people_count').textContent = this.value;
});
</script>

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