@extends('layouts.app')

@section('title', 'Attendance Summary')
@section('heading', 'Attendance Summary')

@section('content')
@include('attendance.top-submenu')
    <x-card>
        <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="{{ 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>
                    @foreach($departmentOptions as $department)
                        <option value="{{ $department->id }}" @selected((int) $selectedDepartmentId === (int) $department->id)>{{ $department->name }}</option>
                    @endforeach
                </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>
                    @foreach($locationOptions as $location)
                        <option value="{{ $location->id }}" @selected((int) $selectedLocationId === (int) $location->id)>{{ $location->name }}</option>
                    @endforeach
                </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>
                    @foreach($markableUsers as $user)
                        <option value="{{ $user->id }}" @selected((int) $selectedUserId === (int) $user->id)>{{ $user->name }}</option>
                    @endforeach
                </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="{{ $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">
                    @for($m = 1; $m <= 12; $m++)
                        <option value="{{ $m }}" @selected((int) $selectedMonth === $m)>{{ \Carbon\Carbon::createFromDate(2000, $m, 1)->format('F') }}</option>
                    @endfor
                </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>
                        @foreach($days as $day)
                            <th class="min-w-[34px] px-1 py-2 text-center text-xs font-semibold">{{ $day['day'] }}</th>
                        @endforeach
                        <th class="min-w-[78px] px-2 py-2 text-right text-xs font-semibold uppercase">Total</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($matrixRows as $row)
                        <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">{{ $row['user']->name }}</p>
                                <p class="text-xs text-slate-500">{{ $row['user']->department?->name ?? 'No department' }}</p>
                            </td>
                            @foreach($row['cells'] as $cell)
                                @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',
                                    };
                                @endphp
                                <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 {{ $cell['can_toggle'] ? 'hover:bg-slate-100' : 'cursor-not-allowed opacity-60' }} {{ $colorClass }}"
                                        data-user-id="{{ $row['user']->id }}"
                                        data-date="{{ $cell['date'] }}"
                                        data-status="{{ $cell['status'] }}"
                                        data-can-toggle="{{ $cell['can_toggle'] ? '1' : '0' }}"
                                        title="{{ ucfirst(str_replace('_', ' ', $cell['status'])) }}"
                                    >{{ $symbol }}</button>
                                </td>
                            @endforeach
                            <td class="px-2 py-2 text-right text-sm font-semibold text-slate-700" data-total-for-user="{{ $row['user']->id }}">{{ $row['total_label'] }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="{{ count($days) + 2 }}" class="px-4 py-8 text-center text-sm text-slate-500">No employees available for the selected filters.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </x-card>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const departmentSelect = document.getElementById('bulkDepartmentFilter');
    const locationSelect = document.getElementById('bulkLocationFilter');
    const employeeSelect = document.getElementById('bulkEmployeeFilter');
    const employeeOptions = @json($employeeOptions ?? []);

    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 = @json(route('attendance.bulk.toggle'));
    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>
@endpush