<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. INITIALIZE VARIABLES & DETERMINE MODE (ADD/EDIT)
$edit_mode = false;
$hotel = []; // Initialize empty array to prevent errors in 'add' mode
$page_error = '';

$hotel_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($hotel_id) {
    $edit_mode = true;
}

// 3. FETCH DATA FOR FORM (PARTNERS & EXISTING HOTEL IF EDITING)
// Fetch partners for the dropdown
$partners_result = $conn->query("SELECT id, full_name FROM users WHERE role LIKE '%_partner' ORDER BY full_name ASC");

if ($edit_mode) {
    $stmt = $conn->prepare("SELECT * FROM hotels WHERE id = ?");
    $stmt->bind_param("i", $hotel_id);
    $stmt->execute();
    $hotel = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$hotel) {
        $page_error = "The requested hotel could not be found.";
    }
}

// 4. HANDLE FORM SUBMISSION (CREATE OR UPDATE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize data
    $name = trim($_POST['name']);
    $location = trim($_POST['location']);
    $star_rating = filter_input(INPUT_POST, 'star_rating', FILTER_VALIDATE_INT);
    $partner_id = filter_input(INPUT_POST, 'partner_id', FILTER_VALIDATE_INT);
    $is_published = isset($_POST['is_published']) ? 1 : 0;
    $description = $_POST['description']; // Assuming TinyMCE cleans its own output
    $amenities = isset($_POST['amenities']) && is_array($_POST['amenities']) ? implode(',', $_POST['amenities']) : '';
    
    // Handle file upload
    $main_image_url = $_POST['current_image_url'] ?? ''; // Keep old image by default
    if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/hotels/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
        $filename = 'hotel-' . uniqid() . '-' . basename($_FILES['main_image']['name']);
        $target_path = $upload_dir . $filename;
        if (move_uploaded_file($_FILES['main_image']['tmp_name'], $target_path)) {
            $main_image_url = 'uploads/hotels/' . $filename;
        } else {
            $_SESSION['error_message'] = "Error uploading file.";
        }
    }

    if (empty($name) || empty($location)) {
        $_SESSION['error_message'] = "Hotel Name and Location are required.";
    } else {
        if ($edit_mode) { // UPDATE
            $stmt = $conn->prepare("UPDATE hotels SET name=?, location=?, star_rating=?, partner_id=?, is_published=?, description=?, amenities=?, main_image_url=? WHERE id=?");
            $stmt->bind_param("ssiiisssi", $name, $location, $star_rating, $partner_id, $is_published, $description, $amenities, $main_image_url, $hotel_id);
            if($stmt->execute()) $_SESSION['success_message'] = "Hotel updated successfully."; else $_SESSION['error_message'] = "Error updating hotel.";
            $stmt->close();
        } else { // INSERT
            $stmt = $conn->prepare("INSERT INTO hotels (name, location, star_rating, partner_id, is_published, description, amenities, main_image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssiiisss", $name, $location, $star_rating, $partner_id, $is_published, $description, $amenities, $main_image_url);
            if($stmt->execute()) $_SESSION['success_message'] = "Hotel created successfully."; else $_SESSION['error_message'] = "Error creating hotel.";
            $stmt->close();
        }
        header("Location: manage-hotels.php");
        exit();
    }
}

// Pre-fill amenities array for the form
$hotel_amenities = isset($hotel['amenities']) ? explode(',', $hotel['amenities']) : [];


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($settings['api_tinymce'] ?? 'no-api-key'); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: 'textarea#description',
    plugins: 'code table lists link autoresize',
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | link',
    skin: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'oxide-dark' : 'oxide'),
    content_css: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default'),
    height: 400
  });
</script>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="manage-hotels.php" class="btn btn-outline-danger">Return to Hotels List</a></div>
<?php else: ?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <div>
            <h1 class="h2"><?php echo $edit_mode ? 'Edit Hotel' : 'Add New Hotel'; ?></h1>
            <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="manage-hotels.php">Hotels</a></li><li class="breadcrumb-item active"><?php echo $edit_mode ? htmlspecialchars($hotel['name']) : 'New'; ?></li></ol></nav>
        </div>
    </div>
    
    <form method="POST" action="edit-hotel.php<?php echo $edit_mode ? '?id=' . $hotel_id : ''; ?>" enctype="multipart/form-data">
        <div class="card shadow-sm">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="hotelTab" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" id="basic-info-tab" data-bs-toggle="tab" data-bs-target="#basic-info" type="button">Basic Info</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="details-tab" data-bs-toggle="tab" data-bs-target="#details" type="button">Description & Amenities</button></li>
                </ul>
            </div>
            
            <div class="card-body">
                <div class="tab-content" id="hotelTabContent">
                    <div class="tab-pane fade show active" id="basic-info" role="tabpanel">
                        <div class="row g-4">
                            <div class="col-md-8">
                                <div class="mb-3"><label class="form-label">Hotel Name <span class="text-danger">*</span></label><input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($hotel['name'] ?? ''); ?>" required></div>
                                <div class="mb-3"><label class="form-label">Location (City, Country) <span class="text-danger">*</span></label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($hotel['location'] ?? ''); ?>" required></div>
                                <div class="row">
                                    <div class="col-sm-6 mb-3"><label class="form-label">Star Rating</label><select name="star_rating" class="form-select"><option value="">Select rating...</option><?php for($i=5; $i>=1; $i--): ?><option value="<?php echo $i; ?>" <?php if(isset($hotel['star_rating']) && $hotel['star_rating'] == $i) echo 'selected'; ?>><?php echo $i; ?> Star<?php echo $i > 1 ? 's' : ''; ?></option><?php endfor; ?></select></div>
                                    <div class="col-sm-6 mb-3"><label class="form-label">Partner (Owner)</label><select name="partner_id" class="form-select"><option value="0">Admin (No Partner)</option><?php while($p = $partners_result->fetch_assoc()): ?><option value="<?php echo $p['id']; ?>" <?php if(isset($hotel['partner_id']) && $hotel['partner_id'] == $p['id']) echo 'selected'; ?>><?php echo htmlspecialchars($p['full_name']); ?></option><?php endwhile; ?></select></div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3"><label class="form-label">Main Image</label><input class="form-control" type="file" name="main_image" id="main-image-input"><input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($hotel['main_image_url'] ?? ''); ?>"></div>
                                <?php $image_src = !empty($hotel['main_image_url']) ? '../' . htmlspecialchars($hotel['main_image_url']) : 'https://via.placeholder.com/300x200.png?text=No+Image'; ?>
                                <img id="image-preview" src="<?php echo $image_src; ?>" class="img-fluid rounded border" alt="Image Preview">
                                <div class="form-check form-switch mt-4"><input class="form-check-input" type="checkbox" role="switch" id="is_published" name="is_published" <?php if(isset($hotel['is_published']) && $hotel['is_published']) echo 'checked'; ?>><label class="form-check-label" for="is_published">Published (Visible on site)</label></div>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="details" role="tabpanel">
                        <div class="mb-3"><label class="form-label">Description</label><textarea id="description" name="description" rows="10"><?php echo htmlspecialchars($hotel['description'] ?? ''); ?></textarea></div>
                        <h5 class="mt-4">Amenities</h5><hr>
                        <div class="row">
                            <?php $common_amenities = ['Wifi', 'Pool', 'Parking', 'Restaurant', 'Pet Friendly', 'Room Service', 'Fitness Center', 'Spa']; ?>
                            <?php foreach($common_amenities as $amenity): ?>
                            <div class="col-md-3 col-sm-6"><div class="form-check"><input class="form-check-input" type="checkbox" name="amenities[]" value="<?php echo $amenity; ?>" id="amenity-<?php echo str_replace(' ','',$amenity); ?>" <?php if(in_array($amenity, $hotel_amenities)) echo 'checked'; ?>><label class="form-check-label" for="amenity-<?php echo str_replace(' ','',$amenity); ?>"><?php echo $amenity; ?></label></div></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-4 d-flex justify-content-end gap-2">
            <a href="manage-hotels.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-1"></i> <?php echo $edit_mode ? 'Update Hotel' : 'Save Hotel'; ?></button>
        </div>
    </form>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('main-image-input');
    const imagePreview = document.getElementById('image-preview');
    if (imageInput) {
        imageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    imagePreview.src = event.target.result;
                }
                reader.readAsDataURL(e.target.files[0]);
            }
        });
    }
});
</script>

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