<?php
include 'header.php'; // Includes partner session check and all necessary variables

// Security: This page is for HOTEL partners only
if ($partner_role !== 'hotel_partner') { 
    header("Location: index.php"); // Redirect to dashboard if not a hotel partner
    exit(); 
}
require_once '../includes/image-resizer.php'; 

$message = '';
// --- ACTION HANDLING (scoped to the logged-in partner) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- DELETE HOTEL ---
    if (isset($_POST['delete_hotel'])) {
        $hotel_id_to_delete = intval($_POST['id']);
        // Add full deletion logic here for associated rooms, images, etc. if needed
        $stmt = $conn->prepare("DELETE FROM hotels WHERE id = ? AND partner_id = ?");
        $stmt->bind_param("ii", $hotel_id_to_delete, $partner_id);
        $stmt->execute();
        $message = '<div class="alert alert-success">Hotel has been deleted.</div>';
    }
    // --- 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']);
        $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-partner" . $partner_id . "-" . 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 (check ownership)
            $stmt = $conn->prepare("UPDATE hotels SET name=?, location=?, description=?, star_rating=?, amenities=?, main_image_url=? WHERE id=? AND partner_id=?");
            $stmt->bind_param("sssisssi", $name, $location, $description, $star_rating, $amenities, $main_image_url, $id, $partner_id);
            $message = '<div class="alert alert-success">Hotel updated successfully.</div>';
        } else { // Insert (assign ownership)
            $stmt = $conn->prepare("INSERT INTO hotels (partner_id, name, location, description, star_rating, amenities, main_image_url) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssiss", $partner_id, $name, $location, $description, $star_rating, $amenities, $main_image_url);
            $message = '<div class="alert alert-success">New hotel added successfully.</div>';
        }
        $stmt->execute();
        $stmt->close();
    }
}

// Fetch hotel for editing if an ID is provided
$edit_hotel = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM hotels WHERE id = ? AND partner_id = ?");
    $stmt->bind_param("ii", $id, $partner_id);
    $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">My Hotels</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm mb-4">
    <div class="card-header"><?php echo $edit_hotel ? 'Edit Hotel Details' : 'Add a New Hotel'; ?></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $edit_hotel['id'] ?? 0; ?>">
            <div class="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="mb-3"><label>Location</label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($edit_hotel['location'] ?? ''); ?>" required></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 (e.g., Wifi, Pool, Gym)</small></div>
            </div>
            <div class="mb-3">
                <label>Main Hotel 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'] ?? ''); ?>">
            </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>

<div class="card shadow-sm">
    <div class="card-header fw-bold">My Hotel Listings</div>
    <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
                $stmt_list = $conn->prepare("SELECT * FROM hotels WHERE partner_id = ? ORDER BY id DESC");
                $stmt_list->bind_param("i", $partner_id);
                $stmt_list->execute();
                $result = $stmt_list->get_result();
                if ($result->num_rows > 0):
                    while($row = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo htmlspecialchars($row['location']); ?></td>
                    <td><?php echo str_repeat('⭐', $row['star_rating']); ?></td>
                    <td class="text-center">
                        <div class="btn-group">
                            <a href="manage-rooms.php?hotel_id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info">Manage Rooms & Rates</a>
                            <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit Hotel</a>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this hotel?');">
                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                <button type="submit" name="delete_hotel" class="btn btn-sm btn-danger">Delete</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php 
                    endwhile; 
                else: 
                ?>
                    <tr><td colspan="4" class="text-center text-muted p-4">You have not added any hotels yet. Use the form above to add your first one.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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