<?php $__env->startSection('backend_css'); ?>
<style>
    .panel-card {
        border: 1px solid #eef0f4;
        border-radius: 14px;
        box-shadow: 0 10px 24px rgba(17, 24, 39, 0.05);
    }

    .ajax-result-item {
        cursor: pointer;
        transition: background 0.15s ease;
    }

    .ajax-result-item:hover,
    .ajax-result-item.focused {
        background: #f2f5ff;
    }

    .user-row-highlight {
        background: #eef2ff;
    }

    .shop-popup-item {
        border: 1px solid #eef0f4;
        border-radius: 8px;
        padding: 8px 10px;
    }

    .shop-popup-item:hover {
        background: #f8f9ff;
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('backend_content'); ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold mb-1"><i class="bx bx-user-plus me-2 text-primary"></i>Shop Staff Assignment</h4>
            <small class="text-muted">Manage users and assign one user to multiple shops.</small>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bx bx-plus me-1"></i> Add New User
        </button>
    </div>

    <div class="row g-4">
        <div class="col-lg-7">
            <div class="card panel-card">
                <div class="card-header bg-transparent border-bottom d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div class="fw-semibold"><i class="bx bx-list-ul me-1"></i> All Users</div>
                    <form method="GET" action="<?php echo e(route('admin.staff-assignment.index')); ?>" class="d-flex gap-2">
                        <input type="text" name="q" class="form-control form-control-sm" placeholder="Search users by name/email" value="<?php echo e($search); ?>" style="width: 220px;">
                        <?php if($selectedUserId): ?>
                            <input type="hidden" name="user_id" value="<?php echo e($selectedUserId); ?>">
                        <?php endif; ?>
                        <button type="submit" class="btn btn-sm btn-outline-primary"><i class="bx bx-search"></i></button>
                        <?php if($search !== ''): ?>
                            <a href="<?php echo e(route('admin.staff-assignment.index')); ?>" class="btn btn-sm btn-light">Clear</a>
                        <?php endif; ?>
                    </form>
                </div>

                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table mb-0 align-middle">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Email</th>
                                    <th>Assigned Shops</th>
                                    <th class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__empty_1 = true; $__currentLoopData = $users; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                    <tr class="<?php echo e((int) $selectedUserId === (int) $user->id ? 'user-row-highlight' : ''); ?>">
                                        <td class="fw-semibold"><?php echo e($user->name); ?></td>
                                        <td><?php echo e($user->email); ?></td>
                                        <td>
                                            <span class="badge bg-label-primary user-shops-count" data-user-id="<?php echo e($user->id); ?>"><?php echo e($user->shops_count); ?> shops</span>
                                        </td>
                                        <td class="text-end">
                                            <a href="<?php echo e(route('admin.staff-assignment.index', ['user_id' => $user->id, 'q' => $search])); ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="bx bx-edit-alt"></i> Edit
                                            </a>
                                            <button type="button" class="btn btn-sm btn-outline-info open-user-shops-modal"
                                                data-user-id="<?php echo e($user->id); ?>" data-user-name="<?php echo e($user->name); ?>">
                                                <i class="bx bx-store"></i> Shops
                                            </button>
                                            <form method="POST" action="<?php echo e(route('admin.staff-assignment.users.destroy', $user)); ?>" class="d-inline delete-user-form"
                                                data-user-name="<?php echo e($user->name); ?>">
                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <i class="bx bx-trash"></i> Delete
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-4">No users found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="card-footer bg-transparent">
                    <?php echo e($users->links()); ?>

                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <?php if($selectedUser): ?>
                <form method="POST" action="<?php echo e(route('admin.staff-assignment.assign-shops')); ?>">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="user_id" value="<?php echo e($selectedUser->id); ?>">

                    <div class="card panel-card">
                        <div class="card-header bg-transparent border-bottom">
                            <div class="fw-semibold d-flex justify-content-between align-items-center mb-2">
                                <span><i class="bx bx-edit me-1"></i> Edit User</span>
                                <span class="badge bg-label-primary">Profile</span>
                            </div>
                        </div>

                        <div class="card-body">
                            <div class="row g-2 mb-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold mb-1">Name</label>
                                    <input type="text" name="edit_name" class="form-control form-control-sm <?php $__errorArgs = ['edit_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                        value="<?php echo e(old('edit_name', $selectedUser->name)); ?>" required>
                                    <?php $__errorArgs = ['edit_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold mb-1">Email</label>
                                    <input type="email" name="edit_email" class="form-control form-control-sm <?php $__errorArgs = ['edit_email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                        value="<?php echo e(old('edit_email', $selectedUser->email)); ?>" required>
                                    <?php $__errorArgs = ['edit_email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold mb-1">New Password <span class="text-muted">(optional)</span></label>
                                    <div class="input-group input-group-sm">
                                        <input type="password" id="editUserPassword" name="edit_password"
                                            class="form-control <?php $__errorArgs = ['edit_password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                            placeholder="Leave blank to keep current password">
                                        <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('editUserPassword', this)">
                                            <i class="bx bx-hide"></i>
                                        </button>
                                    </div>
                                    <?php $__errorArgs = ['edit_password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback d-block"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold mb-1">Confirm New Password</label>
                                    <div class="input-group input-group-sm">
                                        <input type="password" id="editUserPasswordConfirm" name="edit_password_confirmation"
                                            class="form-control" placeholder="Repeat new password">
                                        <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('editUserPasswordConfirm', this)">
                                            <i class="bx bx-hide"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="alert alert-info py-2 px-3 mb-0">
                                <small class="mb-0 d-block">Update user profile details here. Shop assignment controls are hidden on this screen as requested.</small>
                            </div>
                        </div>

                        <div class="card-footer bg-transparent d-flex gap-2">
                            <button type="submit" class="btn btn-primary"><i class="bx bx-save me-1"></i> Save</button>
                            <a href="<?php echo e(route('admin.staff-assignment.index', ['q' => $search])); ?>" class="btn btn-light">Cancel</a>
                        </div>
                    </div>
                </form>
            <?php else: ?>
                <div class="card panel-card">
                    <div class="card-body text-center py-5 text-muted">
                        <i class="bx bx-edit bx-lg mb-2 d-block"></i>
                        Select a user from the list, then click Edit to manage shop assignments.
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="userShopsModal" tabindex="-1" aria-labelledby="userShopsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="userShopsModalLabel">
                    <i class="bx bx-store me-1 text-primary"></i> Assigned Shops
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" id="popupUserId">
                <div class="d-flex align-items-center justify-content-between gap-2 mb-3">
                    <div class="text-muted small" id="popupUserInfo">Loading user info...</div>
                    <input type="text" id="popupShopSearch" class="form-control form-control-sm" placeholder="Search shops..." style="max-width: 260px;" autocomplete="off">
                </div>

                <div id="popupShopsLoading" class="text-muted small mb-2 d-none">Loading shops...</div>
                <div id="popupShopsEmpty" class="text-muted text-center py-3 d-none">No shops found.</div>

                <div class="row g-2" id="popupShopsList"></div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" id="popupSelectAllBtn">Select All</button>
                <button type="button" class="btn btn-outline-secondary" id="popupClearAllBtn">Clear All</button>
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="savePopupShopsBtn">
                    <i class="bx bx-save me-1"></i> Save Shops
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="<?php echo e(route('admin.staff-assignment.create-user')); ?>">
                <?php echo csrf_field(); ?>

                <div class="modal-header">
                    <h5 class="modal-title fw-bold" id="addUserModalLabel">
                        <i class="bx bx-user-plus me-1 text-primary"></i> Create New User
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" value="<?php echo e(old('name')); ?>" required>
                        <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Email <span class="text-danger">*</span></label>
                        <input type="email" name="email" class="form-control <?php $__errorArgs = ['email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" value="<?php echo e(old('email')); ?>" required>
                        <?php $__errorArgs = ['email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Password <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="password" id="newUserPassword" name="password" class="form-control <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('newUserPassword', this)">
                                <i class="bx bx-hide"></i>
                            </button>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Confirm Password <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="password" id="newUserPasswordConfirm" name="password_confirmation" class="form-control" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('newUserPasswordConfirm', this)">
                                <i class="bx bx-hide"></i>
                            </button>
                        </div>
                    </div>

                    <div class="mb-0 position-relative">
                        <label class="form-label fw-semibold">Assign to Shop <span class="text-muted">(optional)</span></label>
                        <input type="hidden" name="shop_id" id="modalSelectedShopId" value="<?php echo e(old('shop_id')); ?>">
                        <input type="text" id="modalShopSearchInput" class="form-control" placeholder="Search shops with AJAX..." autocomplete="off">
                        <div id="modalShopDropdown" class="border rounded shadow-sm mt-1"
                            style="display:none;position:absolute;z-index:1000;background:#fff;width:100%;max-height:220px;overflow-y:auto;">
                        </div>
                        <small class="text-muted d-block mt-1" id="modalSelectedShopLabel">No shop selected</small>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="bx bx-user-check me-1"></i> Create User</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('backend_js'); ?>
<script>
const SHOP_AJAX_SEARCH_URL = '<?php echo e(route('admin.staff-assignment.shops-search')); ?>';
const USER_SHOPS_URL_TEMPLATE = <?php echo json_encode(route('admin.staff-assignment.users.shops', ['user' => '__USER__']), 512) ?>;
const USER_SHOPS_UPDATE_URL_TEMPLATE = <?php echo json_encode(route('admin.staff-assignment.users.shops.update', ['user' => '__USER__']), 512) ?>;
const CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

// AJAX shop search in modal
const modalShopInput = document.getElementById('modalShopSearchInput');
const modalShopDropdown = document.getElementById('modalShopDropdown');
const modalSelectedShopId = document.getElementById('modalSelectedShopId');
const modalSelectedShopLabel = document.getElementById('modalSelectedShopLabel');

let modalShopTimer;
let modalShopFocus = -1;

function setModalSelectedShop(id, name) {
    modalSelectedShopId.value = id || '';
    if (id) {
        modalShopInput.value = name;
        modalSelectedShopLabel.textContent = 'Selected: ' + name;
    } else {
        modalShopInput.value = '';
        modalSelectedShopLabel.textContent = 'No shop selected';
    }
}

function renderModalShopResults(shops) {
    if (!shops.length) {
        modalShopDropdown.innerHTML = '<div class="px-3 py-2 text-muted small">No shop found.</div>';
        modalShopDropdown.style.display = 'block';
        return;
    }

    modalShopDropdown.innerHTML = shops.map(function (shop) {
        const safeName = String(shop.name).replace(/"/g, '&quot;');
        return '<div class="ajax-result-item px-3 py-2 border-bottom" data-id="' + shop.id + '" data-name="' + safeName + '">' +
            '<i class="bx bx-store me-2 text-primary"></i>' + safeName + '</div>';
    }).join('');

    modalShopDropdown.style.display = 'block';

    modalShopDropdown.querySelectorAll('.ajax-result-item').forEach(function (item) {
        item.addEventListener('click', function () {
            setModalSelectedShop(this.dataset.id, this.dataset.name);
            modalShopDropdown.style.display = 'none';
        });
    });
}

function fetchShopsForModal(q) {
    fetch(SHOP_AJAX_SEARCH_URL + '?q=' + encodeURIComponent(q || ''), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function (res) { return res.json(); })
    .then(function (data) { renderModalShopResults(data); })
    .catch(function () {
        modalShopDropdown.innerHTML = '<div class="px-3 py-2 text-danger small">Failed to load shops.</div>';
        modalShopDropdown.style.display = 'block';
    });
}

if (modalShopInput) {
    modalShopInput.addEventListener('focus', function () {
        fetchShopsForModal(this.value.trim());
    });

    modalShopInput.addEventListener('input', function () {
        clearTimeout(modalShopTimer);
        modalShopFocus = -1;
        const query = this.value.trim();

        if (!query) {
            setModalSelectedShop('', '');
            fetchShopsForModal('');
            return;
        }

        modalShopTimer = setTimeout(function () {
            fetchShopsForModal(query);
        }, 250);
    });

    modalShopInput.addEventListener('keydown', function (e) {
        const items = modalShopDropdown.querySelectorAll('.ajax-result-item');
        if (!items.length) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            modalShopFocus = modalShopFocus < items.length - 1 ? modalShopFocus + 1 : 0;
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            modalShopFocus = modalShopFocus > 0 ? modalShopFocus - 1 : items.length - 1;
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (modalShopFocus >= 0 && items[modalShopFocus]) {
                items[modalShopFocus].click();
            }
        } else if (e.key === 'Escape') {
            modalShopDropdown.style.display = 'none';
        }

        items.forEach(function (item, idx) {
            item.classList.toggle('focused', idx === modalShopFocus);
        });
    });
}

document.addEventListener('click', function (e) {
    if (!modalShopInput || !modalShopDropdown) return;
    if (!modalShopInput.contains(e.target) && !modalShopDropdown.contains(e.target)) {
        modalShopDropdown.style.display = 'none';
    }
});

function togglePassword(fieldId, btn) {
    const field = document.getElementById(fieldId);
    const icon = btn.querySelector('i');
    if (field.type === 'password') {
        field.type = 'text';
        icon.classList.replace('bx-hide', 'bx-show');
    } else {
        field.type = 'password';
        icon.classList.replace('bx-show', 'bx-hide');
    }
}

<?php if($errors->any()): ?>
document.addEventListener('DOMContentLoaded', function () {
    window.appToast(<?php echo json_encode($errors->first(), 15, 512) ?>, 'error');

    <?php if($errors->has('name') || $errors->has('email') || $errors->has('password') || $errors->has('shop_id')): ?>
    new bootstrap.Modal(document.getElementById('addUserModal')).show();
    <?php endif; ?>
});
<?php endif; ?>

document.querySelectorAll('.delete-user-form').forEach(function (formEl) {
    formEl.addEventListener('submit', function (event) {
        event.preventDefault();
        const userName = formEl.dataset.userName || 'this user';

        Swal.fire({
            title: 'Delete user?',
            text: `Delete ${userName}? This action cannot be undone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete',
            cancelButtonText: 'Cancel',
            reverseButtons: true,
            customClass: {
                confirmButton: 'btn btn-danger',
                cancelButton: 'btn btn-secondary me-2'
            },
            buttonsStyling: false,
        }).then((result) => {
            if (result.isConfirmed) {
                formEl.submit();
            }
        });
    });
});

const popupModalEl = document.getElementById('userShopsModal');
const popupModal = popupModalEl ? new bootstrap.Modal(popupModalEl) : null;
const popupUserIdInput = document.getElementById('popupUserId');
const popupUserInfo = document.getElementById('popupUserInfo');
const popupShopsList = document.getElementById('popupShopsList');
const popupShopsLoading = document.getElementById('popupShopsLoading');
const popupShopsEmpty = document.getElementById('popupShopsEmpty');
const popupShopSearch = document.getElementById('popupShopSearch');
const popupSelectAllBtn = document.getElementById('popupSelectAllBtn');
const popupClearAllBtn = document.getElementById('popupClearAllBtn');
const savePopupShopsBtn = document.getElementById('savePopupShopsBtn');

let popupAllShops = [];
let popupAssignedShopIds = new Set();

function shopsUrl(userId) {
    return USER_SHOPS_URL_TEMPLATE.replace('__USER__', String(userId));
}

function shopsUpdateUrl(userId) {
    return USER_SHOPS_UPDATE_URL_TEMPLATE.replace('__USER__', String(userId));
}

function renderPopupShops() {
    if (!popupShopsList) return;

    const q = (popupShopSearch?.value || '').toLowerCase().trim();
    const filtered = popupAllShops.filter(shop => !q || String(shop.name).toLowerCase().includes(q));

    if (!filtered.length) {
        popupShopsList.innerHTML = '';
        popupShopsEmpty.classList.remove('d-none');
        return;
    }

    popupShopsEmpty.classList.add('d-none');
    popupShopsList.innerHTML = filtered.map(shop => {
        const checked = popupAssignedShopIds.has(Number(shop.id)) ? 'checked' : '';
        return `
            <div class="col-md-6 col-lg-4">
                <label class="shop-popup-item d-flex align-items-center gap-2 w-100 mb-0">
                    <input type="checkbox" class="form-check-input popup-shop-checkbox" value="${shop.id}" ${checked}>
                    <span>${shop.name}</span>
                </label>
            </div>
        `;
    }).join('');

    popupShopsList.querySelectorAll('.popup-shop-checkbox').forEach(cb => {
        cb.addEventListener('change', function () {
            const id = Number(this.value);
            if (this.checked) {
                popupAssignedShopIds.add(id);
            } else {
                popupAssignedShopIds.delete(id);
            }
        });
    });
}

function openShopsPopup(userId, userName) {
    if (!popupModal) return;

    popupUserIdInput.value = String(userId);
    popupUserInfo.textContent = `User: ${userName}`;
    popupShopsLoading.classList.remove('d-none');
    popupShopsEmpty.classList.add('d-none');
    popupShopsList.innerHTML = '';
    popupAllShops = [];
    popupAssignedShopIds = new Set();
    if (popupShopSearch) popupShopSearch.value = '';

    popupModal.show();

    fetch(shopsUrl(userId), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(res => res.json())
    .then(data => {
        popupAllShops = Array.isArray(data.shops) ? data.shops : [];
        popupAssignedShopIds = new Set((data.assigned_shop_ids || []).map(Number));
        popupShopsLoading.classList.add('d-none');
        renderPopupShops();
    })
    .catch(() => {
        popupShopsLoading.classList.add('d-none');
        popupShopsEmpty.classList.remove('d-none');
        popupShopsEmpty.textContent = 'Failed to load shops.';
    });
}

document.querySelectorAll('.open-user-shops-modal').forEach(btn => {
    btn.addEventListener('click', function () {
        const userId = Number(this.dataset.userId);
        const userName = this.dataset.userName || 'User';
        openShopsPopup(userId, userName);
    });
});

if (popupShopSearch) {
    popupShopSearch.addEventListener('input', renderPopupShops);
}

if (popupSelectAllBtn) {
    popupSelectAllBtn.addEventListener('click', function () {
        popupAllShops.forEach(shop => popupAssignedShopIds.add(Number(shop.id)));
        renderPopupShops();
    });
}

if (popupClearAllBtn) {
    popupClearAllBtn.addEventListener('click', function () {
        popupAssignedShopIds = new Set();
        renderPopupShops();
    });
}

if (savePopupShopsBtn) {
    savePopupShopsBtn.addEventListener('click', function () {
        const userId = Number(popupUserIdInput.value || 0);
        if (!userId) return;

        const params = new URLSearchParams();
        popupAssignedShopIds.forEach(id => params.append('shop_ids[]', String(id)));

        savePopupShopsBtn.disabled = true;
        savePopupShopsBtn.innerHTML = '<i class="bx bx-loader-alt bx-spin me-1"></i> Saving...';

        fetch(shopsUpdateUrl(userId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': CSRF_TOKEN,
            },
            body: params.toString(),
        })
        .then(res => res.json())
        .then(data => {
            window.appToast(data.message || 'Shop assignments updated successfully.', 'success');

            const badge = document.querySelector(`.user-shops-count[data-user-id="${userId}"]`);
            if (badge) {
                const count = Number(data.count || popupAssignedShopIds.size);
                badge.textContent = `${count} shops`;
            }

            popupModal.hide();
        })
        .catch(() => {
            window.appToast('Failed to update shop assignments.', 'error');
        })
        .finally(() => {
            savePopupShopsBtn.disabled = false;
            savePopupShopsBtn.innerHTML = '<i class="bx bx-save me-1"></i> Save Shops';
        });
    });
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('backend.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Abdur Rahman\Desktop\faa\resources\views\backend\staff-assignment\index.blade.php ENDPATH**/ ?>