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

$id = (int)$_GET['id'];
if (!$id) { header("Location: local-tours.php"); exit(); }

// Self-heal new columns
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS category_id INT DEFAULT NULL");
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS duration VARCHAR(100) DEFAULT NULL");
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS highlights TEXT DEFAULT NULL");
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS includes_list TEXT DEFAULT NULL");
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS tour_type VARCHAR(50) DEFAULT 'day-tour'");
$conn->query("ALTER TABLE local_tours ADD COLUMN IF NOT EXISTS sort_order INT DEFAULT 0");

$tour    = $conn->query("SELECT * FROM local_tours WHERE id = $id")->fetch_assoc();
$gallery = $conn->query("SELECT * FROM local_tour_gallery WHERE tour_id = $id");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title         = sanitize($conn, $_POST['title']);
    $location      = sanitize($conn, $_POST['location']);
    $description   = sanitize($conn, $_POST['description']);
    $price         = (float)$_POST['price'];
    $category_id   = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $duration      = sanitize($conn, $_POST['duration']);
    $highlights    = sanitize($conn, $_POST['highlights']);
    $includes_list = sanitize($conn, $_POST['includes_list']);
    $tour_type     = sanitize($conn, $_POST['tour_type']);
    $sort_order    = (int)($_POST['sort_order'] ?? 0);

    $cat_val = $category_id ? $category_id : 'NULL';

    $update_fields = [
        "title = '$title'",
        "location = '$location'",
        "description = '$description'",
        "price = $price",
        "category_id = $cat_val",
        "duration = '$duration'",
        "highlights = '$highlights'",
        "includes_list = '$includes_list'",
        "tour_type = '$tour_type'",
        "sort_order = $sort_order"
    ];

    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'";
    }

    $sql = "UPDATE local_tours 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 local_tour_gallery (tour_id, image) VALUES ($id, '$img_name')");
            }
        }
        $_SESSION['success_msg'] = "Local tour updated successfully!";
        echo "<script>window.location='local-tours.php';</script>";
        exit();
    }
    
    // Re-populate tour from POST
    $tour['title'] = $_POST['title'];
    $tour['location'] = $_POST['location'];
    $tour['description'] = $_POST['description'];
    $tour['price'] = $_POST['price'];
    $tour['category_id'] = $_POST['category_id'] ?? '';
    $tour['duration'] = $_POST['duration'];
    $tour['highlights'] = $_POST['highlights'];
    $tour['includes_list'] = $_POST['includes_list'];
    $tour['tour_type'] = $_POST['tour_type'];
    $tour['sort_order'] = $_POST['sort_order'];
}

// Fetch categories
$categories = $conn->query("SELECT * FROM local_tour_categories ORDER BY sort_order ASC, name ASC");
// Re-fetch gallery if POST was done (it was rewound)
$gallery = $conn->query("SELECT * FROM local_tour_gallery WHERE tour_id = $id");
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <a href="local-tours.php" class="text-decoration-none text-muted small"><i class="fas fa-arrow-left me-1"></i> Back to Local Tours</a>
            <h2 class="fw-bold mb-0 mt-1">Edit Local Tour</h2>
        </div>
    </div>

    <form method="POST" enctype="multipart/form-data">

        <!-- Basic Info -->
        <div class="card border-0 shadow-sm mb-4" style="border-radius: 20px;">
            <div class="card-body p-4">
                <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">
                    <i class="fas fa-info-circle me-2"></i>1. Basic Information
                </h5>
                <div class="row g-4">
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-muted small text-uppercase">Tour Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control form-control-lg border-0 bg-light"
                               value="<?= htmlspecialchars($tour['title']) ?>" style="border-radius: 12px;" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold text-muted small text-uppercase">Category</label>
                        <select name="category_id" class="form-select form-select-lg border-0 bg-light" style="border-radius: 12px;">
                            <option value="">— No Category —</option>
                            <?php if ($categories && $categories->num_rows > 0): ?>
                                <?php while ($cat = $categories->fetch_assoc()): ?>
                                <option value="<?= $cat['id'] ?>" <?= ($tour['category_id'] == $cat['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($cat['name']) ?>
                                </option>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <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;">
                            <?php
                            $types = ['day-tour' => 'Day Tour', 'overnight' => 'Overnight Tour', 'multi-day' => 'Multi-Day Tour', 'private' => 'Private Tour'];
                            foreach ($types as $val => $label):
                            ?>
                            <option value="<?= $val ?>" <?= (($tour['tour_type'] ?? 'day-tour') == $val) ? 'selected' : '' ?>>
                                <?= $label ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Location <span class="text-danger">*</span></label>
                        <input type="text" name="location" class="form-control border-0 bg-light py-3"
                               value="<?= htmlspecialchars($tour['location']) ?>" style="border-radius: 12px;" required>
                    </div>
                    <div class="col-md-4">
                        <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"
                               placeholder="e.g. 1 Day, 2 Days / 1 Night"
                               value="<?= htmlspecialchars($tour['duration'] ?? '') ?>" style="border-radius: 12px;">
                    </div>
                    <div class="col-md-2">
                        <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)$tour['price'] ?>" style="border-radius: 0 12px 12px 0;" required>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <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="<?= $tour['sort_order'] ?? 0 ?>" style="border-radius: 12px;">
                    </div>
                </div>
            </div>
        </div>

        <!-- Detailed Content -->
        <div class="card border-0 shadow-sm mb-4" style="border-radius: 20px;">
            <div class="card-body p-4">
                <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">
                    <i class="fas fa-align-left me-2"></i>2. Detailed Content
                </h5>
                <div class="row g-4">
                    <div class="col-md-12">
                        <label class="form-label fw-bold text-muted small text-uppercase">Full Description</label>
                        <textarea name="description" class="form-control border-0 bg-light" rows="5"
                                  style="border-radius: 15px;" required><?= htmlspecialchars($tour['description']) ?></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-muted small text-uppercase">Tour Highlights</label>
                        <textarea name="highlights" class="form-control border-0 bg-light" rows="6"
                                  style="border-radius: 15px;"><?= htmlspecialchars($tour['highlights'] ?? '') ?></textarea>
                        <small class="text-muted">One highlight per line</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-muted small text-uppercase">What's Included</label>
                        <textarea name="includes_list" class="form-control border-0 bg-light" rows="6"
                                  style="border-radius: 15px;"><?= htmlspecialchars($tour['includes_list'] ?? '') ?></textarea>
                        <small class="text-muted">One item per line</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Media -->
        <div class="card border-0 shadow-sm mb-4" style="border-radius: 20px;">
            <div class="card-body p-4">
                <h5 class="fw-bold text-primary mb-4 border-bottom pb-2">
                    <i class="fas fa-images me-2"></i>3. Media
                </h5>
                <div class="row g-4">
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-muted small text-uppercase">Change 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 ($tour['main_image']): ?>
                        <div class="mt-2 p-2 bg-light rounded-3 d-inline-block">
                            <img src="../uploads/<?= htmlspecialchars($tour['main_image']) ?>" height="60" class="rounded">
                            <span class="ms-2 small text-muted">Current cover image</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <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>

                <?php if ($gallery && $gallery->num_rows > 0): ?>
                <div class="mt-4">
                    <label class="form-label fw-bold text-muted small text-uppercase">Current Gallery</label>
                    <div class="d-flex flex-wrap gap-2 mt-2">
                        <?php while ($g = $gallery->fetch_assoc()): ?>
                        <div style="position: relative; display: inline-block;">
                            <img src="../uploads/<?= htmlspecialchars($g['image']) ?>" height="70" class="rounded">
                            <a href="delete-gallery-image.php?table=local_tour_gallery&id=<?= $g['id'] ?>&return=edit-local-tour.php?id=<?= $id ?>"
                               class="btn btn-danger btn-sm rounded-circle position-absolute top-0 end-0"
                               style="width:20px;height:20px;font-size:10px;padding:0;line-height:20px;"
                               onclick="return confirm('Delete this image?')">&times;</a>
                        </div>
                        <?php endwhile; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="text-end pb-4">
            <a href="local-tours.php" class="btn btn-light rounded-pill px-4 py-3 me-2">Cancel</a>
            <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 LOCAL TOUR
            </button>
        </div>
    </form>
</div>

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