<?php
include 'auth.php';
include '../includes/header.php';

$id = (int)$_GET['id'];
$pkg = $conn->query("SELECT * FROM packages WHERE id = $id")->fetch_assoc();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = sanitize($conn, $_POST['title']);
    $country_id = (int)$_POST['country_id'];
    $tour_name = sanitize($conn, $_POST['tour_name']);
    $duration = sanitize($conn, $_POST['duration']);
    $travel_period = sanitize($conn, $_POST['travel_period']);
    $price = (float)$_POST['price'];
    $landmarks = sanitize($conn, $_POST['landmarks']);
    $includes = sanitize($conn, $_POST['includes']);
    $sort_order = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 0;
    $tour_type = isset($_POST['tour_type']) && in_array($_POST['tour_type'], ['group', 'private']) ? $_POST['tour_type'] : 'group';

    $update_fields = [
        "title = '$title'",
        "country_id = $country_id",
        "tour_name = '$tour_name'",
        "duration = '$duration'",
        "travel_period = '$travel_period'",
        "price = $price",
        "landmarks = '$landmarks'",
        "includes = '$includes'",
        "sort_order = $sort_order",
        "tour_type = '$tour_type'"
    ];

    if (!empty($_FILES['main_image']['name'])) {
        $main_image = time() . '_' . $_FILES['main_image']['name'];
        move_uploaded_file($_FILES['main_image']['tmp_name'], "../uploads/" . $main_image);
        $update_fields[] = "main_image = '$main_image'";
    }

    if (!empty($_FILES['brochure_pdf']['name'])) {
        $brochure_pdf = time() . '_' . $_FILES['brochure_pdf']['name'];
        move_uploaded_file($_FILES['brochure_pdf']['tmp_name'], "../uploads/" . $brochure_pdf);
        $update_fields[] = "brochure_pdf = '$brochure_pdf'";
    }

    $sql = "UPDATE packages SET " . implode(', ', $update_fields) . " WHERE id = $id";
    
    if ($conn->query($sql)) {
        if (!empty($_FILES['gallery']['name'][0])) {
            foreach ($_FILES['gallery']['tmp_name'] as $key => $tmp_name) {
                $img_name = time() . '_' . $_FILES['gallery']['name'][$key];
                move_uploaded_file($tmp_name, "../uploads/" . $img_name);
                $conn->query("INSERT INTO package_gallery (package_id, image) VALUES ($id, '$img_name')");
            }
        }
        echo "<script>alert('Package updated successfully!'); window.location='packages.php';</script>";
    }
}
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold mb-0">Edit Tour Package</h2>
        <a href="packages.php" class="btn btn-outline-secondary rounded-pill px-4">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <div class="card border-0 shadow-sm" style="border-radius: 20px;">
        <div class="card-body p-5">
            <form method="POST" enctype="multipart/form-data">
                <!-- Basic Information -->
                <div class="mb-5">
                    <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">1. Basic Information</h5>
                    <div class="row g-4">
                        <div class="col-md-8">
                            <label class="form-label fw-bold text-muted small text-uppercase">Tour Title</label>
                            <input type="text" name="title" class="form-control form-control-lg border-0 bg-light" value="<?= htmlspecialchars($pkg['title']) ?>" style="border-radius: 12px;" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Destination</label>
                            <select name="country_id" class="form-select form-select-lg border-0 bg-light" style="border-radius: 12px;" required>
                                <?php
                                $dests = $conn->query("SELECT * FROM destinations ORDER BY name");
                                while($d = $dests->fetch_assoc()):
                                    $sel = $d['id'] == $pkg['country_id'] ? 'selected' : '';
                                ?>
                                <option value="<?= $d['id'] ?>" <?= $sel ?>><?= htmlspecialchars($d['name']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Tour Type</label>
                            <select name="tour_type" class="form-select form-select-lg border-0 bg-light" style="border-radius: 12px;" required>
                                <option value="group" <?= ($pkg['tour_type'] ?? 'group') === 'group' ? 'selected' : '' ?>>Group Tour</option>
                                <option value="private" <?= ($pkg['tour_type'] ?? '') === 'private' ? 'selected' : '' ?>>Private Tour</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Logistics & Pricing -->
                <div class="mb-5">
                    <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">2. Logistics & Pricing</h5>
                    <div class="row g-4">
                        <div class="col-md-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Duration</label>
                            <input type="text" name="duration" class="form-control border-0 bg-light py-3" value="<?= htmlspecialchars($pkg['duration']) ?>" style="border-radius: 12px;" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Travel Period</label>
                            <input type="text" name="travel_period" class="form-control border-0 bg-light py-3" value="<?= htmlspecialchars($pkg['travel_period']) ?>" style="border-radius: 12px;" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Price (LKR)</label>
                            <div class="input-group">
                                <span class="input-group-text border-0 bg-light" style="border-radius: 12px 0 0 12px;">LKR</span>
                                <input type="number" name="price" class="form-control border-0 bg-light py-3" value="<?= (int)$pkg['price'] ?>" style="border-radius: 0 12px 12px 0;" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Sort Order</label>
                            <input type="number" name="sort_order" class="form-control border-0 bg-light py-3" value="<?= htmlspecialchars($pkg['sort_order'] ?? 0) ?>" style="border-radius: 12px;" required>
                        </div>
                    </div>
                </div>

                <!-- Detailed Content -->
                <div class="mb-5">
                    <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">3. Detailed Content</h5>
                    <div class="row g-4">
                        <div class="col-md-12">
                            <label class="form-label fw-bold text-muted small text-uppercase">Tour Overview / Full Description</label>
                            <textarea name="tour_name" class="form-control border-0 bg-light" rows="5" style="border-radius: 15px;" required><?= htmlspecialchars($pkg['tour_name']) ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Key Landmarks</label>
                            <textarea name="landmarks" class="form-control border-0 bg-light" rows="6" style="border-radius: 15px;" required><?= htmlspecialchars($pkg['landmarks']) ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">What's Included</label>
                            <textarea name="includes" class="form-control border-0 bg-light" rows="6" style="border-radius: 15px;" required><?= htmlspecialchars($pkg['includes']) ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Media Uploads -->
                <div class="mb-5">
                    <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">4. Media & Documents</h5>
                    <div class="row g-4">
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Main Cover Image</label>
                            <input type="file" name="main_image" class="form-control border-0 bg-light py-3" style="border-radius: 12px;" accept="image/*">
                            <?php if($pkg['main_image']): ?>
                                <div class="mt-2 p-2 bg-light rounded-3 d-inline-block">
                                    <img src="../uploads/<?= $pkg['main_image'] ?>" height="60" class="rounded">
                                    <span class="ms-2 small text-muted">Current image</span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Add Gallery Images</label>
                            <input type="file" name="gallery[]" class="form-control border-0 bg-light py-3" style="border-radius: 12px;" accept="image/*" multiple>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Tour Brochure (PDF)</label>
                            <input type="file" name="brochure_pdf" class="form-control border-0 bg-light py-3" style="border-radius: 12px;" accept="application/pdf">
                            <?php if($pkg['brochure_pdf']): ?>
                                <div class="mt-2"><i class="fas fa-file-pdf text-danger"></i> <span class="small text-muted">PDF attached</span></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="text-end pt-4">
                    <button type="submit" class="btn btn-primary px-5 py-3 rounded-pill fw-bold shadow-lg">
                        <i class="fas fa-save me-2"></i> UPDATE PACKAGE
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
