<?php
$pageTitle = 'Add Package';
require_once 'includes/header.php';

$places = $db->query("SELECT * FROM places WHERE status = 'active' ORDER BY name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $placeId = intval($_POST['place_id']);
    $title = sanitize($_POST['title']);
    $description = sanitize($_POST['description']);
    $pricePerPerson = floatval($_POST['price_per_person']);
    $offerPrice = !empty($_POST['offer_price']) ? floatval($_POST['offer_price']) : null;
    $durationDays = intval($_POST['duration_days']);
    $durationNights = intval($_POST['duration_nights']);
    $minPeople = intval($_POST['min_people']);
    $maxPeople = intval($_POST['max_people']);
    $startDate = $_POST['start_date'] ?: null;
    $endDate = $_POST['end_date'] ?: null;
    $inclusions = sanitize($_POST['inclusions']);
    $exclusions = sanitize($_POST['exclusions']);
    $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
    $status = sanitize($_POST['status']);
    $slug = createSlug($title);
    
    $stmt = $db->prepare("INSERT INTO packages (place_id, title, slug, description, price_per_person, offer_price, duration_days, duration_nights, min_people, max_people, start_date, end_date, inclusions, exclusions, is_featured, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->execute([$placeId, $title, $slug, $description, $pricePerPerson, $offerPrice, $durationDays, $durationNights, $minPeople, $maxPeople, $startDate, $endDate, $inclusions, $exclusions, $isFeatured, $status]);
    
    $packageId = $db->lastInsertId();
    
    // Handle images
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file = [
                    'name' => $_FILES['images']['name'][$key],
                    'tmp_name' => $_FILES['images']['tmp_name'][$key],
                    'size' => $_FILES['images']['size'][$key],
                    'error' => $_FILES['images']['error'][$key],
                ];
                $upload = uploadFile($file, 'packages');
                if ($upload['success']) {
                    $isPrimary = ($key === 0) ? 1 : 0;
                    $stmt = $db->prepare("INSERT INTO package_images (package_id, image, is_primary, sort_order) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$packageId, $upload['filename'], $isPrimary, $key]);
                }
            }
        }
    }
    
    // Handle itinerary
    if (!empty($_POST['itinerary_day'])) {
        foreach ($_POST['itinerary_day'] as $key => $dayNum) {
            if (!empty($_POST['itinerary_title'][$key])) {
                $stmt = $db->prepare("INSERT INTO itinerary (package_id, day_number, title, description, meals, accommodation) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $packageId,
                    intval($dayNum),
                    sanitize($_POST['itinerary_title'][$key]),
                    sanitize($_POST['itinerary_description'][$key] ?? ''),
                    sanitize($_POST['itinerary_meals'][$key] ?? ''),
                    sanitize($_POST['itinerary_accommodation'][$key] ?? '')
                ]);
            }
        }
    }
    
    logActivity($_SESSION['user_id'], 'package_created', "Created package: $title");
    setFlash('success', 'Package created successfully!');
    redirect(ADMIN_URL . 'packages-list.php');
}
?>

<div class="page-header">
    <h1><i class="fas fa-plus text-primary"></i> Add New Package</h1>
    <a href="<?= ADMIN_URL ?>packages-list.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<form method="POST" enctype="multipart/form-data" class="admin-form">
    <!-- Basic Info -->
    <div class="admin-card">
        <div class="card-header"><h3>Basic Information</h3></div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Place <span class="required">*</span></label>
                    <select name="place_id" class="form-control" required>
                        <option value="">Select Place</option>
                        <?php foreach ($places as $place): ?>
                            <option value="<?= $place['id'] ?>"><?= sanitize($place['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label>Package Title <span class="required">*</span></label>
                <input type="text" name="title" class="form-control" placeholder="e.g., Goa Beach Paradise - 4 Days" required>
            </div>
            
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="4" placeholder="Detailed package description..."></textarea>
            </div>
        </div>
    </div>
    
    <!-- Pricing & Duration -->
    <div class="admin-card">
        <div class="card-header"><h3>Pricing & Duration</h3></div>
        <div class="card-body">
            <div class="form-row three-col">
                <div class="form-group">
                    <label>Price Per Person (₹) <span class="required">*</span></label>
                    <input type="number" name="price_per_person" class="form-control" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label>Offer Price (₹)</label>
                    <input type="number" name="offer_price" class="form-control" step="0.01" min="0">
                    <span class="form-hint">Leave empty if no offer</span>
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <div class="form-check" style="padding-top:10px;">
                        <input type="checkbox" name="is_featured" id="is_featured" value="1">
                        <label for="is_featured">Featured Package</label>
                    </div>
                </div>
            </div>
            
            <div class="form-row" style="grid-template-columns:repeat(4,1fr);">
                <div class="form-group">
                    <label>Duration (Days) <span class="required">*</span></label>
                    <input type="number" name="duration_days" class="form-control" min="1" value="1" required>
                </div>
                <div class="form-group">
                    <label>Duration (Nights)</label>
                    <input type="number" name="duration_nights" class="form-control" min="0" value="0">
                </div>
                <div class="form-group">
                    <label>Min People</label>
                    <input type="number" name="min_people" class="form-control" min="1" value="2">
                </div>
                <div class="form-group">
                    <label>Max People</label>
                    <input type="number" name="max_people" class="form-control" min="1" value="20">
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>Start Date</label>
                    <input type="date" name="start_date" class="form-control">
                </div>
                <div class="form-group">
                    <label>End Date</label>
                    <input type="date" name="end_date" class="form-control">
                </div>
            </div>
        </div>
    </div>
    
    <!-- Images -->
    <div class="admin-card">
        <div class="card-header"><h3>Package Images</h3></div>
        <div class="card-body">
            <div class="form-group">
                <label>Upload Images (First image will be primary)</label>
                <input type="file" name="images[]" class="form-control" accept="image/*" multiple onchange="previewImages(this, 'images-preview')">
                <div class="image-preview-grid" id="images-preview"></div>
            </div>
        </div>
    </div>
    
    <!-- Inclusions & Exclusions -->
    <div class="admin-card">
        <div class="card-header"><h3>Inclusions & Exclusions</h3></div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Inclusions (one per line)</label>
                    <textarea name="inclusions" class="form-control" rows="6" placeholder="Hotel Accommodation&#10;Daily Breakfast&#10;Airport Transfers&#10;Sightseeing"></textarea>
                </div>
                <div class="form-group">
                    <label>Exclusions (one per line)</label>
                    <textarea name="exclusions" class="form-control" rows="6" placeholder="Airfare&#10;Lunch&#10;Personal Expenses&#10;Travel Insurance"></textarea>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Itinerary -->
    <div class="admin-card">
        <div class="card-header">
            <h3>Itinerary (Day-wise)</h3>
            <button type="button" class="btn btn-sm btn-primary" onclick="addItineraryDay()"><i class="fas fa-plus"></i> Add Day</button>
        </div>
        <div class="card-body" id="itinerary-container">
            <div class="itinerary-form-item" style="border:1px solid var(--gray-lighter);border-radius:8px;padding:20px;margin-bottom:15px;">
                <div class="form-row" style="grid-template-columns:80px 1fr;">
                    <div class="form-group">
                        <label>Day</label>
                        <input type="number" name="itinerary_day[]" class="form-control" value="1" min="1">
                    </div>
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" name="itinerary_title[]" class="form-control" placeholder="e.g., Arrival & Local Sightseeing">
                    </div>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="itinerary_description[]" class="form-control" rows="3" placeholder="Day activities description..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Meals</label>
                        <input type="text" name="itinerary_meals[]" class="form-control" placeholder="e.g., Breakfast, Dinner">
                    </div>
                    <div class="form-group">
                        <label>Accommodation</label>
                        <input type="text" name="itinerary_accommodation[]" class="form-control" placeholder="e.g., Hotel in Goa">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div style="display:flex;gap:10px;margin-top:10px;">
        <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Create Package</button>
        <a href="<?= ADMIN_URL ?>packages-list.php" class="btn btn-outline btn-lg">Cancel</a>
    </div>
</form>

<script>
let dayCounter = 1;
function addItineraryDay() {
    dayCounter++;
    const container = document.getElementById('itinerary-container');
    const html = `
        <div class="itinerary-form-item" style="border:1px solid var(--gray-lighter);border-radius:8px;padding:20px;margin-bottom:15px;position:relative;">
            <button type="button" onclick="this.parentElement.remove()" style="position:absolute;top:10px;right:10px;background:var(--danger);color:#fff;border:none;width:28px;height:28px;border-radius:50%;cursor:pointer;font-size:0.8rem;"><i class="fas fa-times"></i></button>
            <div class="form-row" style="grid-template-columns:80px 1fr;">
                <div class="form-group">
                    <label>Day</label>
                    <input type="number" name="itinerary_day[]" class="form-control" value="${dayCounter}" min="1">
                </div>
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" name="itinerary_title[]" class="form-control" placeholder="Day title...">
                </div>
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="itinerary_description[]" class="form-control" rows="3" placeholder="Day activities..."></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Meals</label>
                    <input type="text" name="itinerary_meals[]" class="form-control" placeholder="e.g., Breakfast, Dinner">
                </div>
                <div class="form-group">
                    <label>Accommodation</label>
                    <input type="text" name="itinerary_accommodation[]" class="form-control" placeholder="e.g., Hotel">
                </div>
            </div>
        </div>
    `;
    container.insertAdjacentHTML('beforeend', html);
}
</script>

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