<?php
include 'db.php';

if(isset($_POST['submit'])){
    // 1. Basic Details
    $hotel_name    = $_POST['hotel_name'] ?? '';
    $owner_name    = $_POST['owner_name'] ?? '';
    $owner_number  = $_POST['owner_number'] ?? '';
    $owner_number_2 = $_POST['owner_number_2'] ?? ''; // Second contact
    $hotel_rating  = $_POST['hotel_type'] ?? ''; 
    $address       = $_POST['address'] ?? '';
    $floors        = $_POST['floors'] ?? 0;
    $total_rooms   = $_POST['total_rooms'] ?? 0;
    $facilities    = $_POST['facilities'] ?? ''; 
    $amenities     = $_POST['amenities'] ?? '';
    $restaurant    = $_POST['restaurant'] ?? 'No';
    $weekday_rate  = 0;
    $weekend_rate  = 0;
    $gst_no        = $_POST['gst_no'] ?? '';
    
    // 2. Custom Fields (JSON)
    $custom_keys = $_POST['custom_keys'] ?? [];
    $custom_values = $_POST['custom_values'] ?? [];
    $extra_data = [];

    // Store second contact in extra data
    if(!empty($owner_number_2)) $extra_data['contact_2'] = $owner_number_2;

    // Handle Hotel Logo Upload
    $upload_dir = "uploads/";
    if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
    
    if(isset($_FILES['hotel_logo']) && $_FILES['hotel_logo']['error'] == 0){
        $logo_ext = pathinfo($_FILES['hotel_logo']['name'], PATHINFO_EXTENSION);
        $logo_name = "logo_" . time() . "." . $logo_ext;
        move_uploaded_file($_FILES['hotel_logo']['tmp_name'], $upload_dir . $logo_name);
        $extra_data['hotel_logo'] = $upload_dir . $logo_name;
    }

    for($i = 0; $i < count($custom_keys); $i++){
        $key = trim($custom_keys[$i]);
        $val = trim($custom_values[$i]);
        if(!empty($key)) $extra_data[$key] = $val;
    }
    $json_data = !empty($extra_data) ? json_encode($extra_data) : null;
    $room_entries = [];

    function cleanName($string) {
        return strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', trim($string)));
    }
    $safe_hotel_name = cleanName($hotel_name);

    if(isset($_POST['rooms']) && is_array($_POST['rooms'])){
        foreach($_POST['rooms'] as $index => $details){
            $type    = $details['type'] ?? 'Category';
            $count   = $details['count'] ?? 0;
            $price   = $details['price'] ?? 0;
            $w_day   = $details['weekday'] ?? 0;
            $w_end   = $details['weekend'] ?? 0;
            
            $uploaded_paths = [];
            if (isset($_FILES['room_images']['name'][$index])) {
                $files = $_FILES['room_images'];
                $safe_room_type = cleanName($type);

                foreach($files['name'][$index] as $file_key => $name){
                    if($files['error'][$index][$file_key] === 0){
                        $tmp_name = $files['tmp_name'][$index][$file_key];
                        $ext = pathinfo($name, PATHINFO_EXTENSION);
                        $new_filename = $safe_hotel_name . "_" . $safe_room_type . "_" . time() . "_" . $index . "_" . $file_key . "." . $ext;
                        $target_file = $upload_dir . $new_filename;
                        
                        if(move_uploaded_file($tmp_name, $target_file)){
                            $uploaded_paths[] = $target_file;
                        }
                    }
                }
            }
            
            $img_list = !empty($uploaded_paths) ? implode(", ", $uploaded_paths) : "No Images";
            $room_entries[] = "$type: $count rooms @ ₹$price [Weekday: ₹$w_day, Weekend: ₹$w_end] (Images: $img_list)";
        }
    }
    $room_category_string = implode(" | ", $room_entries);

    $stmt = $con->prepare("INSERT INTO hotel_enquiry (hotel_name, owner_name, owner_number, hotel_star_rating, address, floors, total_rooms, room_category, facilities, amenities, restaurant, weekday_rate, weekend_rate, gst_no, extra_data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssiissssssss", $hotel_name, $owner_name, $owner_number, $hotel_rating, $address, $floors, $total_rooms, $room_category_string, $facilities, $amenities, $restaurant, $weekday_rate, $weekend_rate, $gst_no, $json_data);

    if($stmt->execute()){
        header("Location: " . $_SERVER['PHP_SELF'] . "?status=success");
        exit();
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hotel Partner Registration</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .input-focus { @apply transition-all duration-200 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-slate-50/50; }
        .img-thumb { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid #e2e8f0; }
        .delete-btn { position: absolute; top: -5px; right: -5px; background: #ef4444; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 12px; cursor: pointer; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .animate-fade-in { animation: fadeIn 0.3s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body class="bg-slate-50 min-h-screen pb-24 md:py-12 px-0 md:px-4">

<?php if(isset($_GET['status']) && $_GET['status'] == 'success'): ?>
<div class="max-w-5xl mx-auto mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-xl text-center shadow-md animate-bounce">
    <strong class="font-bold">Success!</strong> Hotel Listing saved successfully.
</div>
<?php endif; ?>

<div class="bg-white w-full max-w-5xl mx-auto md:rounded-3xl shadow-xl border border-slate-100 overflow-hidden">
    <div class="bg-slate-900 px-6 py-10 md:px-12 text-center">
        <h2 class="text-3xl font-bold text-white tracking-tight">Hotel Partner Registration</h2>
        <p class="text-slate-400 mt-2">Required fields marked with *</p>
    </div>

    <form method="post" enctype="multipart/form-data" class="p-6 md:p-12 space-y-12" onsubmit="return validateForm()">
        
        <div class="space-y-6">
            <h3 class="text-xs font-bold uppercase tracking-widest text-blue-600 border-b pb-2">Primary Details (Required)</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <input type="text" name="hotel_name" placeholder="Hotel Name *" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                <div class="grid grid-cols-2 gap-4">
                    <input type="tel" name="owner_number" placeholder="Contact (1) *" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                    <input type="tel" name="owner_number_2" placeholder="Contact (2) *" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="flex flex-col justify-center">
                    <label class="text-[10px] font-bold text-slate-400 uppercase mb-1 ml-2">Hotel Logo</label>
                    <input type="file" name="hotel_logo" accept="image/*" class="w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-blue-50 file:text-blue-700">
                </div>
                <input type="number" name="floors" placeholder="No. Of Floors" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                <input type="number" name="total_rooms" placeholder="No. Of Rooms" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
            </div>

            <div class="space-y-4">
                <div class="flex justify-between items-center">
                    <label class="text-xs font-bold uppercase text-slate-600">Room Categories & Images *</label>
                    <button type="button" onclick="addRoomCategory()" class="bg-blue-600 text-white px-3 py-1 rounded-lg text-xs font-bold">+ Add Room</button>
                </div>
                <div id="room-categories-container" class="grid grid-cols-1 md:grid-cols-2 gap-6"></div>
            </div>
        </div>

        <div class="space-y-6">
            <h3 class="text-xs font-bold uppercase tracking-widest text-slate-400 border-b pb-2">Optional Information</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <input type="text" name="owner_name" placeholder="Owner Name" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                <input type="text" name="hotel_type" placeholder="Star Rating / Type" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                <input type="text" name="gst_no" placeholder="GST Number" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus uppercase">
            </div>

            <textarea name="address" placeholder="Full Address" rows="2" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"></textarea>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <textarea name="facilities" placeholder="Facilities (e.g. WiFi, Pool)" rows="2" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"></textarea>
                <textarea name="amenities" placeholder="Amenities (e.g. AC, TV)" rows="2" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"></textarea>
            </div>

            <div class="flex justify-between items-center border-t pt-4">
                <span class="text-xs font-bold uppercase text-slate-400">Custom Fields</span>
                <button type="button" onclick="addCustomField()" class="text-blue-600 font-bold text-xs">+ Add Field</button>
            </div>
            <div id="custom-fields-container" class="space-y-3"></div>
        </div>

        <button name="submit" type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-5 rounded-2xl font-bold shadow-xl transition-all text-lg">
            Submit Listing
        </button>
    </form>
</div>

<script>
    let roomIndex = 0;
    const fileManagers = {};

    function addRoomCategory() {
        const container = document.getElementById('room-categories-container');
        const id = `room_${roomIndex}`;
        
        const card = document.createElement('div');
        card.className = "p-6 bg-white border border-slate-200 rounded-3xl space-y-4 shadow-sm relative animate-fade-in";
        card.innerHTML = `
            <button type="button" onclick="this.parentElement.remove()" class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 shadow-md">✕</button>
            <input type="text" name="rooms[${roomIndex}][type]" placeholder="Room Category Name" required class="w-full border border-slate-200 rounded-xl px-4 py-2 font-bold text-slate-800 outline-none">
            
            <div class="grid grid-cols-2 gap-4">
                <input type="number" name="rooms[${roomIndex}][count]" placeholder="Qty" class="w-full border border-slate-200 rounded-xl px-4 py-2 text-sm bg-slate-50/50 outline-none">
                <input type="number" name="rooms[${roomIndex}][price]" placeholder="Price ₹" class="w-full border border-slate-200 rounded-xl px-4 py-2 text-sm bg-slate-50/50 outline-none">
            </div>

            <div>
                <div id="preview-${id}" class="flex flex-wrap gap-2 mb-3"></div>
                <input type="file" id="real-input-${id}" name="room_images[${roomIndex}][]" class="hidden" multiple>
                <button type="button" onclick="document.getElementById('trigger-${id}').click()" class="w-full border-2 border-dashed border-slate-200 rounded-xl py-3 text-slate-400 font-bold text-[10px] uppercase hover:border-blue-400 hover:text-blue-500 transition-all">
                    + Upload Images *
                </button>
                <input type="file" id="trigger-${id}" class="hidden" multiple accept="image/*" onchange="handleFiles('${id}', ${roomIndex})">
            </div>
        `;
        
        container.appendChild(card);
        roomIndex++;
    }

    function handleFiles(id, index) {
        const trigger = document.getElementById('trigger-' + id);
        const realInput = document.getElementById('real-input-' + id);
        const preview = document.getElementById('preview-' + id);
        if (!fileManagers[id]) fileManagers[id] = new DataTransfer();

        Array.from(trigger.files).forEach(file => {
            fileManagers[id].items.add(file);
            const reader = new FileReader();
            reader.onload = (e) => {
                const div = document.createElement('div');
                div.className = 'relative';
                div.innerHTML = `<img src="${e.target.result}" class="img-thumb"><div class="delete-btn" onclick="this.parentElement.remove()">✕</div>`;
                preview.appendChild(div);
            };
            reader.readAsDataURL(file);
        });
        realInput.files = fileManagers[id].files;
    }

    function addCustomField() {
        const container = document.getElementById('custom-fields-container');
        const div = document.createElement('div');
        div.className = "flex gap-2 animate-fade-in";
        div.innerHTML = `<input type="text" name="custom_keys[]" placeholder="Label" class="flex-1 border border-slate-200 rounded-lg px-3 py-2 text-sm outline-none"><input type="text" name="custom_values[]" placeholder="Value" class="flex-1 border border-slate-200 rounded-lg px-3 py-2 text-sm outline-none"><button type="button" onclick="this.parentElement.remove()" class="text-red-400 font-bold">✕</button>`;
        container.appendChild(div);
    }

    function validateForm() {
        const container = document.getElementById('room-categories-container');
        if (container.children.length === 0) {
            alert("Please add at least one Room Category with Images.");
            return false;
        }
        return true;
    }

    window.onload = () => addRoomCategory();
</script>

</body>
</html>