@extends('layouts.dashboard.adminapp')

@section('title', 'Employee Attendance')
@section('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .dt-buttons .btn {
            margin-right: 0.5rem !important;
            padding: 0.25rem 0.75rem !important;
            font-size: 0.95rem !important;
        }

        .modal-header {
            background-color: #236ac2;
        }
    </style>
@endsection
@section('content')
    <!-- Page Heading -->
    <div class="p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL / Employee Attendance</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Top Buttons -->
    

    <!-- Card Table -->
    <div class="card shadow mb-4">
        <div class="card-header gap-3">
        
            <button type="button" style="width: 200px;float:right;" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadModal">
                <i class="fas fa-upload"></i> Upload
            </button>
            <button type="button" style="width: 200px;float:right;margin-right: 10px;" class="btn btn-primary" onclick="openAddModal()">
                <i class="fas fa-plus"></i> Add
            </button>
        
        </div>
        <div class="card-header d-flex align-items-center">
            <i class="fas fa-table me-2"></i>
            <span class="fw-bold">Employee Attendance Records</span>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="attendanceTable" style="display: inline-table;" class="table table-bordered table-hover text-dark w-100">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>Employee Name</th>
                            <th>Employee ID</th>
                            <th>Gender</th>
                            <th>DOB</th>
                            <th>DOJ</th>
                            <th>Department</th>
                            <th>Designation</th>
                            <th>Days Worked</th>
                            <th>Sundays</th>
                            <th>Holidays</th>
                            <th>Leave</th>
                            <th>Paid Days</th>
                            <th>Absent</th>
                            <th>1st Shifts</th>
                            <th>Night Shifts</th>
                            <th>OT</th>
                            <th>Shortage</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($data as $row)
                            <tr class="text-center align-middle" id="row-{{ $row->id }}">
                                <td>{{ $row->employee_name }}</td>
                                <td>{{ $row->employee_id }}</td>
                                <td>{{ $row->gender }}</td>
                                <td>{{ $row->date_of_birth }}</td>
                                <td>{{ $row->date_of_joining }}</td>
                                <td>{{ $row->department }}</td>
                                <td>{{ $row->designation }}</td>
                                <td>{{ $row->days_worked }}</td>
                                <td>{{ $row->sundays_eligible }}</td>
                                <td>{{ $row->holidays }}</td>
                                <td>{{ $row->leave_enjoyed }}</td>
                                <td>{{ $row->total_paid_days }}</td>
                                <td>{{ $row->absent }}</td>
                                <td>{{ $row->first_shifts }}</td>
                                <td>{{ $row->night_shifts }}</td>
                                <td>{{ $row->ot_hours }}</td>
                                <td>{{ $row->shortage_hours }}</td>
                                <td>
                                    <button class="btn btn-warning btn-sm mb-1"
                                        onclick="editRow({{ $row->id }})">Edit</button>
                                    <button class="btn btn-danger btn-sm"
                                        onclick="deleteRow({{ $row->id }})">Delete</button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Upload Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form action="{{ route('admin.attendance.import') }}" method="POST" enctype="multipart/form-data"
                class="modal-content">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Upload Attendance File</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="file" name="import_file" class="form-control" required>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary">Upload</button>
                </div>
            </form>
        </div>
    </div>

    @php
        $fields = [
            'employee_name',
            'employee_id',
            'gender',
            'date_of_birth',
            'date_of_joining',
            'department',
            'designation',
            'days_worked',
            'sundays_eligible',
            'holidays',
            'leave_enjoyed',
            'total_paid_days',
            'absent',
            'first_shifts',
            'night_shifts',
            'ot_hours',
            'shortage_hours',
        ];

        $numericFields = [
            'days_worked',
            'sundays_eligible',
            'holidays',
            'leave_enjoyed',
            'total_paid_days',
            'absent',
            'first_shifts',
            'night_shifts',
            'ot_hours',
            'shortage_hours',
        ];
    @endphp

    <!-- Add Attendance Modal -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <form id="addAttendanceForm" action="{{ route('admin.attendance.store') }}" method="POST"
                class="modal-content">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Add Attendance</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body row">
                    @foreach ($fields as $field)
                        <div class="col-md-4 mb-2">
                            <label class="form-label">{{ ucwords(str_replace('_', ' ', $field)) }}</label>
                            @if ($field === 'gender')
                                <select name="gender" class="form-control" required>
                                    <option value="">-- Select Gender --</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>
                            @else
                                <input
                                    type="{{ in_array($field, ['date_of_birth', 'date_of_joining']) ? 'date' : (in_array($field, $numericFields) ? 'number' : 'text') }}"
                                    class="form-control" name="{{ $field }}" required>
                            @endif
                        </div>
                    @endforeach
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Attendance Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <form id="editAttendanceForm" method="POST" class="modal-content">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Edit Attendance</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body row">
                    @foreach ($fields as $field)
                        <div class="col-md-4 mb-2">
                            <label class="form-label">{{ ucwords(str_replace('_', ' ', $field)) }}</label>
                            @if ($field === 'gender')
                                <select name="gender" id="edit_gender" class="form-control" required>
                                    <option value="">-- Select Gender --</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>
                            @else
                                <input
                                    type="{{ in_array($field, ['date_of_birth', 'date_of_joining']) ? 'date' : (in_array($field, $numericFields) ? 'number' : 'text') }}"
                                    class="form-control" name="{{ $field }}" id="edit_{{ $field }}"
                                    required>
                            @endif
                        </div>
                    @endforeach
                </div>
                <input type="hidden" id="edit_id_hidden">
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Update</button>
                </div>
            </form>
        </div>
    </div>
    </div>
    </div>
@endsection

@section('scripts')
   
    <script>
        $(document).ready(function() {
            // DataTable with export buttons
            $('#attendanceTable').DataTable({
                dom: 'Bfrtip',
                buttons: [{
                        extend: 'copy',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'csv',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'excel',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'pdf',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'print',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'colvis',
                        className: 'btn btn-secondary btn-sm'
                    }
                ],
                responsive: true,
                destroy: true,
            });
        });

        function openAddModal() {
            $('#addAttendanceForm')[0].reset();
            const modal = new bootstrap.Modal(document.getElementById('addModal'));
            modal.show();
        }

        function editRow(id) {
            $.get(`{{ url('admin/attendance/edit') }}/${id}`, function(data) {
                Object.keys(data).forEach(function(key) {
                    $(`#edit_${key}`).val(data[key]);
                });
                $('#edit_id_hidden').val(id);
                const modal = new bootstrap.Modal(document.getElementById('editModal'));
                modal.show();
            });
        }

        $('#addAttendanceForm').submit(function(e) {
            e.preventDefault();
            const form = $(this);
            $.post(form.attr('action'), form.serialize(), () => location.reload())
                .fail(() => alert('Error adding record'));
        });

        $('#editAttendanceForm').submit(function(e) {
            e.preventDefault();
            const id = $('#edit_id_hidden').val();
            const url = `{{ url('admin/attendance/update') }}/${id}`;
            $.post(url, $(this).serialize(), () => location.reload())
                .fail(() => alert('Error updating record'));
        });

        function deleteRow(id) {
            if (confirm('Are you sure you want to delete this record?')) {
                $.ajax({
                    url: `{{ url('admin/attendance/delete') }}/${id}`,
                    type: 'DELETE',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: () => $(`#row-${id}`).remove(),
                    error: () => alert('Error deleting record')
                });
            }
        }
    </script>
@endsection
