<?php
include 'db.php';

// 1. Validate ID
$id = intval($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid ID");

// 2. Fetch Existing Data
$stmt = $con->prepare("SELECT * FROM hotel_enquiry WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$data) die("Record not found");

// Parse extra_data for Logo and Contact 2
$extra_data = !empty($data['extra_data']) ? json_decode($data['extra_data'], true) : [];
$existing_logo = $extra_data['hotel_logo'] ?? '';
$contact_2 = $extra_data['contact_2'] ?? '';

// Track original images for physical deletion
$original_images_flat = [];
if (!empty($data['room_category'])) {
    preg_match_all('/\(Images:\s*(.*?)\)/', $data['room_category'], $image_matches);
    foreach ($image_matches[1] as $match) {
        if ($match !== 'No Images' && !empty($match)) {
            $imgs = explode(", ", $match);
            foreach ($imgs as $img) {
                $original_images_flat[] = trim($img);
            }
        }
    }
}

// 3. Parse Existing Room Data (RELAXED REGEX for missing numbers)
$parsed_rooms = [];
if (!empty($data['room_category'])) {
    $parts = explode(" | ", $data['room_category']);
    foreach ($parts as $part) {
        $part = trim($part);
        if (empty($part)) continue;

        // Relaxed pattern to handle missing counts/prices
        $pattern = '/^(.*?):\s*(\d*)\s*rooms\s*@\s*₹?\s*(\d*)\s*\[Weekday:\s*₹?(\d*),\s*Weekend:\s*₹?(\d*)\](?:\s*\(Images:\s*(.*?)\))?$/u';
        
        if (preg_match($pattern, $part, $matches)) {
            $raw_imgs = $matches[6] ?? '';
            $img_array = (!empty($raw_imgs) && $raw_imgs !== 'No Images') ? explode(", ", $raw_imgs) : [];
            
            $parsed_rooms[] = [
                'type'    => trim($matches[1]),
                'count'   => $matches[2] !== '' ? $matches[2] : '',
                'price'   => $matches[3] !== '' ? $matches[3] : '',
                'weekday' => $matches[4] !== '' ? $matches[4] : '0',
                'weekend' => $matches[5] !== '' ? $matches[5] : '0',
                'images'  => array_filter(array_map('trim', $img_array))
            ];
        }
    }
}

// 4. Handle Update Submission
if (isset($_POST['update'])) {
    $hotel_name    = $_POST['hotel_name'];
    $owner_number  = $_POST['owner_number'];
    $owner_number_2 = $_POST['owner_number_2']; 
    $floors        = $_POST['floors'];
    $total_rooms   = $_POST['total_rooms'];
    $owner_name    = $_POST['owner_name'] ?? '';
    $hotel_rating  = $_POST['hotel_type'] ?? '';
    $address       = $_POST['address'] ?? '';
    $facilities    = $_POST['facilities'] ?? '';
    $amenities     = $_POST['amenities'] ?? '';
    $restaurant    = $_POST['restaurant'] ?? 'No';
    $gst_no        = $_POST['gst_no'] ?? '';
    
    $upload_dir = "uploads/"; 
    if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

    // Handle Hotel Logo Update
    $logo_path = $existing_logo;
    if (isset($_FILES['hotel_logo']) && $_FILES['hotel_logo']['error'] === 0) {
        if (!empty($existing_logo) && file_exists($existing_logo)) unlink($existing_logo);
        $logo_ext = pathinfo($_FILES['hotel_logo']['name'], PATHINFO_EXTENSION);
        $logo_path = $upload_dir . "logo_" . time() . "." . $logo_ext;
        move_uploaded_file($_FILES['hotel_logo']['tmp_name'], $logo_path);
    }

    $new_extra = ['hotel_logo' => $logo_path, 'contact_2' => $owner_number_2];
    $json_data = json_encode($new_extra);

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

    $room_entries = [];
    $all_kept_images = []; 

    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;
            
            $current_existing = $_POST['existing_images'][$index] ?? [];
            $all_kept_images = array_merge($all_kept_images, $current_existing);
            $final_images = $current_existing;

            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)) {
                            $final_images[] = $target_file; 
                        }
                    }
                }
            }

            $img_list = !empty($final_images) ? implode(", ", array_filter($final_images)) : "No Images";
            $room_entries[] = "$type: $count rooms @ ₹$price [Weekday: ₹$w_day, Weekend: ₹$w_end] (Images: $img_list)";
        }
    }
    $room_category_string = implode(" | ", $room_entries);

    foreach ($original_images_flat as $old_img) {
        if (!in_array($old_img, $all_kept_images) && file_exists($old_img)) {
            unlink($old_img);
        }
    }

    $stmt = $con->prepare("UPDATE hotel_enquiry SET hotel_name=?, owner_name=?, owner_number=?, hotel_star_rating=?, address=?, floors=?, total_rooms=?, room_category=?, facilities=?, amenities=?, restaurant=?, gst_no=?, extra_data=? WHERE id=?");
    // Correct bind_param (13 placeholders in query, 14 variables including ID)
    $stmt->bind_param("sssssiissssssi", $hotel_name, $owner_name, $owner_number, $hotel_rating, $address, $floors, $total_rooms, $room_category_string, $facilities, $amenities, $restaurant, $gst_no, $json_data, $id);

    if ($stmt->execute()) {
        echo "<script>window.location.href='edit_enquiry.php?id=$id&updated=1';</script>";
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Hotel #<?php echo $id; ?></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: 12px; border: 2px solid #e2e8f0; }
        .delete-btn { position: absolute; top: -8px; right: -8px; background: #ef4444; color: white; border-radius: 50%; width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; font-size: 12px; cursor: pointer; border: 2px solid white; shadow: 0 2px 4px rgba(0,0,0,0.2); }
    </style>
</head>
<body class="bg-slate-50 min-h-screen pb-24 md:py-12 px-0 md:px-4">

<?php if(isset($_GET['updated'])): ?>
<div class="max-w-5xl mx-auto mb-6 bg-green-500 text-white px-4 py-3 rounded-xl text-center shadow-lg">
    <strong class="font-bold">Success!</strong> Changes 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">Edit Hotel Details</h2>
        <p class="text-slate-400 mt-2">ID: #<?php echo $id; ?></p>
    </div>

    <form method="post" enctype="multipart/form-data" class="p-6 md:p-12 space-y-12">
        
        <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">
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Hotel Name *</label>
                    <input type="text" name="hotel_name" value="<?php echo htmlspecialchars($data['hotel_name']); ?>" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Contact (1) *</label>
                        <input type="tel" name="owner_number" value="<?php echo htmlspecialchars($data['owner_number']); ?>" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                    </div>
                    <div>
                        <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Contact (2) *</label>
                        <input type="tel" name="owner_number_2" value="<?php echo htmlspecialchars($contact_2); ?>" required class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Hotel Logo</label>
                    <?php if($existing_logo): ?>
                        <div class="mb-2"><img src="<?php echo $existing_logo; ?>" class="h-12 w-12 object-cover rounded-lg border"></div>
                    <?php endif; ?>
                    <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>
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">No. Of Floors</label>
                    <input type="number" name="floors" value="<?php echo htmlspecialchars($data['floors']); ?>" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                </div>
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">No. Of Rooms</label>
                    <input type="number" name="total_rooms" value="<?php echo htmlspecialchars($data['total_rooms']); ?>" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus">
                </div>
            </div>

            <div class="space-y-4">
                <div class="flex justify-between items-center">
                    <label class="text-xs font-bold uppercase text-slate-600 tracking-wider">Room Images *</label>
                    <button type="button" onclick="addRoomCategory()" class="bg-blue-600 text-white px-4 py-2 rounded-xl text-xs font-bold shadow-lg">+ Add Category</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" value="<?php echo htmlspecialchars($data['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" value="<?php echo htmlspecialchars($data['hotel_star_rating']); ?>" 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" value="<?php echo htmlspecialchars($data['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" rows="2" placeholder="Address" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"><?php echo htmlspecialchars($data['address']); ?></textarea>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <textarea name="facilities" rows="2" placeholder="Facilities" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"><?php echo htmlspecialchars($data['facilities']); ?></textarea>
                <textarea name="amenities" rows="2" placeholder="Amenities" class="w-full border border-slate-200 rounded-xl px-4 py-3 input-focus"><?php echo htmlspecialchars($data['amenities'] ?? ''); ?></textarea>
            </div>
        </div>

        <button name="update" type="submit" class="w-full bg-slate-900 text-white py-5 rounded-2xl font-bold shadow-xl text-lg">Update Hotel Record</button>
    </form>
</div>

<script>
    let roomIndex = 0;
    const existingRooms = <?php echo json_encode($parsed_rooms); ?>;

    function addRoomCategory(data = null) {
        const container = document.getElementById('room-categories-container');
        const id = `room_${roomIndex}`;
        const type = data ? data.type : '';
        const count = data ? data.count : '';
        const price = data ? data.price : '';
        const weekday = data ? data.weekday : '';
        const weekend = data ? data.weekend : '';
        const card = document.createElement('div');
        card.className = "p-6 bg-white border border-slate-200 rounded-3xl space-y-4 shadow-sm relative";
        
        let existingImagesHTML = '';
        if (data && data.images) {
            data.images.forEach(img => {
                existingImagesHTML += `<div class="relative"><img src="${img}" class="img-thumb"><div class="delete-btn" onclick="this.parentElement.remove()">✕</div><input type="hidden" name="existing_images[${roomIndex}][]" value="${img}"></div>`;
            });
        }

        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]" value="${type}" placeholder="Room Type" required class="w-full border border-slate-200 rounded-xl px-4 py-2 font-bold outline-none">
            <div class="grid grid-cols-2 gap-4 text-xs">
                <input type="number" name="rooms[${roomIndex}][count]" value="${count}" placeholder="Qty" class="border border-slate-200 rounded-lg px-3 py-2 outline-none">
                <input type="number" name="rooms[${roomIndex}][price]" value="${price}" placeholder="Base Price" class="border border-slate-200 rounded-lg px-3 py-2 outline-none">
            </div>
            <div class="grid grid-cols-2 gap-4 text-xs">
                <input type="number" name="rooms[${roomIndex}][weekday]" value="${weekday}" placeholder="Weekday ₹" class="border border-slate-200 rounded-lg px-3 py-2 outline-none bg-blue-50/20">
                <input type="number" name="rooms[${roomIndex}][weekend]" value="${weekend}" placeholder="Weekend ₹" class="border border-slate-200 rounded-lg px-3 py-2 outline-none bg-blue-50/20">
            </div>
            <div>
                <div class="flex flex-wrap gap-2 mb-2">${existingImagesHTML}</div>
                <div id="preview-${id}" class="flex flex-wrap gap-2 mb-2"></div>
                <input type="file" name="room_images[${roomIndex}][]" id="file-${id}" multiple class="hidden" onchange="previewImages(this, '${id}')">
                <button type="button" onclick="document.getElementById('file-${id}').click()" class="w-full border border-dashed border-slate-300 rounded-xl py-2 text-slate-400 text-[10px] font-bold uppercase">+ Upload New Photos</button>
            </div>`;
        container.appendChild(card);
        roomIndex++;
    }

    function previewImages(input, id) {
        const preview = document.getElementById('preview-' + id);
        preview.innerHTML = '';
        if (input.files) {
            Array.from(input.files).forEach(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 opacity-50">`;
                    preview.appendChild(div);
                };
                reader.readAsDataURL(file);
            });
        }
    }

    window.onload = () => {
        if (existingRooms.length > 0) existingRooms.forEach(room => addRoomCategory(room));
        else addRoomCategory();
    };
</script>
</body>
</html>