

<?php $__env->startSection('title', 'Attendance Summary'); ?>
<?php $__env->startSection('heading', 'Attendance Summary'); ?>

<?php $__env->startSection('content'); ?>
<?php echo $__env->make('attendance.top-submenu', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => []] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
        <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
            <div class="flex flex-wrap items-center gap-4 text-xs font-medium text-slate-600">
                <span class="inline-flex items-center gap-1"><span class="text-red-500">✖</span> Absent</span>
                <span class="inline-flex items-center gap-1"><span class="text-emerald-600">✔</span> Present</span>
                <span class="inline-flex items-center gap-1"><span class="text-amber-600">◐</span> Half Day</span>
                <span class="inline-flex items-center gap-1"><span class="text-fuchsia-600">■</span> On Leave</span>
                <span class="inline-flex items-center gap-1"><span class="text-slate-400">•</span> Week Off</span>
                <span class="inline-flex items-center gap-1"><span class="text-teal-600">▣</span> Holiday</span>
            </div>
            <p class="text-xs text-slate-500">Click a day cell to toggle status. Future dates are read-only.</p>
        </div>

        <form method="GET" action="<?php echo e(route('attendance.bulk')); ?>" class="mb-4 grid gap-3 rounded-lg border border-slate-200 bg-slate-50 p-3 md:grid-cols-3 lg:grid-cols-6 ">
            <div>
                <label class="mb-1 block text-xs font-medium uppercase text-slate-500">Department</label>
                <select id="bulkDepartmentFilter" name="department_id" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2">
                    <option value="">All departments</option>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $departmentOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $department): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($department->id); ?>" <?php if((int) $selectedDepartmentId === (int) $department->id): echo 'selected'; endif; ?>><?php echo e($department->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </select>
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium uppercase text-slate-500">Location</label>
                <select id="bulkLocationFilter" name="location_id" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2">
                    <option value="">All locations</option>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $locationOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $location): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($location->id); ?>" <?php if((int) $selectedLocationId === (int) $location->id): echo 'selected'; endif; ?>><?php echo e($location->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </select>
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium uppercase text-slate-500">Employee</label>
                <select id="bulkEmployeeFilter" name="user_id" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2">
                    <option value="">All employees</option>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $markableUsers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($user->id); ?>" <?php if((int) $selectedUserId === (int) $user->id): echo 'selected'; endif; ?>><?php echo e($user->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </select>
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium uppercase text-slate-500">Year</label>
                <input type="number" min="2000" max="2100" name="year" value="<?php echo e($selectedYear); ?>" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium uppercase text-slate-500">Month</label>
                <select name="month" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm js-select2">
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php for($m = 1; $m <= 12; $m++): ?>
                        <option value="<?php echo e($m); ?>" <?php if((int) $selectedMonth === $m): echo 'selected'; endif; ?>><?php echo e(\Carbon\Carbon::createFromDate(2000, $m, 1)->format('F')); ?></option>
                    <?php endfor; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </select>
            </div>
            <div class="flex items-end">
                <button type="submit" class="inline-flex w-full items-center justify-center rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700">Apply</button>
            </div>
        </form>

        <div class="overflow-x-auto rounded-lg border border-slate-200">
            <table class="min-w-full text-sm">
                <thead class="bg-teal-600 text-white">
                    <tr>
                        <th class="sticky left-0 z-20 min-w-[220px] bg-teal-600 px-3 py-2 text-left text-xs font-semibold uppercase">Employee</th>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $days; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $day): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <th class="min-w-[34px] px-1 py-2 text-center text-xs font-semibold"><?php echo e($day['day']); ?></th>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        <th class="min-w-[78px] px-2 py-2 text-right text-xs font-semibold uppercase">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $matrixRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr class="border-t border-slate-200">
                            <td class="sticky left-0 z-10 bg-white px-3 py-2">
                                <p class="font-medium text-slate-900"><?php echo e($row['user']->name); ?></p>
                                <p class="text-xs text-slate-500"><?php echo e($row['user']->department?->name ?? 'No department'); ?></p>
                            </td>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $row['cells']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cell): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $symbol = match($cell['status']) {
                                        'present' => '✔',
                                        'half_day' => '◐',
                                        'leave' => '■',
                                        'holiday' => '▣',
                                        'weekoff' => '•',
                                        'not_joined' => '–',
                                        default => '✖',
                                    };
                                    $colorClass = match($cell['status']) {
                                        'present' => 'text-emerald-600',
                                        'half_day' => 'text-amber-600',
                                        'leave' => 'text-fuchsia-600',
                                        'holiday' => 'text-teal-600',
                                        'weekoff' => 'text-slate-400',
                                        'not_joined' => 'text-slate-300',
                                        default => 'text-red-500',
                                    };
                                ?>
                                <td class="px-1 py-1 text-center">
                                    <button
                                        type="button"
                                        class="bulk-status-cell inline-flex h-7 w-7 items-center justify-center rounded <?php echo e($cell['can_toggle'] ? 'hover:bg-slate-100' : 'cursor-not-allowed opacity-60'); ?> <?php echo e($colorClass); ?>"
                                        data-user-id="<?php echo e($row['user']->id); ?>"
                                        data-date="<?php echo e($cell['date']); ?>"
                                        data-status="<?php echo e($cell['status']); ?>"
                                        data-can-toggle="<?php echo e($cell['can_toggle'] ? '1' : '0'); ?>"
                                        title="<?php echo e(ucfirst(str_replace('_', ' ', $cell['status']))); ?>"
                                    ><?php echo e($symbol); ?></button>
                                </td>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            <td class="px-2 py-2 text-right text-sm font-semibold text-slate-700" data-total-for-user="<?php echo e($row['user']->id); ?>"><?php echo e($row['total_label']); ?></td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="<?php echo e(count($days) + 2); ?>" class="px-4 py-8 text-center text-sm text-slate-500">No employees available for the selected filters.</td>
                        </tr>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </tbody>
            </table>
        </div>
     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const departmentSelect = document.getElementById('bulkDepartmentFilter');
    const locationSelect = document.getElementById('bulkLocationFilter');
    const employeeSelect = document.getElementById('bulkEmployeeFilter');
    const employeeOptions = <?php echo json_encode($employeeOptions ?? [], 15, 512) ?>;

    function toNullableInt(value) {
        if (value === null || value === undefined || value === '') {
            return null;
        }
        const parsed = Number(value);
        return Number.isNaN(parsed) ? null : parsed;
    }

    function renderEmployeeOptions() {
        if (!departmentSelect || !locationSelect || !employeeSelect) {
            return;
        }

        const selectedDepartmentId = toNullableInt(departmentSelect.value);
        const selectedLocationId = toNullableInt(locationSelect.value);
        const previousSelectedUserId = toNullableInt(employeeSelect.value);

        const filteredUsers = employeeOptions.filter((user) => {
            const departmentOk = !selectedDepartmentId || toNullableInt(user.department_id) === selectedDepartmentId;
            const locationOk = !selectedLocationId || toNullableInt(user.location_id) === selectedLocationId;
            return departmentOk && locationOk;
        });

        employeeSelect.innerHTML = '';
        const allOption = document.createElement('option');
        allOption.value = '';
        allOption.textContent = 'All employees';
        employeeSelect.appendChild(allOption);

        let hasPreviousSelection = false;
        filteredUsers.forEach((user) => {
            const option = document.createElement('option');
            option.value = String(user.id);
            option.textContent = user.name;
            if (previousSelectedUserId && Number(user.id) === previousSelectedUserId) {
                option.selected = true;
                hasPreviousSelection = true;
            }
            employeeSelect.appendChild(option);
        });

        if (!hasPreviousSelection) {
            employeeSelect.value = '';
        }
    }

    if (departmentSelect && locationSelect && employeeSelect) {
        departmentSelect.addEventListener('change', renderEmployeeOptions);
        locationSelect.addEventListener('change', renderEmployeeOptions);
        renderEmployeeOptions();
    }

    const cells = Array.from(document.querySelectorAll('.bulk-status-cell'));
    if (!cells.length) {
        return;
    }

    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    const toggleUrl = <?php echo json_encode(route('attendance.bulk.toggle'), 15, 512) ?>;
    const statusCycle = ['absent', 'present', 'leave', 'half_day'];
    const statusUi = {
        absent: { symbol: '✖', className: 'text-red-500' },
        present: { symbol: '✔', className: 'text-emerald-600' },
        leave: { symbol: '■', className: 'text-fuchsia-600' },
        half_day: { symbol: '◐', className: 'text-amber-600' },
        holiday: { symbol: '▣', className: 'text-teal-600' },
        weekoff: { symbol: '•', className: 'text-slate-400' },
        not_joined: { symbol: '–', className: 'text-slate-300' }
    };

    function nextStatus(status) {
        const idx = statusCycle.indexOf(status);
        return idx === -1 ? 'present' : statusCycle[(idx + 1) % statusCycle.length];
    }

    function applyCellStatus(cell, status) {
        const ui = statusUi[status] || statusUi.absent;
        Object.values(statusUi).forEach((item) => cell.classList.remove(item.className));
        cell.classList.add(ui.className);
        cell.textContent = ui.symbol;
        cell.dataset.status = status;
        cell.title = status.replace('_', ' ');
    }

    async function toggleCell(cell) {
        if (cell.dataset.canToggle !== '1' || cell.dataset.loading === '1') {
            return;
        }
        const current = cell.dataset.status;
        const intended = nextStatus(current);
        const userId = cell.dataset.userId;
        const date = cell.dataset.date;
        const totalEl = document.querySelector(`[data-total-for-user="${userId}"]`);
        const oldTotal = totalEl ? totalEl.textContent : '';

        cell.dataset.loading = '1';
        applyCellStatus(cell, intended);

        try {
            const response = await fetch(toggleUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': token
                },
                body: JSON.stringify({
                    user_id: Number(userId),
                    date: date,
                    next_status: intended
                })
            });
            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.message || 'Unable to update status.');
            }
            applyCellStatus(cell, result.status);
            if (totalEl && result.total_label) {
                totalEl.textContent = result.total_label;
            }
        } catch (error) {
            applyCellStatus(cell, current);
            if (totalEl) {
                totalEl.textContent = oldTotal;
            }
            window.alert(error.message || 'Failed to update attendance.');
        } finally {
            cell.dataset.loading = '0';
        }
    }

    cells.forEach((cell) => {
        cell.addEventListener('click', function () {
            toggleCell(cell);
        });
    });
});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/kiyohr/v2_version/resources/views/attendance/create-bulk.blade.php ENDPATH**/ ?>