@extends('layouts.app')

@section('title', 'Tagihan Pembayaran')

@push('styles')
<style>
    /* ── Stats Bar ── */
    .tunggakan-stats {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px 20px;
        background: linear-gradient(135deg, #fff3cd, #ffeaa7);
        border: 1px solid #ffc107;
        border-radius: 8px;
        padding: 12px 18px;
        margin-top: 12px;
    }
    .tunggakan-stats .stat-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .tunggakan-stats .stat-icon {
        font-size: 1.4rem;
        opacity: .75;
    }
    .tunggakan-stats .stat-body .stat-label {
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: .04em;
        color: #856404;
        line-height: 1.2;
    }
    .tunggakan-stats .stat-body .stat-value {
        font-size: 1rem;
        font-weight: 700;
        color: #212529;
        line-height: 1.2;
    }
    .tunggakan-stats .btn-kirim-semua {
        margin-left: auto;
    }

    /* ── Modal ── */
    #modalKirimSemua .modal-header {
        background: linear-gradient(135deg, #28a745, #1e7e34);
        color: #fff;
    }
    #modalKirimSemua .modal-header .close { color: #fff; opacity: .85; }
    #modalKirimSemua .modal-title { font-size: .95rem; font-weight: 700; }

    .siswa-check-list {
        max-height: 380px;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 6px;
    }
    .siswa-check-list .siswa-row {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 12px;
        border-bottom: 1px solid #f0f0f0;
        transition: background .15s;
    }
    .siswa-check-list .siswa-row:last-child { border-bottom: none; }
    .siswa-check-list .siswa-row:hover { background: #f8f9fa; }
    .siswa-check-list .siswa-row input[type=checkbox] {
        width: 16px; height: 16px; cursor: pointer; flex-shrink: 0;
    }
    .siswa-check-list .siswa-info { flex: 1; min-width: 0; }
    .siswa-check-list .siswa-name { font-weight: 600; font-size: .875rem; }
    .siswa-check-list .siswa-meta { font-size: .78rem; color: #6c757d; }
    .siswa-check-list .siswa-tunggakan {
        font-size: .8rem; font-weight: 700; color: #dc3545;
        white-space: nowrap;
    }

    .select-all-bar {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 12px;
        background: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
        font-size: .82rem;
    }

    /* Progress / loading */
    #kirimProgress { display: none; }
    .progress-info { font-size: .82rem; color: #6c757d; margin-top: 4px; }

    /* Toast Notifikasi */
    #waIndexToast {
        position: fixed; top: 20px; right: 20px; z-index: 9999;
        min-width: 300px; max-width: 420px;
        border-radius: 8px; padding: 14px 16px;
        display: none; box-shadow: 0 4px 16px rgba(0,0,0,.18);
        font-size: .88rem; align-items: flex-start; gap: 10px;
    }
    #waIndexToast.toast-success { background: #d4edda; border-left: 4px solid #28a745; color: #155724; }
    #waIndexToast.toast-error   { background: #f8d7da; border-left: 4px solid #dc3545; color: #721c24; }
    #waIndexToast .toast-icon   { font-size: 1.2rem; margin-top: 1px; flex-shrink: 0; }
    #waIndexToast .toast-close  { margin-left: auto; cursor: pointer; opacity: .6; flex-shrink: 0; }
</style>
@endpush

@section('content')
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card card-outline card-primary">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-search"></i> Cari Tagihan Siswa</h3>
            </div>
            <div class="card-body">
                <form action="{{ route('tagihan.cari') }}" method="GET">
                    <div class="input-group">
                        <select name="nis" id="search-nis" class="form-control" style="width: 100%;" required>
                            <option value="">Ketik NIS atau Nama Siswa...</option>
                        </select>
                        <div class="input-group-append">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Cari</button>
                        </div>
                    </div>
                </form>

                {{-- ── Stats Bar Tunggakan ── --}}
                @if($totalSiswaMenunggak > 0 || $totalTunggakanAll > 0)
                <div class="tunggakan-stats">
                    <div class="stat-item">
                        <i class="fas fa-users text-danger stat-icon"></i>
                        <div class="stat-body">
                            <div class="stat-label">Siswa Menunggak</div>
                            <div class="stat-value">{{ number_format($totalSiswaMenunggak) }} siswa</div>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-money-bill-wave text-danger stat-icon"></i>
                        <div class="stat-body">
                            <div class="stat-label">Total Tunggakan</div>
                            <div class="stat-value">Rp {{ number_format($totalTunggakanAll, 0, ',', '.') }}</div>
                        </div>
                    </div>
                    <div class="btn-kirim-semua">
                        <button type="button" id="btnKirimSemua" class="btn btn-success btn-sm"
                            data-toggle="modal" data-target="#modalKirimSemua">
                            <i class="fab fa-whatsapp mr-1"></i> Tagihan Tunggakan massal
                        </button>
                    </div>
                </div>
                @else
                <div class="alert alert-success mt-3 mb-0 py-2">
                    <i class="fas fa-check-circle"></i> Tidak ada siswa yang menunggak saat ini.
                </div>
                @endif

            </div>
        </div>
    </div>
</div>

{{-- ── Modal Kirim Semua Tagihan ── --}}
<div class="modal fade" id="modalKirimSemua" tabindex="-1" aria-labelledby="modalKirimSemuaLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalKirimSemuaLabel">
                    <i class="fab fa-whatsapp mr-1"></i> Kirim Tagihan ke Semua Siswa Menunggak
                </h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body py-2">

                {{-- Loading state --}}
                <div id="loadingDaftar" class="text-center py-4">
                    <i class="fas fa-spinner fa-spin fa-2x text-muted"></i>
                    <p class="text-muted mt-2 mb-0">Memuat daftar siswa...</p>
                </div>

                {{-- List area --}}
                <div id="daftarSiswaArea" style="display:none">
                    <p class="text-muted mb-2" style="font-size:.85rem">
                        Berikut daftar siswa yang memiliki tunggakan. Semua siswa <strong>dipilih secara default</strong>.
                        Anda dapat menghapus centang untuk mengecualikan siswa tertentu.
                    </p>

                    {{-- Select All bar --}}
                    <div class="select-all-bar">
                        <input type="checkbox" id="checkAll" checked>
                        <label for="checkAll" class="mb-0" style="cursor:pointer">
                            Pilih Semua &nbsp;|&nbsp; <span id="selectedCount">0</span> siswa dipilih
                        </label>
                        <span class="ml-auto text-muted" id="totalSiswaMeta"></span>
                    </div>

                    <div class="siswa-check-list" id="siswaCheckList">
                        {{-- diisi via JS --}}
                    </div>
                </div>

                {{-- Empty state --}}
                <div id="emptyDaftar" style="display:none" class="text-center py-4">
                    <i class="fas fa-check-circle fa-3x text-success"></i>
                    <p class="mt-2 text-success font-weight-bold">Tidak ada siswa yang menunggak!</p>
                </div>

                {{-- Progress state --}}
                <div id="kirimProgress" class="mt-3">
                    <div class="progress" style="height:6px">
                        <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" style="width:0%"></div>
                    </div>
                    <p class="progress-info mt-1" id="progressText">Mengirim 0 dari 0...</p>
                </div>
            </div>
            <div class="modal-footer py-2">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Batal</button>
                <button type="button" id="btnKirimPesan" class="btn btn-success btn-sm" disabled>
                    <i class="fab fa-whatsapp mr-1"></i> Kirim Pesan
                </button>
            </div>
        </div>
    </div>
</div>

{{-- Toast Bulk WA --}}
<div id="waIndexToast">
    <i class="toast-icon fas"></i>
    <div id="waIndexToastMsg" style="flex:1"></div>
    <span class="toast-close" onclick="$(this).closest('#waIndexToast').fadeOut();">&#x2715;</span>
</div>

@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // ── Select2 NIS search ──
    $('#search-nis').select2({
        theme: 'bootstrap4',
        width: '100%',
        placeholder: 'Ketik NIS atau Nama Siswa...',
        allowClear: true,
        minimumInputLength: 1,
        ajax: {
            url: '{{ route("ajax.search-nis") }}',
            dataType: 'json',
            delay: 300,
            data: function(params) { return { q: params.term }; },
            processResults: function(data) { return data; },
            cache: true
        }
    });

    // ── State ──
    let siswaData = [];

    // ── Load daftar saat modal dibuka ──
    $('#modalKirimSemua').on('show.bs.modal', function() {
        $('#loadingDaftar').show();
        $('#daftarSiswaArea').hide();
        $('#emptyDaftar').hide();
        $('#kirimProgress').hide();
        $('#btnKirimPesan').prop('disabled', true);
        $('#siswaCheckList').empty();
        siswaData = [];

        $.ajax({
            url: '{{ route("ajax.tagihan.daftar-tunggakan") }}',
            method: 'GET',
            success: function(res) {
                $('#loadingDaftar').hide();

                if (!res.success || res.data.length === 0) {
                    $('#emptyDaftar').show();
                    return;
                }

                siswaData = res.data;
                renderSiswaList(siswaData);
                updateSelectedCount();
                $('#daftarSiswaArea').show();
                $('#btnKirimPesan').prop('disabled', false);
                $('#totalSiswaMeta').text('Total: ' + res.total + ' siswa');
            },
            error: function() {
                $('#loadingDaftar').hide();
                $('#siswaCheckList').html('<p class="text-danger text-center py-3"><i class="fas fa-exclamation-triangle"></i> Gagal memuat data. Silakan coba lagi.</p>');
                $('#daftarSiswaArea').show();
            }
        });
    });

    // ── Render list ──
    function renderSiswaList(data) {
        var html = '';
        data.forEach(function(s, idx) {
            html += '<div class="siswa-row">' +
                '<input type="checkbox" class="siswa-checkbox" id="chk_' + idx + '" ' +
                    'data-idx="' + idx + '" checked>' +
                '<label for="chk_' + idx + '" class="siswa-info mb-0" style="cursor:pointer">' +
                    '<div class="siswa-name">' + escHtml(s.nama_lengkap) + '</div>' +
                    '<div class="siswa-meta">' +
                        '<i class="fas fa-id-card mr-1"></i>' + escHtml(s.nis) +
                        ' &nbsp;|&nbsp; <i class="fas fa-school mr-1"></i>' + escHtml(s.kelas) +
                        ' &nbsp;|&nbsp; <i class="fab fa-whatsapp mr-1"></i>' + escHtml(s.no_wa) +
                    '</div>' +
                '</label>' +
                '<span class="siswa-tunggakan">Rp ' + formatRupiah(s.total_tunggakan) + '</span>' +
            '</div>';
        });
        $('#siswaCheckList').html(html);
    }

    // ── Helper ──
    function escHtml(str) {
        return $('<div>').text(str || '').html();
    }
    function formatRupiah(num) {
        return Math.round(num).toLocaleString('id-ID');
    }

    // ── Update counter ──
    function updateSelectedCount() {
        var count = $('.siswa-checkbox:checked').length;
        $('#selectedCount').text(count);
        $('#btnKirimPesan').prop('disabled', count === 0);
        // Sinkronisasi checkAll
        var total = $('.siswa-checkbox').length;
        if (count === 0) {
            $('#checkAll').prop('indeterminate', false).prop('checked', false);
        } else if (count === total) {
            $('#checkAll').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#checkAll').prop('indeterminate', true);
        }
    }

    // ── Check all ──
    $('#checkAll').on('change', function() {
        $('.siswa-checkbox').prop('checked', $(this).is(':checked'));
        updateSelectedCount();
    });

    // ── Individual checkbox ──
    $(document).on('change', '.siswa-checkbox', function() {
        updateSelectedCount();
    });

    // ── Kirim Pesan via Fonnte (bulk) ──
    $('#btnKirimPesan').on('click', function() {
        var selected = [];
        $('.siswa-checkbox:checked').each(function() {
            var idx = parseInt($(this).data('idx'));
            selected.push({
                nis   : siswaData[idx].nis,
                no_wa : siswaData[idx].no_wa,
                pesan : siswaData[idx].pesan,
            });
        });

        if (selected.length === 0) {
            alert('Tidak ada siswa yang dipilih.');
            return;
        }

        // Konfirmasi
        if (!confirm('Anda akan mengirim notifikasi WhatsApp via Fonnte ke ' + selected.length + ' siswa yang dipilih.\n\nLanjutkan?')) {
            return;
        }

        // Tampilkan progress
        $('#daftarSiswaArea').hide();
        $('#kirimProgress').show();
        $('#btnKirimPesan').prop('disabled', true);
        $('#progressBar').css('width', '30%');
        $('#progressText').text('Mengirim ke ' + selected.length + ' siswa via Fonnte...');

        $.ajax({
            url: '{{ route("ajax.tagihan.kirim-wa-bulk") }}',
            method: 'POST',
            contentType: 'application/json',
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            data: JSON.stringify({ siswa: selected }),
            success: function(res) {
                $('#progressBar').css('width', '100%');
                var berhasil = res.berhasil_count || 0;
                var gagal    = res.gagal_count    || 0;

                var msg = '<strong>' + berhasil + ' pesan berhasil dikirim</strong>';
                if (gagal > 0) {
                    msg += ', <strong>' + gagal + ' gagal</strong>';
                    if (res.gagal && res.gagal.length > 0) {
                        msg += ':<ul class="mb-0 mt-1" style="padding-left:16px;font-size:.82rem">';
                        res.gagal.forEach(function(g) {
                            msg += '<li>NIS ' + g.nis + ': ' + g.reason + '</li>';
                        });
                        msg += '</ul>';
                    }
                    showIndexToast('error', msg);
                } else {
                    showIndexToast('success', msg + '.');
                }

                $('#progressText').text('Selesai! ' + berhasil + ' berhasil, ' + gagal + ' gagal.');
                $('#btnKirimPesan').text('Tutup').prop('disabled', false)
                    .removeClass('btn-success').addClass('btn-secondary')
                    .off('click').on('click', function() {
                        $('#modalKirimSemua').modal('hide');
                    });
            },
            error: function(xhr) {
                $('#progressBar').css('width', '100%').removeClass('bg-success').addClass('bg-danger');
                var msg = xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : 'Terjadi kesalahan server.';
                $('#progressText').text('Gagal: ' + msg);
                showIndexToast('error', '<strong>Gagal mengirim!</strong> ' + msg);
                $('#btnKirimPesan').text('Coba Lagi').prop('disabled', false)
                    .removeClass('btn-secondary').addClass('btn-success')
                    .off('click');
                // Re-init click handler on retry
                $('#btnKirimPesan').on('click', arguments.callee);
            }
        });
    });

    function showIndexToast(type, msg) {
        var $t = $('#waIndexToast');
        $t.removeClass('toast-success toast-error').addClass('toast-' + type);
        $t.find('.toast-icon').removeClass('fa-check-circle fa-times-circle')
            .addClass(type === 'success' ? 'fa-check-circle' : 'fa-times-circle');
        $('#waIndexToastMsg').html(msg);
        $t.css('display', 'flex').hide().fadeIn(300);
        if (type === 'success') setTimeout(function(){ $t.fadeOut(400); }, 6000);
    }

    // ── Reset modal saat ditutup ──
    $('#modalKirimSemua').on('hidden.bs.modal', function() {
        $('#btnKirimPesan').text('Kirim Pesan')
            .removeClass('btn-secondary').addClass('btn-success')
            .prop('disabled', true).off('click');
        $('#daftarSiswaArea').hide();
        $('#kirimProgress').hide();
        $('#progressBar').css('width', '0%').removeClass('bg-danger').addClass('bg-success');
    });
});
</script>
@endpush
