@extends('admin.layouts.app')

@section('content')
    <div class="bg-gray-50 min-h-full p-4 font-sans text-sm">

        <!-- Main Container -->
        <div class="bg-white shadow-sm border border-gray-200">

            <!-- Header -->
            <div class="flex items-center">
                <div class="bg-[#ff5722] text-white px-4 py-2 font-bold flex-1 flex items-center shadow-sm">
                    <i class="fa-solid fa-pen-to-square mr-2"></i> Manual Punch
                </div>
                <div class="bg-gray-200 text-gray-500 px-6 py-2 font-bold shadow-inner">
                    Shift Details
                </div>
            </div>

            @if(session('success'))
                <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-3 mx-4 mt-4 text-xs font-bold"
                    role="alert">
                    {{ session('success') }}
                </div>
            @endif
            @if($errors->any())
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-3 mx-4 mt-4 text-xs font-bold" role="alert">
                    @foreach($errors->all() as $error)
                        <p>{{ $error }}</p>
                    @endforeach
                </div>
            @endif

            <form action="{{ route('manual_punch.store') }}" method="POST" id="manualPunchForm">
                @csrf
                <div class="p-4 border-b border-gray-200">
                    <!-- Selection By Title -->
                    <h3 class="text-[#e64a19] font-bold text-sm mb-3">Selection By</h3>

                    <!-- Selection Grid -->
                    <div class="grid grid-cols-4 gap-4">

                        <!-- Removed Company Column -->

                        <!-- Branch Column -->
                        <div class="flex flex-col space-y-1">
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="branch_selection" value="all"
                                    class="text-[#ff5722] focus:ring-[#ff5722]" checked>
                                <span>All Branch</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="branch_selection" value="few"
                                    class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>Few Branch</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs cursor-pointer mt-2">
                                <input type="checkbox" id="selectAllBranch" class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>SelectAll/De-Select All</span>
                            </label>
                            <div class="border border-gray-300 h-48 overflow-y-auto mt-1 p-2 bg-white">
                                @foreach($branches as $branch)
                                    <label class="flex items-center space-x-2 text-xs cursor-pointer mb-1">
                                        <input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}"
                                            class="branch-checkbox text-[#ff5722] focus:ring-[#ff5722]">
                                        <span>{{ $branch->name }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>

                        <!-- Department Column -->
                        <div class="flex flex-col space-y-1">
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="department_selection" value="all"
                                    class="text-[#ff5722] focus:ring-[#ff5722]" checked>
                                <span>All Department</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="department_selection" value="few"
                                    class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>Few Department</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs cursor-pointer mt-2">
                                <input type="checkbox" id="selectAllDepartment" class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>SelectAll/De-Select All</span>
                            </label>
                            <div class="border border-gray-300 h-48 overflow-y-auto mt-1 p-2 bg-white">
                                @foreach($departments as $dept)
                                    <label class="flex items-center space-x-2 text-xs cursor-pointer mb-1">
                                        <input type="checkbox" name="department_ids[]" value="{{ $dept->id }}"
                                            class="department-checkbox text-[#ff5722] focus:ring-[#ff5722]">
                                        <span>{{ $dept->name }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>

                        <!-- Designation Column -->
                        <div class="flex flex-col space-y-1">
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="designation_selection" value="all"
                                    class="text-[#ff5722] focus:ring-[#ff5722]" checked>
                                <span>All Designation</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="designation_selection" value="few"
                                    class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>Few Designation</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs cursor-pointer mt-2">
                                <input type="checkbox" id="selectAllDesignation"
                                    class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>SelectAll/De-Select All</span>
                            </label>
                            <div class="border border-gray-300 h-48 overflow-y-auto mt-1 p-2 bg-white">
                                @foreach($designations as $desig)
                                    <label class="flex items-center space-x-2 text-xs cursor-pointer mb-1">
                                        <input type="checkbox" name="designation_ids[]" value="{{ $desig->id }}"
                                            class="designation-checkbox text-[#ff5722] focus:ring-[#ff5722]">
                                        <span>{{ $desig->name }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>

                        <!-- Employee Column -->
                        <div class="flex flex-col space-y-1">
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="employee_selection" value="all"
                                    class="text-[#ff5722] focus:ring-[#ff5722]" checked>
                                <span>All employee</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs font-semibold cursor-pointer">
                                <input type="radio" name="employee_selection" value="few"
                                    class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>Few Employee</span>
                            </label>
                            <label class="flex items-center space-x-2 text-xs cursor-pointer mt-2">
                                <input type="checkbox" id="selectAllEmployee" class="text-[#ff5722] focus:ring-[#ff5722]">
                                <span>SelectAll/De-Select All</span>
                            </label>
                            <div class="border border-gray-300 h-48 mt-1 bg-white flex flex-col">
                                <input type="text" id="employeeSearch" placeholder="Search employee"
                                    class="w-full border-b border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                <div class="overflow-y-auto flex-1 p-2">
                                    @foreach($employees as $emp)
                                        <label class="flex items-center space-x-2 text-xs cursor-pointer mb-1 employee-item">
                                            <input type="checkbox" name="employee_ids[]" value="{{ $emp->user_id }}"
                                                class="employee-checkbox text-[#ff5722] focus:ring-[#ff5722]">
                                            <span class="emp-name">{{ $emp->name }} ({{ $emp->employee_code }})</span>
                                        </label>
                                    @endforeach
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Bottom Forms Section -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-4">

                    <!-- Manual Punch Entry Form -->
                    <div class="border border-gray-200 shadow-sm bg-white">
                        <div class="bg-[#ff7043] text-white px-3 py-2 flex justify-between items-center text-sm font-bold">
                            <span>Manual Punch Entry</span>
                            <span class="text-xs">Time Format Should be (HH:MM) in 24 Hrs</span>
                        </div>

                        <div class="p-4 space-y-4">
                            <div class="grid grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-xs font-bold text-gray-800 mb-1">Date</label>
                                    <input type="date" name="punch_date"
                                        class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]"
                                        required>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold text-gray-800 mb-1">IN-Time</label>
                                    <input type="time" name="in_time"
                                        class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                </div>
                                <div>
                                    <label class="block text-xs font-bold text-gray-800 mb-1">Out Time</label>
                                    <input type="time" name="out_time"
                                        class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                </div>
                            </div>

                            <div class="grid grid-cols-3 gap-4">
                                <div class="col-span-2">
                                    <label class="block text-xs font-bold text-gray-800 mb-1">Remark</label>
                                    <textarea name="remark" rows="1"
                                        class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]"></textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold text-gray-800 mb-1">Select Device For
                                        In/Out</label>
                                    <select name="device"
                                        class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                        <option value="">▼</option>
                                        <option value="Web">Web</option>
                                        <option value="Mobile">Mobile</option>
                                    </select>
                                </div>
                            </div>

                            <button type="submit"
                                class="w-full bg-[#4caf50] hover:bg-[#43a047] text-white font-bold py-2 rounded text-sm transition shadow-sm mt-2">
                                Insert Punch
                            </button>
                            <div class="text-center font-bold text-xl leading-none mt-1">+</div>
                        </div>
                    </div>

                    <!-- View Punch Form -->
                    <div class="border border-gray-200 shadow-sm bg-white flex flex-col">
                        <div class="bg-[#ff7043] text-white px-3 py-2 flex justify-between items-center text-sm font-bold">
                            <span>View Punch</span>
                            <label class="flex items-center space-x-1 cursor-pointer">
                                <input type="checkbox" checked class="h-3 w-3">
                                <span class="text-xs">Show Manual Punch</span>
                            </label>
                        </div>

                        <div class="p-4 flex-1 flex flex-col">
                            <div class="flex items-end space-x-3 mb-4">
                                <div class="flex flex-col items-center">
                                    <label class="text-xs font-bold text-gray-800 mb-1">&nbsp;</label>
                                    <input type="checkbox"
                                        class="h-4 w-4 border-gray-300 rounded text-[#ff5722] focus:ring-[#ff5722]">
                                    <span class="text-[10px] font-bold mt-1">Select</span>
                                </div>
                                <div class="flex-1 grid grid-cols-2 gap-3">
                                    <div>
                                        <label class="block text-[11px] font-bold text-gray-800 mb-1">From Date:</label>
                                        <input type="date" id="viewFromDate"
                                            class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                    </div>
                                    <div>
                                        <label class="block text-[11px] font-bold text-gray-800 mb-1">To Date:</label>
                                        <input type="date" id="viewToDate"
                                            class="w-full border border-gray-300 px-2 py-1 text-xs focus:outline-none focus:border-[#ff5722]">
                                    </div>
                                </div>
                                <div class="flex space-x-2 pb-0.5">
                                    <button type="button" id="btnViewPunch"
                                        class="bg-[#4caf50] hover:bg-[#43a047] text-white px-3 py-1 rounded shadow-sm text-xs font-semibold transition">View
                                        Punch</button>
                                    <button type="button" id="btnDeletePunch"
                                        class="bg-[#4caf50] hover:bg-[#43a047] text-white px-3 py-1 rounded shadow-sm text-xs font-semibold transition">Delete</button>
                                </div>
                            </div>

                            <div class="flex justify-center mb-3">
                                <button type="button"
                                    class="bg-[#f44336] hover:bg-[#d32f2f] text-white px-6 py-1 rounded shadow-sm text-xs font-semibold transition">Close</button>
                            </div>

                            <!-- Data Table Placeholder -->
                            <div id="punchTableContainer"
                                class="flex-1 border border-gray-200 bg-gray-50 flex flex-col min-h-[200px] overflow-auto relative">
                                <div class="flex-1 flex items-center justify-center min-h-[100px]" id="noDataMsg">
                                    <span class="text-xs text-gray-500 font-semibold">No Data Found</span>
                                </div>
                                <table id="punchTable" class="min-w-full hidden bg-white text-xs text-left text-gray-600">
                                    <thead class="bg-gray-100 text-gray-800 font-bold border-b border-gray-200">
                                        <tr>
                                            <th class="px-2 py-1 text-center"><input type="checkbox" id="selectAllPunches">
                                            </th>
                                            <th class="px-2 py-1">Emp Name</th>
                                            <th class="px-2 py-1">Punch Date</th>
                                            <th class="px-2 py-1 border-r border-[#e64a19]">Check In</th>
                                            <th class="px-2 py-1 border-r border-[#e64a19]">Check Out</th>
                                            <th class="px-2 py-1 border-r border-[#e64a19]">Work Duration</th>
                                            <th class="px-2 py-1 border-r border-[#e64a19]">Break Before</th>
                                            <th class="px-2 py-1">Device Name</th>
                                            <th class="px-2 py-1">Remark</th>
                                        </tr>
                                    </thead>
                                    <tbody id="punchTableBody" class="divide-y divide-gray-100">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>
            </form>

        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Select All / De-select All logic
            function setupSelectAll(selectAllId, checkboxClass) {
                const selectAllCheckbox = document.getElementById(selectAllId);
                const checkboxes = document.querySelectorAll('.' + checkboxClass);

                if (selectAllCheckbox) {
                    selectAllCheckbox.addEventListener('change', function () {
                        checkboxes.forEach(cb => {
                            cb.checked = this.checked;
                        });
                    });

                    checkboxes.forEach(cb => {
                        cb.addEventListener('change', function () {
                            if (!this.checked) {
                                selectAllCheckbox.checked = false;
                            } else {
                                const allChecked = Array.from(checkboxes).every(c => c.checked);
                                selectAllCheckbox.checked = allChecked;
                            }
                        });
                    });
                }
            }

            // setupSelectAll('selectAllCompany', 'company-checkbox');
            setupSelectAll('selectAllBranch', 'branch-checkbox');
            setupSelectAll('selectAllDepartment', 'department-checkbox');
            setupSelectAll('selectAllDesignation', 'designation-checkbox');
            setupSelectAll('selectAllEmployee', 'employee-checkbox');

            // Employee search logic
            const searchInput = document.getElementById('employeeSearch');
            if (searchInput) {
                searchInput.addEventListener('keyup', function () {
                    const filter = this.value.toLowerCase();
                    const items = document.querySelectorAll('.employee-item');

                    items.forEach(item => {
                        const name = item.querySelector('.emp-name').textContent.toLowerCase();
                        if (name.includes(filter)) {
                            item.style.display = '';
                        } else {
                            item.style.display = 'none';
                        }
                    });
                });
            }

            // Handle "All" vs "Few" radio buttons (disable/enable lists)
            function handleRadioSelection(radioName, checkboxClass, selectAllId) {
                const radios = document.querySelectorAll(`input[name="${radioName}"]`);
                const checkboxes = document.querySelectorAll('.' + checkboxClass);
                const selectAll = document.getElementById(selectAllId);

                radios.forEach(radio => {
                    radio.addEventListener('change', function () {
                        const isFew = this.value === 'few';
                        checkboxes.forEach(cb => {
                            cb.disabled = !isFew;
                            if (!isFew) cb.checked = true; // Typically 'all' implies everything is checked
                            else cb.checked = false;      // Reset when switching to 'few'
                        });
                        if (selectAll) {
                            selectAll.disabled = !isFew;
                            selectAll.checked = !isFew;
                        }
                    });
                });

                // Trigger initial state
                const checkedRadio = document.querySelector(`input[name="${radioName}"]:checked`);
                if (checkedRadio) checkedRadio.dispatchEvent(new Event('change'));
            }

            // handleRadioSelection('company_selection', 'company-checkbox', 'selectAllCompany');
            handleRadioSelection('branch_selection', 'branch-checkbox', 'selectAllBranch');
            handleRadioSelection('department_selection', 'department-checkbox', 'selectAllDepartment');
            handleRadioSelection('designation_selection', 'designation-checkbox', 'selectAllDesignation');
            handleRadioSelection('employee_selection', 'employee-checkbox', 'selectAllEmployee');

            // AJAX View Punch Logic
            document.getElementById('btnViewPunch').addEventListener('click', function () {
                const fromDate = document.getElementById('viewFromDate').value;
                const toDate = document.getElementById('viewToDate').value;

                // Get selected employee IDs
                const selectedEmpCheckboxes = document.querySelectorAll('.employee-checkbox:checked');
                const employeeIds = Array.from(selectedEmpCheckboxes).map(cb => cb.value);

                const payload = {
                    _token: '{{ csrf_token() }}',
                    from_date: fromDate,
                    to_date: toDate,
                    employee_ids: employeeIds
                };

                const btn = this;
                btn.textContent = 'Loading...';
                btn.disabled = true;

                fetch('{{ route('manual_punch.view') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(payload)
                })
                    .then(res => res.json())
                    .then(data => {
                        btn.textContent = 'View Punch';
                        btn.disabled = false;

                        const tbody = document.getElementById('punchTableBody');
                        const table = document.getElementById('punchTable');
                        const noDataMsg = document.getElementById('noDataMsg');

                        tbody.innerHTML = '';

                        if (data.length === 0) {
                            table.classList.add('hidden');
                            noDataMsg.classList.remove('hidden');
                            return;
                        }

                        table.classList.remove('hidden');
                        noDataMsg.classList.add('hidden');

                        data.forEach(punch => {
                            const tr = document.createElement('tr');
                            tr.classList.add('hover:bg-orange-50');
                            tr.innerHTML = `
                            <td class="px-2 py-1 text-center"><input type="checkbox" class="punch-select" value="${punch.id}"></td>
                            <td class="px-2 py-1 font-semibold text-[#cc4c1f]">${punch.employee ? punch.employee.name + ' (' + punch.employee.employee_code + ')' : 'N/A'}</td>
                            <td class="px-2 py-1">${punch.punch_time}</td>
                            <td class="px-2 py-1">${punch.status === 'In' ? punch.punch_time : '-'}</td>
                            <td class="px-2 py-1">${punch.status === 'Out' ? punch.punch_time : '-'}</td>
                            <td class="px-2 py-1 font-bold text-green-600">${punch.work_duration_str}</td>
                            <td class="px-2 py-1 font-bold text-red-500">${punch.break_duration_str}</td>
                            <td class="px-2 py-1">${punch.device || '-'}</td>
                            <td class="px-2 py-1 truncate max-w-[100px]" title="${punch.remark || ''}">${punch.remark || '-'}</td>
                        `;
                            tbody.appendChild(tr);
                        });
                    })
                    .catch(err => {
                        btn.textContent = 'View Punch';
                        btn.disabled = false;
                        console.error(err);
                        alert('Failed to load punches. Please try again.');
                    });
            });

            // Select All for punches table
            document.getElementById('selectAllPunches')?.addEventListener('change', function () {
                const checkboxes = document.querySelectorAll('.punch-select');
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        });
    </script>
@endsection