
<?php
    $rmgTotalPax = collect($rooming)->sum('pax_named');
?>

<?php if(!$roomingReady): ?>
    <div class="rmg-note warn">
        <i class="fas fa-database"></i>
        <span>Oda tabloları henüz oluşturulmamış. Terminalde <b>php artisan migrate</b>
        komutunu çalıştırdıktan sonra odalama burada açılacak.</span>
    </div>
<?php elseif(empty($rooming)): ?>
    <div class="rmg-empty">
        <i class="fas fa-bed"></i>
        <b>Bu kalkışta rezervasyon yok</b>
        <span>Odalama, kalkışa bağlı rezervasyonlar üzerinden kurgulanır.</span>
    </div>
<?php else: ?>

<div class="rmg-root" id="rmgRoot-<?php echo e($uid); ?>"
     data-rmg-uid="<?php echo e($uid); ?>"
     data-rmg-assign="<?php echo e(route('agency.operations.rooming.assign', [$typeKey, $id])); ?>"
     data-rmg-rooms="<?php echo e(url('/agency/operations/' . $typeKey . '/' . $id . '/rooming/rooms')); ?>"
     data-rmg-self="<?php echo e(route('agency.operations.quick-view', [$typeKey, $id])); ?>">

    
    <div class="rmg-bar">
        <div class="rmg-stats">
            <span class="rmg-stat"><i class="fas fa-bed"></i><b id="rmgRoomCount-<?php echo e($uid); ?>"><?php echo e($roomingSummary['rooms']); ?></b> oda</span>
            <span class="rmg-sep"></span>
            <span class="rmg-stat ok"><i class="fas fa-user-check"></i><b id="rmgAssigned-<?php echo e($uid); ?>"><?php echo e($roomingSummary['assigned']); ?></b>/<?php echo e($rmgTotalPax); ?> yerleşti</span>
            <span class="rmg-sep"></span>
            <span class="rmg-stat <?php echo e($roomingSummary['unassigned'] ? 'warn' : ''); ?>"><i class="fas fa-user-clock"></i><b id="rmgUnassigned-<?php echo e($uid); ?>"><?php echo e($roomingSummary['unassigned']); ?></b> atanmamış</span>
            <?php if($roomingSummary['over']): ?>
                <span class="rmg-sep"></span>
                <span class="rmg-stat bad"><i class="fas fa-triangle-exclamation"></i><b><?php echo e($roomingSummary['over']); ?></b> kapasite aşımı</span>
            <?php endif; ?>
        </div>
        <span class="rmg-hint"><i class="fas fa-hand-pointer"></i> Yolcuyu sürükleyip odaya bırakın — ya da kartındaki listeden oda seçin.</span>
    </div>

    
    <?php $__currentLoopData = $rooming; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <?php $sid = $s['sale_id']; ?>
        <div class="rmg-sale" data-rmg-sale="<?php echo e($sid); ?>">
            <div class="rmg-sale-head">
                <span class="rmg-sale-av"><?php echo e(mb_strtoupper(mb_substr($s['customer'], 0, 1))); ?></span>
                <div class="rmg-sale-txt">
                    <button type="button" class="rmg-sale-code" onclick="openSaleDrawer(<?php echo e($sid); ?>)" title="Satış kartını aç">#<?php echo e($s['sale_code']); ?></button>
                    <span class="rmg-sale-sub">
                        <?php echo e($s['customer']); ?>

                        · <b data-rmg-placed><?php echo e($s['assigned_count']); ?></b>/<?php echo e($s['pax_named']); ?> yolcu yerleşti
                        <?php if($s['pax_missing'] > 0): ?>
                            <span class="rmg-flag warn" title="Kişi sayısı kadar yolcu kaydı girilmemiş"><?php echo e($s['pax_missing']); ?> isimsiz</span>
                        <?php endif; ?>
                    </span>
                </div>
                <button type="button" class="rmg-addbtn" onclick="rmgToggleAdd('<?php echo e($uid); ?>', <?php echo e($sid); ?>)">
                    <i class="fas fa-plus"></i> Oda Ekle
                </button>
            </div>

            
            <div class="rmg-addform" id="rmgAdd-<?php echo e($uid); ?>-<?php echo e($sid); ?>" hidden>
                <div class="rmg-f">
                    <label>Oda Tipi</label>
                    <select class="rmg-input" data-rmg-new="room_type">
                        <?php $__currentLoopData = $roomTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($key); ?>" <?php if($key === 'double'): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="rmg-f">
                    <label>Etiket</label>
                    <input type="text" class="rmg-input" data-rmg-new="label" maxlength="60" placeholder="Oda <?php echo e(count($s['rooms']) + 1); ?>">
                </div>
                <label class="rmg-chk">
                    <input type="checkbox" data-rmg-new="extra_bed"><span>Ek yatak</span>
                </label>
                <div class="rmg-f-acts">
                    <button type="button" class="rmg-cancel" onclick="rmgToggleAdd('<?php echo e($uid); ?>', <?php echo e($sid); ?>, false)">Vazgeç</button>
                    <button type="button" class="rmg-save" onclick="rmgCreateRoom('<?php echo e($uid); ?>', <?php echo e($sid); ?>)"><i class="fas fa-check me-1"></i>Ekle</button>
                </div>
            </div>

            <div class="rmg-cols">
                
                <div class="rmg-pool" data-rmg-drop="pool" data-sale="<?php echo e($sid); ?>">
                    <div class="rmg-pool-h">
                        <i class="fas fa-user-clock"></i> Atanmamış
                        <b data-rmg-poolcount><?php echo e(count($s['unassigned'])); ?></b>
                    </div>
                    <div class="rmg-slots" data-rmg-slots>
                        <?php $__currentLoopData = $s['unassigned']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php echo $__env->make('agency.operations.partials.rooming-chip', ['p' => $p, 'sale' => $s, 'uid' => $uid, 'roomId' => null], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                    <div class="rmg-pool-empty" data-rmg-poolempty <?php if(count($s['unassigned'])): ?> hidden <?php endif; ?>>
                        <i class="fas fa-circle-check"></i> Tüm yolcular yerleşti
                    </div>
                </div>

                
                <div class="rmg-rooms">
                    <?php $__empty_1 = true; $__currentLoopData = $s['rooms']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $room): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <div class="rmg-room <?php echo e($room['is_over'] ? 'is-over' : ($room['is_full'] ? 'is-full' : '')); ?>"
                             data-rmg-drop="room" data-sale="<?php echo e($sid); ?>" data-room="<?php echo e($room['id']); ?>"
                             data-cap="<?php echo e($room['bed_capacity']); ?>">
                            <div class="rmg-room-h">
                                <i class="fas fa-bed"></i>
                                <b data-rmg-label><?php echo e($room['label']); ?></b>
                                <span class="rmg-type"><?php echo e($room['type_label']); ?></span>
                                <?php if($room['extra_bed']): ?><span class="rmg-type xb" title="Ek yatak"><i class="fas fa-plus"></i> yatak</span><?php endif; ?>
                                <span class="rmg-beds" data-rmg-beds><?php echo e($room['beds_used']); ?>/<?php echo e($room['bed_capacity']); ?></span>
                                <button type="button" class="rmg-ico" title="Odayı düzenle" onclick="rmgToggleEdit(this)"><i class="fas fa-pen"></i></button>
                            </div>

                            
                            <div class="rmg-editform" hidden>
                                <div class="rmg-f">
                                    <label>Oda Tipi</label>
                                    <select class="rmg-input" data-rmg-edit="room_type">
                                        <?php $__currentLoopData = $roomTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($key); ?>" <?php if($key === $room['room_type']): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="rmg-f">
                                    <label>Etiket</label>
                                    <input type="text" class="rmg-input" data-rmg-edit="label" maxlength="60" value="<?php echo e($room['label']); ?>">
                                </div>
                                <div class="rmg-f narrow">
                                    <label>Yatak</label>
                                    <input type="number" class="rmg-input" data-rmg-edit="capacity" min="1" max="12" value="<?php echo e($room['capacity']); ?>">
                                </div>
                                <label class="rmg-chk">
                                    <input type="checkbox" data-rmg-edit="extra_bed" <?php if($room['extra_bed']): echo 'checked'; endif; ?>><span>Ek yatak</span>
                                </label>
                                <div class="rmg-f-acts">
                                    <button type="button" class="rmg-del" onclick="rmgDeleteRoom('<?php echo e($uid); ?>', this)"><i class="fas fa-trash"></i></button>
                                    <button type="button" class="rmg-cancel" onclick="rmgToggleEdit(this, false)">Vazgeç</button>
                                    <button type="button" class="rmg-save" onclick="rmgUpdateRoom('<?php echo e($uid); ?>', this)"><i class="fas fa-check me-1"></i>Kaydet</button>
                                </div>
                            </div>

                            <div class="rmg-slots" data-rmg-slots>
                                <?php $__currentLoopData = $room['occupants']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php echo $__env->make('agency.operations.partials.rooming-chip', ['p' => $p, 'sale' => $s, 'uid' => $uid, 'roomId' => $room['id']], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>

                            <?php if($room['priced']['adult'] || $room['priced']['child'] || $room['priced']['infant']): ?>
                                <div class="rmg-room-f" title="Satış kartında fiyatlanan kompozisyon">
                                    <i class="fas fa-tag"></i>
                                    Fiyatlanan: <?php echo e($room['priced']['adult']); ?>Y
                                    <?php if($room['priced']['child']): ?> · <?php echo e($room['priced']['child']); ?>Ç <?php endif; ?>
                                    <?php if($room['priced']['infant']): ?> · <?php echo e($room['priced']['infant']); ?>B <?php endif; ?>
                                    <?php if($room['unit_price'] !== null): ?>· <?php echo e(number_format($room['unit_price'], 0, ',', '.')); ?>₺<?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="rmg-noroom">
                            <i class="fas fa-bed"></i>
                            <b>Bu rezervasyonda oda tanımlanmamış</b>
                            <span>Oda ekleyip yolcuları yerleştirebilirsiniz.</span>
                            <button type="button" class="rmg-save" onclick="rmgToggleAdd('<?php echo e($uid); ?>', <?php echo e($sid); ?>, true)">
                                <i class="fas fa-plus me-1"></i> Oda Ekle
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
<?php endif; ?>

<?php echo $__env->make('agency.operations.partials.rooming-styles', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?php if($roomingReady && !empty($rooming)): ?>
<script>
(function () {
    const UID = <?php echo json_encode($uid, 15, 512) ?>;
    const CSRF = document.querySelector('meta[name="csrf-token"]')?.content || '';

    // Her uç, üzerinde çalışılan elemanın kendi kökünden okunur (bkz. .rmg-root)
    const rootOf = el => el?.closest?.('.rmg-root') || document.getElementById('rmgRoot-' + UID);
    const urlOf = (el, key) => rootOf(el)?.dataset[key] || '';
    const refreshFrom = el => {
        const self = urlOf(el, 'rmgSelf');
        if (self && typeof openQuickView === 'function') openQuickView(self, 'rooming');
    };
    const toast = (icon, title) => {
        if (typeof Swal === 'undefined') return;
        Swal.fire({ toast: true, position: 'top-end', timer: 2600, showConfirmButton: false, icon, title });
    };

    function post(url, body, method) {
        return fetch(url, {
            method: method || 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': CSRF },
            body: body ? JSON.stringify(body) : undefined,
        }).then(r => r.json());
    }

    // ── Sayaçları yeniden çiz ──
    // Kaydın ardından tüm kartı tazelemek açık formları ve kaydırmayı bozardı;
    // bunun yerine yerleşim DOM'da taşınır ve sayaçlar burada tazelenir.
    function paintRoom(roomEl) {
        const cap = parseInt(roomEl.dataset.cap || '0', 10);
        const chips = [...roomEl.querySelectorAll('[data-rmg-slots] > .rmg-pax')];
        const beds = chips.filter(c => c.dataset.bed === '1').length;

        roomEl.querySelector('[data-rmg-beds]').textContent = beds + '/' + cap;
        roomEl.classList.toggle('is-full', beds === cap);
        roomEl.classList.toggle('is-over', beds > cap);

        // Boş yatak yer tutucuları
        const slots = roomEl.querySelector('[data-rmg-slots]');
        slots.querySelectorAll('.rmg-ghost').forEach(g => g.remove());
        for (let i = beds; i < cap; i++) {
            const g = document.createElement('div');
            g.className = 'rmg-ghost';
            g.innerHTML = '<i class="fas fa-bed"></i> Boş yatak';
            slots.appendChild(g);
        }
    }

    function paintSale(saleEl) {
        if (!saleEl) return;
        const pool = saleEl.querySelector('.rmg-pool');
        const poolChips = pool.querySelectorAll('[data-rmg-slots] > .rmg-pax').length;
        pool.querySelector('[data-rmg-poolcount]').textContent = poolChips;
        pool.querySelector('[data-rmg-poolempty]').toggleAttribute('hidden', poolChips > 0);

        const placed = saleEl.querySelectorAll('.rmg-room [data-rmg-slots] > .rmg-pax').length;
        const placedEl = saleEl.querySelector('[data-rmg-placed]');
        if (placedEl) placedEl.textContent = placed;

        saleEl.querySelectorAll('.rmg-room').forEach(paintRoom);
        paintBar(saleEl);
    }

    function paintBar(el) {
        const scope = rootOf(el);
        if (!scope) return;
        const set = (sel, v) => { const n = scope.querySelector(sel); if (n) n.textContent = v; };
        set('[id^="rmgRoomCount-"]', scope.querySelectorAll('.rmg-room').length);
        set('[id^="rmgAssigned-"]', scope.querySelectorAll('.rmg-room [data-rmg-slots] > .rmg-pax').length);
        set('[id^="rmgUnassigned-"]', scope.querySelectorAll('.rmg-pool [data-rmg-slots] > .rmg-pax').length);
    }

    // Her odanın oda-seçme listesini güncel tut (oda eklenince/silinince)
    function refreshSelects(saleEl) {
        const opts = [...saleEl.querySelectorAll('.rmg-room')].map(r => ({
            id: r.dataset.room, label: r.querySelector('[data-rmg-label]').textContent.trim(),
        }));
        saleEl.querySelectorAll('.rmg-pax select.rmg-move').forEach(sel => {
            const chip = sel.closest('.rmg-pax');
            const cur = chip.dataset.room || '';
            sel.innerHTML = '<option value="">Atanmamış</option>'
                + opts.map(o => '<option value="' + o.id + '"' + (String(o.id) === String(cur) ? ' selected' : '') + '>' + o.label + '</option>').join('');
        });
    }

    // ── Yerleşim ──
    function place(chip, targetEl) {
        const saleEl = chip.closest('[data-rmg-sale]');
        const fromRoom = chip.dataset.room || '';
        const toRoom = targetEl.dataset.drop === 'room' ? targetEl.dataset.room : '';
        if (String(fromRoom) === String(toRoom)) return;

        const homeSlots = chip.parentElement;
        const homeNext = chip.nextSibling;
        const slots = targetEl.querySelector('[data-rmg-slots]');

        // İyimser taşıma — sunucu reddederse geri alınır
        slots.appendChild(chip);
        chip.dataset.room = toRoom;
        chip.classList.add('is-saving');
        paintSale(saleEl);

        post(urlOf(chip, 'rmgAssign'), {
            sale_id: chip.dataset.sale,
            passenger_id: chip.dataset.passenger,
            room_id: toRoom || null,
        }).then(d => {
            chip.classList.remove('is-saving');
            if (!d.success) {
                homeSlots.insertBefore(chip, homeNext);
                chip.dataset.room = fromRoom;
                paintSale(saleEl);
                refreshSelects(saleEl);
                toast('warning', d.message || 'Yerleştirilemedi');
                return;
            }
            chip.classList.add('is-ok');
            setTimeout(() => chip.classList.remove('is-ok'), 900);
            refreshSelects(saleEl);
        }).catch(() => {
            chip.classList.remove('is-saving');
            homeSlots.insertBefore(chip, homeNext);
            chip.dataset.room = fromRoom;
            paintSale(saleEl);
            toast('error', 'Sunucuya ulaşılamadı');
        });
    }

    // Kart her tazelendiğinde yeniden bağlanır; dinleyici birikmesin diye
    // tek delege dinleyici kullanılır.
    if (!window.__rmgBound) {
        window.__rmgBound = true;

        document.addEventListener('dragstart', e => {
            const chip = e.target.closest?.('.rmg-pax');
            if (!chip) return;
            if (e.target.closest('select, button')) { e.preventDefault(); return; }
            window.__rmgDrag = chip;
            chip.classList.add('is-dragging');
            e.dataTransfer.effectAllowed = 'move';
            try { e.dataTransfer.setData('text/plain', chip.dataset.passenger); } catch (_) {}
        });

        document.addEventListener('dragend', () => {
            window.__rmgDrag?.classList.remove('is-dragging');
            document.querySelectorAll('.rmg-over').forEach(el => el.classList.remove('rmg-over'));
            window.__rmgDrag = null;
        });

        document.addEventListener('dragover', e => {
            const zone = e.target.closest?.('[data-rmg-drop]');
            if (!zone || !window.__rmgDrag) return;
            if (zone.dataset.sale !== window.__rmgDrag.dataset.sale) return; // odalama satış içinde kalır
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            if (!zone.classList.contains('rmg-over')) {
                document.querySelectorAll('.rmg-over').forEach(el => el.classList.remove('rmg-over'));
                zone.classList.add('rmg-over');
            }
        });

        document.addEventListener('drop', e => {
            const zone = e.target.closest?.('[data-rmg-drop]');
            const chip = window.__rmgDrag;
            if (!zone || !chip) return;
            e.preventDefault();
            zone.classList.remove('rmg-over');
            if (zone.dataset.sale !== chip.dataset.sale) {
                toast('warning', 'Yolcu yalnızca kendi rezervasyonundaki odalara yerleştirilebilir.');
                return;
            }
            place(chip, zone);
        });

        // Dokunmatik / klavye yolu: karttaki oda listesi
        document.addEventListener('change', e => {
            const sel = e.target.closest?.('select.rmg-move');
            if (!sel) return;
            const chip = sel.closest('.rmg-pax');
            const saleEl = chip.closest('[data-rmg-sale]');
            const target = sel.value
                ? saleEl.querySelector('.rmg-room[data-room="' + sel.value + '"]')
                : saleEl.querySelector('.rmg-pool');
            if (target) place(chip, target);
        });
    }

    // ── Oda ekle / düzenle / sil ──
    window.rmgToggleAdd = function (uid, saleId, force) {
        const box = document.getElementById('rmgAdd-' + uid + '-' + saleId);
        if (!box) return;
        const open = force !== undefined ? force : box.hasAttribute('hidden');
        box.toggleAttribute('hidden', !open);
        if (open) box.querySelector('[data-rmg-new="label"]')?.focus();
    };

    window.rmgCreateRoom = function (uid, saleId) {
        const box = document.getElementById('rmgAdd-' + uid + '-' + saleId);
        if (!box) return;
        post(urlOf(box, 'rmgRooms'), {
            sale_id: saleId,
            room_type: box.querySelector('[data-rmg-new="room_type"]').value,
            label: box.querySelector('[data-rmg-new="label"]').value,
            extra_bed: box.querySelector('[data-rmg-new="extra_bed"]').checked ? 1 : 0,
        }).then(d => {
            if (!d.success) { toast('error', d.message || 'Oda eklenemedi'); return; }
            toast('success', d.message);
            refreshFrom(box); // yeni oda kartı sunucudan gelsin
        }).catch(() => toast('error', 'Sunucuya ulaşılamadı'));
    };

    window.rmgToggleEdit = function (btn, force) {
        const room = btn.closest('.rmg-room');
        const box = room.querySelector('.rmg-editform');
        const open = force !== undefined ? force : box.hasAttribute('hidden');
        box.toggleAttribute('hidden', !open);
    };

    window.rmgUpdateRoom = function (uid, btn) {
        const room = btn.closest('.rmg-room');
        const g = k => room.querySelector('[data-rmg-edit="' + k + '"]');

        post(urlOf(room, 'rmgRooms') + '/' + room.dataset.room, {
            room_type: g('room_type').value,
            label: g('label').value,
            capacity: g('capacity').value,
            extra_bed: g('extra_bed').checked ? 1 : 0,
        }, 'PATCH').then(d => {
            if (!d.success) { toast('error', d.message || 'Oda güncellenemedi'); return; }
            toast('success', d.message);
            refreshFrom(room);
        }).catch(() => toast('error', 'Sunucuya ulaşılamadı'));
    };

    window.rmgDeleteRoom = function (uid, btn) {
        const room = btn.closest('.rmg-room');
        const label = room.querySelector('[data-rmg-label]').textContent.trim();
        const run = () => post(urlOf(room, 'rmgRooms') + '/' + room.dataset.room, null, 'DELETE').then(d => {
            toast(d.success ? 'success' : 'error', d.message || '');
            if (d.success) refreshFrom(room);
        }).catch(() => toast('error', 'Sunucuya ulaşılamadı'));

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: label + ' silinsin mi?',
                text: 'İçindeki yolcular "atanmamış" listesine döner.',
                icon: 'warning', showCancelButton: true,
                confirmButtonColor: '#ef4444', confirmButtonText: 'Evet, sil', cancelButtonText: 'Vazgeç',
            }).then(r => r.isConfirmed && run());
        } else if (confirm(label + ' silinsin mi?')) run();
    };

    // İlk çizim: boş yatak yer tutucuları + sayaçlar
    document.getElementById('rmgRoot-' + UID)?.querySelectorAll('[data-rmg-sale]').forEach(paintSale);
})();
</script>
<?php endif; ?>
<?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/operations/partials/rooming-panel.blade.php ENDPATH**/ ?>