<x-app-layout>
    @section('page-title', 'Manajemen Denda')

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="my-0 fw-bold">Manajemen Denda & Sanksi</h3>
            <p class="text-muted mb-0">Pantau pengguna terlambat dan berikan sanksi jika diperlukan.</p>
        </div>
    </div>

    {{-- FILTER SECTION --}}
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body py-3">
            <div class="row g-3 align-items-center">
                <div class="col-md-auto">
                    <span class="fw-bold text-muted"><i class="bi bi-funnel-fill me-1"></i> Filter Data:</span>
                </div>
                <div class="col-md-3">
                    <select id="filterKelas" class="form-select form-select-sm">
                        <option value="">Semua Kelas/Golongan</option>
                        @foreach ($listKelas as $kelas)
                        <option value="{{ $kelas }}">{{ $kelas }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <select id="filterBesaran" class="form-select form-select-sm">
                        <option value="">Semua Nominal</option>
                        <option value="ringan">Denda Ringan (< Rp 10.000)</option>
                        <option value="berat">Denda Berat (> Rp 10.000)</option>
                    </select>
                </div>
                <div class="col-md-auto ms-auto">
                    <button id="resetFilter" class="btn btn-sm btn-light border text-muted">
                        <i class="bi bi-arrow-counterclockwise"></i> Reset
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table id="dendaTable" class="table table-striped table-hover align-middle" style="width:100%">
                    <thead class="table-light">
                        <tr>
                            <th class="text-center" width="5%">NO</th>
                            <th width="25%">NAMA</th>
                            <th width="25%">BUKU TERLAMBAT</th>
                            <th width="15%">STATUS</th>
                            <th width="15%">DENDA</th>
                            <th width="15%">AKSI</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($siswaTelat as $item)
                        <tr>
                            <td class="text-center">{{ $loop->iteration }}</td>
                            <td>
                                <div class="fw-bold text-dark">{{ $item['peminjam'] }}</div>
                                <span class="badge bg-light text-secondary border mt-1 mb-1">{{ $item['kelas'] }}</span>
                                <div class="small text-muted">
                                    <i class="bi bi-telephone me-1"></i>{{ $item['nomor_hp'] }}
                                </div>
                            </td>
                            <td>
                                <ul class="mb-0 ps-3 small text-muted">
                                    @foreach ($item['books'] as $buku)
                                    <li>{{ $buku['judul'] }}</li>
                                    @endforeach
                                </ul>
                            </td>

                            {{-- KOLOM STATUS --}}
                            <td data-order="{{ $item['tenggat_kembali']->timestamp }}">
                                @if(isset($item['role']) && strtolower($item['role']) === 'guru')
                                <div class="fw-bold text-muted">-</div>
                                @else
                                <span class="badge bg-danger-subtle text-danger border border-danger-subtle rounded-pill px-3">
                                    Telat {{ $item['hari_terlambat'] }} Hari
                                </span>
                                <div class="small text-muted mt-1">
                                    Tenggat: {{ $item['tenggat_kembali']->format('d/m/Y') }}
                                </div>
                                @endif
                            </td>

                            <td data-order="{{ $item['total_denda'] }}">
                                @if($item['is_guru'])
                                <div class="fw-bold text-success">Bebas Denda</div>
                                <small class="text-muted" style="font-size: 0.75rem;">Kebijakan Guru</small>
                                @else
                                <div class="fw-bold text-danger">Rp
                                    {{ number_format($item['total_denda'], 0, ',', '.') }}
                                </div>
                                <small class="text-muted" style="font-size: 0.75rem;">Rp 1.000/hari</small>
                                @endif
                            </td>

                            {{-- KOLOM AKSI --}}
                            <td>
                                <div class="d-flex gap-2">
                                    {{-- Tombol WA (Muncul untuk semua) --}}
                                    <a href="{{ $item['wa_link'] }}" target="_blank"
                                        class="btn btn-sm btn-success text-white" title="Tagih via WhatsApp">
                                        <i class="bi bi-whatsapp"></i>
                                    </a>

                                    {{-- LOGIC TOMBOL AKTIFKAN / SANKSI --}}
                                    @if ($item['is_banned'])
                                    {{-- Jika sudah dibekukan (Otomatis/Manual), muncul tombol AKTIFKAN --}}
                                    <button class="btn btn-sm btn-outline-success btn-aktifkan"
                                        data-user-id="{{ $item['user_id'] }}"
                                        data-nama="{{ $item['peminjam'] }}" title="Aktifkan Kembali Akun">
                                        <i class="bi bi-shield-check"></i> Aktifkan
                                    </button>
                                    @else
                                    {{-- Jika belum dibekukan, muncul tombol SANKSI (Manual) --}}
                                    <button class="btn btn-sm btn-outline-danger btn-sanksi"
                                        data-user-id="{{ $item['user_id'] }}"
                                        data-nama="{{ $item['peminjam'] }}" title="Berikan Sanksi">
                                        <i class="bi bi-slash-circle"></i> Sanksi
                                    </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="6" class="text-center py-5">
                                <div class="text-muted opacity-50">
                                    <i class="bi bi-emoji-smile fs-1 mb-2 d-block"></i>
                                    <p class="mb-0">Tidak ada buku terlambat hari ini.</p>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        $(document).ready(function() {
            var table = $('#dendaTable').DataTable({
                order: [
                    [3, 'desc']
                ],

                columnDefs: [{
                    "searchable": false,
                    "orderable": false,
                    "targets": 0
                }],

                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Cari nama peminjam..."
                },
                dom: 'rtip'
            });

            table.on('order.dt search.dt', function() {
                table.column(0, {
                    search: 'applied',
                    order: 'applied'
                }).nodes().each(function(cell, i) {
                    cell.innerHTML = i + 1;
                });
            }).draw();

            $.fn.dataTable.ext.search.push(
                function(settings, data, dataIndex) {
                    var filterKelas = $('#filterKelas').val();
                    var filterBesaran = $('#filterBesaran').val();
                    var dataSiswa = data[1] || "";
                    var dataDendaRaw = data[4] || "0";
                    var dataDenda = parseInt(dataDendaRaw.replace(/[^0-9]/g, ''), 10);

                    if (filterKelas !== "" && !dataSiswa.includes(filterKelas)) return false;
                    if (filterBesaran === "ringan" && dataDenda >= 10000) return false;
                    if (filterBesaran === "berat" && dataDenda < 10000) return false;

                    return true;
                }
            );

            $('#filterKelas, #filterBesaran').change(function() {
                table.draw();
            });
            $('#resetFilter').click(function() {
                $('#filterKelas').val('');
                $('#filterBesaran').val('');
                table.draw();
            });
        });

        $(document).on('click', '.btn-sanksi', function() {
            const nama = $(this).data('nama');
            const userId = $(this).data('user-id');

            modernSwal.fire({
                title: 'Nonaktifkan Akun?',
                text: `Apakah Anda yakin ingin memberikan sanksi pembekuan akun kepada ${nama}?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Bekukan',
                confirmButtonColor: '#dc3545',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    modernSwal.fire({
                        title: 'Memproses...',
                        didOpen: () => Swal.showLoading()
                    });

                    $.ajax({
                        url: '{{ route('
                        admin.denda.sanksi ') }}',
                        method: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            user_id: userId,
                            action: 'ban'
                        },
                        success: function(response) {
                            if (response.status === 'success') {
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Sanksi Diterapkan',
                                    text: response.message
                                });
                                setTimeout(() => location.reload(), 1500);
                            } else {
                                modernSwal.fire('Gagal', response.message, 'error');
                            }
                        },
                        error: function() {
                            modernSwal.fire('Gagal', 'Terjadi kesalahan saat memproses data.', 'error');
                        }
                    });
                }
            });
        });

        $(document).on('click', '.btn-aktifkan', function() {
            const nama = $(this).data('nama');
            const userId = $(this).data('user-id');

            modernSwal.fire({
                title: 'Aktifkan Akun?',
                text: `Pastikan ${nama} sudah melunasi denda. Akun akan diaktifkan kembali.`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, Aktifkan',
                confirmButtonColor: '#198754',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    modernSwal.fire({
                        title: 'Memproses...',
                        didOpen: () => Swal.showLoading()
                    });

                    $.ajax({
                        url: '{{ route('
                        admin.denda.sanksi ') }}',
                        method: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            user_id: userId,
                            action: 'unban'
                        },
                        success: function(response) {
                            if (response.status === 'success') {
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Akun Diaktifkan',
                                    text: response.message
                                });
                                setTimeout(() => location.reload(), 1500);
                            } else {
                                modernSwal.fire('Gagal', response.message, 'error');
                            }
                        },
                        error: function() {
                            modernSwal.fire('Gagal', 'Terjadi kesalahan saat memproses data.', 'error');
                        }
                    });
                }
            });
        });
    </script>
    @endpush
</x-app-layout>