<?php
include 'admin-header.php';
require_once '../includes/image-resizer.php'; 

$message = '';
// Use a single variable to track the item being edited.
$item_id_context = intval($_GET['edit'] ?? $_POST['id'] ?? 0);

// --- ACTION HANDLING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- ACTION: DELETE A SINGLE GALLERY IMAGE ---
    if (isset($_POST['delete_gallery_image'])) {
        $image_id_to_delete = intval($_POST['image_id']);
        $stmt_img = $conn->prepare("SELECT image_url FROM galleries WHERE id = ?");
        $stmt_img->bind_param("i", $image_id_to_delete);
        $stmt_img->execute();
        if($row_img = $stmt_img->get_result()->fetch_assoc()) {
            if(!empty($row_img['image_url']) && file_exists('../' . $row_img['image_url'])) { unlink('../' . $row_img['image_url']); }
        }
        $stmt_del = $conn->prepare("DELETE FROM galleries WHERE id = ?");
        $stmt_del->bind_param("i", $image_id_to_delete);
        $stmt_del->execute();
        $message = '<div class="alert alert-success">Gallery image deleted.</div>';
    }
    // --- ACTION: DELETE AN ENTIRE TOUR/SERVICE ---
    elseif (isset($_POST['delete_tour'])) {
        $item_id_to_delete = intval($_POST['id']);
        $conn->begin_transaction();
        try {
            $stmt_main_img = $conn->query("SELECT image_url FROM tours WHERE id = $item_id_to_delete");
            if ($stmt_main_img->num_rows > 0) {
                if ($main_img_path = $stmt_main_img->fetch_assoc()['image_url']) { if (file_exists('../' . $main_img_path)) unlink('../' . $main_img_path); }
            }
            $stmt_gallery_imgs = $conn->query("SELECT image_url FROM galleries WHERE item_id = $item_id_to_delete AND item_type = 'tour'");
            while($img = $stmt_gallery_imgs->fetch_assoc()) {
                if (!empty($img['image_url']) && file_exists('../' . $img['image_url'])) unlink('../' . $img['image_url']);
            }
            $conn->query("DELETE FROM galleries WHERE item_id = $item_id_to_delete AND item_type = 'tour'");
            $conn->query("DELETE FROM tours WHERE id = $item_id_to_delete");
            $conn->commit();
            $message = '<div class="alert alert-success">Item and all its images have been deleted.</div>';
        } catch (mysqli_sql_exception $e) { $conn->rollback(); $message = '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>'; }
    } 
    // --- ACTION: SAVE (ADD/EDIT) A TOUR/SERVICE ---
    elseif (isset($_POST['save_tour'])) {
        $id = intval($_POST['id'] ?? 0);
        $category = $_POST['category'];
        $title = trim($_POST['title']);
        $location = trim($_POST['location']);
        $description = trim($_POST['description']);
        $price = floatval($_POST['price']);
        $duration_days = intval($_POST['duration_days']);
        $is_featured = isset($_POST['is_featured']) ? 1 : 0;
        $image_url = $_POST['current_image'] ?? '';

        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $upload_dir = ($category == 'Service') ? 'services' : 'tours';
            $target_dir = "../uploads/$upload_dir/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "item-main-" . uniqid() . "." . basename($_FILES["image"]["name"]);
            if (resizeImage($_FILES["image"]["tmp_name"], $target_file, 1200, 800)) { $image_url = str_replace('../', '', $target_file); }
        }

        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE tours SET category=?, title=?, location=?, description=?, price=?, duration_days=?, image_url=?, is_featured=? WHERE id=?");
            $stmt->bind_param("ssssdisii", $category, $title, $location, $description, $price, $duration_days, $image_url, $is_featured, $id);
        } else {
            $stmt = $conn->prepare("INSERT INTO tours (category, title, location, description, price, duration_days, image_url, is_featured) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssdisi", $category, $title, $location, $description, $price, $duration_days, $image_url, $is_featured);
        }
        $stmt->execute();
        $item_id_context = $id > 0 ? $id : $conn->insert_id;
        $stmt->close();
        
        if ($item_id_context > 0 && isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {
            $upload_dir = ($category == 'Service') ? 'services' : 'tours';
            $target_dir = "../uploads/$upload_dir/gallery/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['gallery_images']['error'][$key] == 0) {
                    $file_name = "item-gallery-" . $item_id_context . "-" . uniqid() . "." . basename($_FILES['gallery_images']['name'][$key]);
                    $target_file = $target_dir . $file_name;
                    if (resizeImage($tmp_name, $target_file, 1200, 800)) {
                        $gallery_image_url = str_replace('../', '', $target_file);
                        $stmt_gallery = $conn->prepare("INSERT INTO galleries (item_id, item_type, image_url) VALUES (?, 'tour', ?)");
                        $stmt_gallery->bind_param("is", $item_id_context, $gallery_image_url);
                        $stmt_gallery->execute();
                    }
                }
            }
        }
        $message = '<div class="alert alert-success">Item saved successfully.</div>';
    }
}

// Fetch item for editing
$edit_item = null;
if ($item_id_context > 0) {
    $stmt = $conn->prepare("SELECT * FROM tours WHERE id = ?");
    $stmt->bind_param("i", $item_id_context);
    $stmt->execute();
    $edit_item = $stmt->get_result()->fetch_assoc();
}
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Tours & Services</h1>
</div>
<?php echo $message; ?>

<form method="POST" enctype="multipart/form-data" action="manage-tours.php?edit=<?php echo $edit_item['id'] ?? 0; ?>">
    <input type="hidden" name="id" value="<?php echo $edit_item['id'] ?? 0; ?>">
    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow-sm mb-4">
                <div class="card-header"><?php echo $edit_item ? 'Edit Item' : 'Add New Item'; ?></div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label>Category</label><select name="category" class="form-select" required><option value="Tour" <?php if(isset($edit_item['category']) && $edit_item['category'] == 'Tour') echo 'selected'; ?>>Tour Package</option><option value="Service" <?php if(isset($edit_item['category']) && $edit_item['category'] == 'Service') echo 'selected'; ?>>Custom Service</option></select></div>
                        <div class="col-md-6 mb-3"><label>Title</label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($edit_item['title'] ?? ''); ?>" required></div>
                    </div>
                    <div class="mb-3 autocomplete-container"><label>Location / Area</label><input type="text" id="tourLocation" class="form-control" name="location" value="<?php echo htmlspecialchars($edit_item['location'] ?? 'Nationwide'); ?>" required autocomplete="off"></div>
                    <div class="mb-3"><label>Description</label><textarea class="form-control" name="description" rows="5" required><?php echo htmlspecialchars($edit_item['description'] ?? ''); ?></textarea></div>
                    <div class="row">
                        <div class="col-md-6 mb-3"><label>Price ₱</label><input type="number" step="0.01" class="form-control" name="price" value="<?php echo $edit_item['price'] ?? ''; ?>" required></div>
                        <div class="col-md-6 mb-3"><label>Duration (Days)</label><input type="number" class="form-control" name="duration_days" value="<?php echo $edit_item['duration_days'] ?? 0; ?>"><small class="text-muted">Enter 0 for services.</small></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header">Publishing & Images</div>
                <div class="card-body">
                    <div class="mb-3 form-check form-switch"><input type="checkbox" class="form-check-input" id="is_featured" name="is_featured" value="1" <?php echo (isset($edit_item['is_featured']) && $edit_item['is_featured'] == 1) ? 'checked' : ''; ?>><label class="form-check-label" for="is_featured">Feature on homepage?</label></div>
                    <div class="mb-3"><label>Main Image</label><input type="file" class="form-control" name="image" accept="image/*"><input type="hidden" name="current_image" value="<?php echo htmlspecialchars($edit_item['image_url'] ?? ''); ?>"><?php if (!empty($edit_item['image_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($edit_item['image_url']); ?>" class="img-thumbnail" style="max-height:100px;"></div><?php endif; ?></div>
                    <div class="mb-3"><label>Add Gallery Images</label><input type="file" class="form-control" name="gallery_images[]" accept="image/*" multiple></div>
                    <div class="d-grid"><button type="submit" name="save_tour" class="btn btn-primary"><?php echo $edit_item ? 'Save Changes' : 'Add Item'; ?></button></div>
                    <?php if ($edit_item): ?><a href="manage-tours.php" class="btn btn-secondary d-block mt-2">Cancel Edit</a><?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</form>

<?php if ($edit_item): ?>
<div class="card mt-4 shadow-sm">
    <div class="card-header">Image Gallery for <?php echo htmlspecialchars($edit_item['title']); ?></div>
    <div class="card-body"><div class="row">
    <?php 
    $stmt_gallery = $conn->prepare("SELECT * FROM galleries WHERE item_id = ? AND item_type = 'tour' ORDER BY id DESC");
    $stmt_gallery->bind_param("i", $edit_item['id']);
    $stmt_gallery->execute();
    $gallery_result = $stmt_gallery->get_result();

    if ($gallery_result && $gallery_result->num_rows > 0): while($img = $gallery_result->fetch_assoc()): ?>
        <div class="col-xl-2 col-lg-3 col-md-4 col-6 mb-3 text-center">
            <img src="../<?php echo htmlspecialchars($img['image_url']); ?>" class="img-thumbnail mb-2" style="height: 120px; width:100%; object-fit: cover;">
            <form method="POST" action="manage-tours.php?edit=<?php echo $edit_item['id']; ?>" onsubmit="return confirm('Delete this image?');"><input type="hidden" name="image_id" value="<?php echo $img['id']; ?>"><button type="submit" name="delete_gallery_image" class="btn btn-danger btn-sm">Delete</button></form>
        </div>
    <?php endwhile; else: echo '<p class="text-muted text-center">No gallery images uploaded yet.</p>'; endif; ?>
    </div></div>
</div>
<?php endif; ?>

<div class="card mt-4 shadow-sm">
    <div class="card-header">Existing Tours & Services</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead><tr><th>Category</th><th>Title</th><th>Location</th><th>Actions</th></tr></thead>
                <tbody>
                <?php $result = $conn->query("SELECT id, category, title, location FROM tours ORDER BY id DESC"); while($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><span class="badge <?php echo $row['category'] == 'Service' ? 'bg-info' : 'bg-primary'; ?>"><?php echo $row['category']; ?></span></td>
                        <td><?php echo htmlspecialchars($row['title']); ?></td>
                        <td><?php echo htmlspecialchars($row['location']); ?></td>
                        <td>
                            <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this item?');"><input type="hidden" name="id" value="<?php echo $row['id']; ?>"><button type="submit" name="delete_tour" class="btn btn-sm btn-danger">Delete</button></form>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    activateAutocomplete('tourLocation', 'tour_location');
});
</script>

<?php include 'admin-footer.php'; ?>
