<x-app-layout>
    @section('title', 'Karyawan')
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Employees') }}
        </h2>
    </x-slot>

    <!-- Custom Styles for DataTables Modernization -->
    <style>
        /* Force rounded corners for the 'Show entries' dropdown */
        .dataTables_wrapper .dataTables_length select {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 2.25rem 0.375rem 0.75rem !important;
            background-position: right 0.5rem center !important;
        }

        /* Force rounded corners for the 'Search' input */
        .dataTables_wrapper .dataTables_filter input {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 0.75rem !important;
            margin-left: 0.5rem !important;
        }

        /* Pagination buttons styling */
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 0.375rem !important; /* rounded-md */
            border: 1px solid #e5e7eb !important;
            background: white !important;
            color: #374151 !important;
            margin: 0 0.125rem !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #eff6ff !important; /* blue-50 */
            border-color: #3b82f6 !important; /* blue-500 */
            color: #1d4ed8 !important; /* blue-700 */
            font-weight: 600 !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #f3f4f6 !important; /* gray-100 */
            border-color: #d1d5db !important;
            color: #111827 !important;
        }

        /* Table header styling */
        table.dataTable thead th {
             border-bottom: 2px solid #e5e7eb !important;
             color: #4b5563;
             font-weight: 600;
             text-transform: uppercase;
             font-size: 0.75rem;
             letter-spacing: 0.05em;
        }

        /* Responsive styling tweaks */
        @media (max-width: 640px) {
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter {
                text-align: left !important;
                margin-bottom: 0.5rem;
            }
            .dataTables_wrapper .dataTables_filter input {
                width: 100% !important;
                margin-left: 0 !important;
                margin-top: 0.25rem;
            }
            .dataTables_wrapper .dataTables_filter input {
                width: 100% !important;
                margin-left: 0 !important;
                margin-top: 0.25rem;
            }
        }
    </style>

    <link href="{{ asset('assets/css/jquery.dataTables.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/css/responsive.dataTables.min.css') }}" rel="stylesheet">

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-lg sm:rounded-xl">
                <div class="p-6 text-gray-900">

                    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 gap-4">
                        <h3 class="text-xl font-bold text-gray-800 self-start sm:self-center">Daftar Karyawan</h3>
                        <a href="javascript:void(0)" id="createNewEmployee" style="background-color: #3b82f6; color: white; border-radius: 8px;" class="w-full sm:w-auto bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow transition duration-150 ease-in-out flex items-center justify-center gap-2">
                             <span>+ Tambah Karyawan</span>
                        </a>
                    </div>

                    <div class="rounded-lg border border-gray-100 p-2">
                        <table class="display nowrap" id="data-table" width="100%">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">NIK</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Departemen</th>
                                    <th class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="ajaxModel" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity backdrop-filter backdrop-blur-sm" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form id="employeeForm" name="employeeForm" class="form-horizontal" enctype="multipart/form-data">
                    <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                        <div class="sm:flex sm:items-start">
                            <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                                <h3 class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4" id="modelHeading"></h3>
                                <div class="mt-2 space-y-5">
                                    <input type="hidden" name="id" id="employee_id">

                                    <div>
                                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Nama <span class="text-red-500">*</span></label>
                                        <input type="text" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="name" name="name" placeholder="Masukkan Nama" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="nik" class="block text-sm font-medium text-gray-700 mb-1">NIK</label>
                                        <input type="text" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="nik" name="nik" placeholder="Masukkan NIK">
                                    </div>

                                    <div class="mt-4">
                                        <label for="department" class="block text-sm font-medium text-gray-700 mb-1">Departemen</label>
                                        <input type="text" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="department" name="department" placeholder="Masukkan Departemen">
                                    </div>

                                    <div class="mt-4">
                                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email <span class="text-red-500">*</span></label>
                                        <input type="email" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="email" name="email" placeholder="Masukkan Email" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password <span class="text-xs text-gray-500" id="password-hint">(Wajib untuk user baru)</span></label>
                                        <input type="password" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="password" name="password" placeholder="Masukkan Password">
                                    </div>

                                    <div class="mt-4">
                                        <label for="image" class="block text-sm font-medium text-gray-700 mb-1">Foto (Opsional)</label>
                                        <input type="file" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" id="image" name="image" accept="image/*">
                                        <div id="image-preview" class="mt-2 hidden">
                                            <img id="preview-img" src="" alt="Preview" class="w-20 h-20 object-cover rounded-full border border-gray-200 shadow-sm">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2">
                        <button type="submit" style="background-color: #2563eb; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm" id="saveBtn" value="create">Simpan</button>
                        <button type="button" style="background-color: white; color: #374151; border: 1px solid #d1d5db; border-radius: 8px;" class="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm" id="closeModal">Batal</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="{{ asset('assets/js/jquery.min.js') }}"></script>
    <script src="{{ asset('assets/js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('assets/js/dataTables.responsive.min.js') }}"></script>
    <script src="{{ asset('assets/js/sweetalert2.all.min.js') }}"></script>

    <script type="text/javascript">
        $(function () {

            // SweetAlert2 Toast Configuration
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var table = $('#data-table').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                autoWidth: false,
                ajax: "{{ route('employees.index') }}",
                columnDefs: [
                    { responsivePriority: 1, targets: 0 }, // No
                    { responsivePriority: 2, targets: 2 }, // Name
                    { responsivePriority: 3, targets: -1 }, // Action
                ],
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
                    {data: 'image_display', name: 'image_display', orderable: false, searchable: false},
                    {data: 'name', name: 'name'},
                    {data: 'nik', name: 'nik'},
                    {data: 'department', name: 'department'},
                    {data: 'action', name: 'action', orderable: false, searchable: false, className: "text-center"},
                ],
                // Add language customization for better UX
                language: {
                    "sEmptyTable":   "Tidak ada data karyawan",
                    "sProcessing":   "Sedang memproses...",
                    "sLengthMenu":   "Tampilkan _MENU_ entri",
                    "sZeroRecords":  "Tidak ditemukan data yang sesuai",
                    "sSearch":       "Cari:",
                    "oPaginate": { "sFirst": "Pertama", "sPrevious": "Sebelumnya", "sNext": "Selanjutnya", "sLast": "Terakhir" }
                }
            });

            // Image Preview
            $('#image').change(function() {
                var file = this.files[0];
                if (file) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#preview-img').attr('src', e.target.result);
                        $('#image-preview').removeClass('hidden');
                    }
                    reader.readAsDataURL(file);
                } else {
                    $('#image-preview').addClass('hidden');
                }
            });

            $('#createNewEmployee').click(function () {
                $('#saveBtn').val("create-employee");
                $('#saveBtn').html("Simpan");
                $('#employee_id').val('');
                $('#employeeForm').trigger("reset");
                $('#image-preview').addClass('hidden');
                $('#modelHeading').html("Tambah Karyawan Baru");
                $('#password-hint').text('(Wajib diisi)');
                $('#password').prop('required', true);
                $('#ajaxModel').removeClass('hidden');
            });

            $('body').on('click', '.edit', function () {
                var id = $(this).data('id');
                $.get("{{ route('employees.index') }}" +'/' + id +'/edit', function (data) {
                    $('#modelHeading').html("Edit Karyawan");
                    $('#saveBtn').val("edit-employee");
                    $('#saveBtn').html("Update Data");
                    $('#ajaxModel').removeClass('hidden');
                    $('#employee_id').val(data.id);
                    $('#name').val(data.name);
                    $('#nik').val(data.nik);
                    $('#department').val(data.department);
                    $('#email').val(data.email);

                    // Image preview logic
                    if (data.image) {
                        $('#preview-img').attr('src', '{{ asset("storage") }}/' + data.image);
                        $('#image-preview').removeClass('hidden');
                    } else {
                        $('#image-preview').addClass('hidden');
                    }

                    $('#password-hint').text('(Kosongkan jika tidak ingin mengubah)');
                    $('#password').prop('required', false);
                    $('#password').val('');
                })
            });

            $('#saveBtn').click(function (e) {
                e.preventDefault();

                // Validation Check
                if (!$('#employeeForm')[0].checkValidity()) {
                    $('#employeeForm')[0].reportValidity();
                    return;
                }

                $(this).html('Mengirim...');
                var id = $('#employee_id').val();
                var url = id ? "{{ route('employees.index') }}" + '/' + id : "{{ route('employees.store') }}";
                var type = id ? "PUT" : "POST";

                // Use FormData for file upload
                var formData = new FormData($('#employeeForm')[0]);
                if (type === "PUT") {
                    formData.append('_method', 'PUT');
                }

                $.ajax({
                    data: formData, // Use formData
                    url: url,
                    type: "POST", // Always POST for FormData (handled by _method for PUT)
                    dataType: 'json',
                    processData: false, // Required for FormData
                    contentType: false, // Required for FormData
                    success: function (data) {
                        $('#employeeForm').trigger("reset");
                        $('#ajaxModel').addClass('hidden');
                        table.draw();
                        $('#saveBtn').html('Simpan');

                        Toast.fire({
                            icon: 'success',
                            title: 'Berhasil',
                            text: data.success
                        });
                    },
                    error: function (data) {
                        console.log('Error:', data);
                        $('#saveBtn').html('Simpan');

                        let errorMessage = 'Terjadi kesalahan.';
                        if (data.status === 422) {
                             let errors = data.responseJSON.errors;
                             errorMessage = '';
                             $.each(errors, function(key, value) {
                                 errorMessage += value[0] + '<br>';
                             });
                        }

                        Toast.fire({
                            icon: 'error',
                            title: 'Gagal',
                            html: errorMessage
                        });
                    }
                });
            });

            $('body').on('click', '.delete', function () {
                var id = $(this).data("id");
                Swal.fire({
                    title: 'Delete this data?',
                    text: "You won't be able to revert this!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ route('employees.store') }}"+'/'+id,
                            success: function (data) {
                                table.draw();
                                // Success Toast for Delete
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Record has been deleted.'
                                });
                            },
                            error: function (data) {
                                console.log('Error:', data);
                                // Error Toast for Delete
                                Toast.fire({
                                    icon: 'error',
                                    title: 'Something went wrong.'
                                });
                            }
                        });
                    }
                })
            });

            $('body').on('click', '#closeModal', function() {
                $('#ajaxModel').addClass('hidden');
            });
        });
    </script>
</x-app-layout>
