<?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 successfully.</div>';
    }
    // --- ACTION: DELETE AN ENTIRE HOTEL ---
    elseif (isset($_POST['delete_hotel'])) {
        $hotel_id_to_delete = intval($_POST['hotel_id']);
        $conn->begin_transaction();
        try {
            $stmt_main_img = $conn->query("SELECT main_image_url FROM hotels WHERE id = $hotel_id_to_delete");
            if ($stmt_main_img->num_rows > 0) {
                if ($main_img_path = $stmt_main_img->fetch_assoc()['main_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 = $hotel_id_to_delete AND item_type = 'hotel'");
            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 = $hotel_id_to_delete AND item_type = 'hotel'");
            $conn->query("DELETE FROM hotel_room_rates WHERE room_id IN (SELECT id FROM hotel_rooms WHERE hotel_id = $hotel_id_to_delete)");
            $conn->query("DELETE FROM hotel_rooms WHERE hotel_id = $hotel_id_to_delete");
            $conn->query("DELETE FROM hotels WHERE id = $hotel_id_to_delete");
            $conn->commit();
            $message = '<div class="alert alert-success">Hotel and all associated data have been deleted.</div>';
        } catch (mysqli_sql_exception $e) { $conn->rollback(); $message = '<div class="alert alert-danger">Error deleting hotel: ' . $e->getMessage() . '</div>'; }
    } 
    // --- ACTION: SAVE (ADD/EDIT) A HOTEL ---
    elseif (isset($_POST['save_hotel'])) {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $location = trim($_POST['location']);
        $description = trim($_POST['description']);
        $star_rating = intval($_POST['star_rating']);
        $is_recommended = isset($_POST['is_recommended']) ? 1 : 0;
        $amenities = trim($_POST['amenities']);
        $main_image_url = $_POST['current_image_url'] ?? '';

        if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] == 0) {
            $target_dir = "../uploads/hotels/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "hotel-main-" . uniqid() . basename($_FILES["main_image"]["name"]);
            if (resizeImage($_FILES["main_image"]["tmp_name"], $target_file, 1200, 800)) { $main_image_url = str_replace('../', '', $target_file); }
        }

        if ($id > 0) { // Update
            $stmt = $conn->prepare("UPDATE hotels SET name=?, location=?, description=?, star_rating=?, is_recommended=?, amenities=?, main_image_url=? WHERE id=?");
            $stmt->bind_param("sssisssi", $name, $location, $description, $star_rating, $is_recommended, $amenities, $main_image_url, $id);
        } else { // Insert
            $stmt = $conn->prepare("INSERT INTO hotels (name, location, description, star_rating, is_recommended, amenities, main_image_url) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssisss", $name, $location, $description, $star_rating, $is_recommended, $amenities, $main_image_url);
        }
        $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])) {
            $target_dir = "../uploads/hotels/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 = "hotel-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 (?, 'hotel', ?)");
                        $stmt_gallery->bind_param("is", $item_id_context, $gallery_image_url);
                        $stmt_gallery->execute();
                    }
                }
            }
        }
        $message = '<div class="alert alert-success">Hotel saved successfully.</div>';
    }
}

// Fetch hotel for editing
$edit_hotel = null;
if ($item_id_context > 0) {
    $stmt = $conn->prepare("SELECT * FROM hotels WHERE id = ?");
    $stmt->bind_param("i", $item_id_context);
    $stmt->execute();
    $edit_hotel = $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 Hotels</h1></div>
<?php echo $message; ?>
<form method="POST" enctype="multipart/form-data" action="manage-hotels.php?edit=<?php echo $edit_hotel['id'] ?? 0; ?>">
    <input type="hidden" name="id" value="<?php echo $edit_hotel['id'] ?? 0; ?>">
    <div class="card mb-4 shadow-sm">
        <div class="card-header"><?php echo $edit_hotel ? 'Edit Hotel Details' : 'Add New Hotel'; ?></div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3"><label>Hotel Name</label><input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($edit_hotel['name'] ?? ''); ?>" required></div>
                <div class="col-md-6 mb-3"><label>Location</label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($edit_hotel['location'] ?? ''); ?>" required></div>
            </div>
            <div class="mb-3"><label>Description</label><textarea class="form-control" name="description" rows="4" required><?php echo htmlspecialchars($edit_hotel['description'] ?? ''); ?></textarea></div>
            <div class="row">
                <div class="col-md-4 mb-3"><label>Star Rating (1-5)</label><input type="number" class="form-control" name="star_rating" min="1" max="5" value="<?php echo $edit_hotel['star_rating'] ?? 3; ?>" required></div>
                <div class="col-md-8 mb-3"><label>Amenities</label><input type="text" class="form-control" name="amenities" value="<?php echo htmlspecialchars($edit_hotel['amenities'] ?? ''); ?>"><small class="text-muted">Comma-separated</small></div>
            </div>
            <div class="mb-3"><label>Main Image</label><input type="file" class="form-control" name="main_image" accept="image/*"><input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($edit_hotel['main_image_url'] ?? ''); ?>"><?php if (!empty($edit_hotel['main_image_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($edit_hotel['main_image_url']); ?>" style="max-height: 80px;" class="img-thumbnail"></div><?php endif; ?></div>
            <div class="mb-3"><label>Add Gallery Images</label><input type="file" class="form-control" name="gallery_images[]" multiple accept="image/*"></div>
            <div class="mb-3 form-check form-switch"><input type="checkbox" class="form-check-input" id="is_recommended" name="is_recommended" value="1" <?php echo (isset($edit_hotel['is_recommended']) && $edit_hotel['is_recommended']) ? 'checked' : ''; ?>><label class="form-check-label" for="is_recommended">Recommend on homepage?</label></div>
            <button type="submit" name="save_hotel" class="btn btn-primary"><?php echo $edit_hotel ? 'Save Changes' : 'Add Hotel'; ?></button>
            <?php if ($edit_hotel): ?><a href="manage-hotels.php" class="btn btn-secondary">Cancel Edit</a><?php endif; ?>
        </form>
    </div>
</div>

<?php if ($edit_hotel): ?>
<div class="card mt-4 shadow-sm">
    <div class="card-header">Image Gallery for <?php echo htmlspecialchars($edit_hotel['name']); ?></div>
    <div class="card-body"><div class="row">
        <?php $stmt_gallery = $conn->prepare("SELECT * FROM galleries WHERE item_id = ? AND item_type = 'hotel'"); $stmt_gallery->bind_param("i", $edit_hotel['id']); $stmt_gallery->execute(); $gallery_result = $stmt_gallery->get_result(); if ($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-hotels.php?edit=<?php echo $edit_hotel['id']; ?>" onsubmit="return confirm('Delete image?');"><input type="hidden" name="id" value="<?php echo $edit_hotel['id']; ?>"><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">Hotel Listings</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark"><tr><th>Hotel Name</th><th>Location</th><th>Rating</th><th class="text-center">Actions</th></tr></thead>
                <tbody>
                <?php $result = $conn->query("SELECT * FROM hotels ORDER BY name ASC"); while ($hotel = $result->fetch_assoc()): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($hotel['name']); ?></strong></td>
                        <td><?php echo htmlspecialchars($hotel['location']); ?></td>
                        <td><?php echo str_repeat('⭐', $hotel['star_rating']); ?></td>
                        <td class="text-center">
                            <div class="btn-group">
                                <a href="manage-rooms.php?hotel_id=<?php echo $hotel['id']; ?>" class="btn btn-sm btn-info">Manage Rooms</a>
                                <a href="?edit=<?php echo $hotel['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Delete this hotel and ALL data?');"><input type="hidden" name="hotel_id" value="<?php echo $hotel['id']; ?>"><button type="submit" name="delete_hotel" class="btn btn-sm btn-danger">Delete</button></form>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
