<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-piggy-bank text-primary"></i>
            <span class="fw-semibold">Laporan Tabungan</span>
            <?php if ($activePeriod): ?>
            <span class="badge bg-success"><?= esc($activePeriod['year_name']) ?> — <?= esc($activePeriod['semester']) ?></span>
            <?php endif; ?>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <?php if ($waConfigured && $waTabunganEnabled): ?>
            <div class="btn-group">
                <button type="button" class="btn btn-sm btn-success dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-whatsapp me-1"></i>Kirim Laporan
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="openSendModal('daily')"><i class="bi bi-calendar-day me-2"></i>Laporan Harian</a></li>
                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="openSendModal('monthly')"><i class="bi bi-calendar-month me-2"></i>Laporan Bulanan</a></li>
                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="openSendModal('yearly')"><i class="bi bi-calendar-year me-2"></i>Laporan Tahunan</a></li>
                </ul>
            </div>
            <?php else: ?>
            <button class="btn btn-sm btn-outline-secondary" disabled title="WhatsApp atau fitur laporan tabungan belum diaktifkan. Atur di Pengaturan WhatsApp.">
                <i class="bi bi-whatsapp me-1"></i>Kirim Laporan
            </button>
            <?php endif; ?>
            <a href="/tabungan/print-report?classroom_id=<?= $selectedClassroom ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-printer me-1"></i>Cetak PDF
            </a>
            <a href="/tabungan" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Kembali
            </a>
        </div>
    </div>
    <div class="card-body">
        <form method="get" class="row g-2 mb-3">
            <div class="col-md-4">
                <label class="form-label small text-muted mb-1">Tingkat</label>
                <select class="form-select form-select-sm" id="reportGrade" onchange="onReportGradeChange()">
                    <option value="">-- Semua Tingkat --</option>
                    <?php foreach ($grades as $grade): ?>
                    <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label small text-muted mb-1">Kelas</label>
                <select name="classroom_id" id="reportClassroom" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">-- Semua Kelas --</option>
                    <?php foreach ($classrooms as $c): ?>
                    <option value="<?= $c['id'] ?>" data-grade="<?= $c['grade_id'] ?>" <?= $selectedClassroom == $c['id'] ? 'selected' : '' ?>>
                        <?= esc($c['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <a href="/tabungan/report" class="btn btn-sm btn-outline-secondary w-100">
                    <i class="bi bi-x-circle me-1"></i>Reset Filter
                </a>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-sm table-hover" id="reportTable">
                <thead class="table-light">
                    <tr>
                        <th style="width:30px">
                            <input type="checkbox" class="form-check-input" id="selectAll" title="Pilih Semua">
                        </th>
                        <th>No</th>
                        <th>NIS</th>
                        <th>Nama</th>
                        <th>Kelas</th>
                        <th class="text-end">Total Setoran</th>
                        <th class="text-end">Total Penarikan</th>
                        <th class="text-end">Saldo</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($report)): ?>
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4">Belum ada data tabungan</td>
                    </tr>
                    <?php else: ?>
                    <?php $no = 1; $totalSetoran = 0; $totalPenarikan = 0; $totalSaldo = 0; ?>
                    <?php foreach ($report as $r): ?>
                    <?php $totalSetoran += $r['total_setoran']; $totalPenarikan += $r['total_penarikan']; $totalSaldo += $r['balance']; ?>
                    <tr>
                        <td>
                            <input type="checkbox" class="form-check-input student-check" value="<?= $r['student_id'] ?>" data-name="<?= esc($r['full_name']) ?>">
                        </td>
                        <td><?= $no++ ?></td>
                        <td class="small"><?= esc($r['nis']) ?></td>
                        <td class="fw-semibold small"><?= esc($r['full_name']) ?></td>
                        <td class="small"><?= esc($r['classroom_name']) ?></td>
                        <td class="text-end text-success"><?= number_format($r['total_setoran'], 0, ',', '.') ?></td>
                        <td class="text-end text-danger"><?= number_format($r['total_penarikan'], 0, ',', '.') ?></td>
                        <td class="text-end fw-bold"><?= number_format($r['balance'], 0, ',', '.') ?></td>
                        <td class="text-center">
                            <a href="/tabungan/detail/<?= $r['student_id'] ?>" class="btn btn-sm btn-outline-info">
                                <i class="bi bi-eye me-1"></i>Detail
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <?php if (!empty($report)): ?>
                <tfoot class="table-light fw-bold">
                    <tr>
                        <td colspan="5">Total</td>
                        <td class="text-end text-success"><?= number_format($totalSetoran, 0, ',', '.') ?></td>
                        <td class="text-end text-danger"><?= number_format($totalPenarikan, 0, ',', '.') ?></td>
                        <td class="text-end"><?= number_format($totalSaldo, 0, ',', '.') ?></td>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
        </div>
    </div>
</div>

<!-- Modal Kirim Laporan -->
<div class="modal fade" id="sendReportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="sendReportModalLabel">Kirim Laporan Tabungan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>
            <div class="modal-body">
                <p class="mb-3">Siswa terpilih: <strong id="selectedCount">0</strong></p>
                <input type="hidden" id="reportType">

                <div id="dailyInput" class="mb-3">
                    <label for="reportDate" class="form-label">Tanggal</label>
                    <input type="date" class="form-control" id="reportDate" value="<?= date('Y-m-d') ?>">
                </div>

                <div id="monthlyInput" class="mb-3 d-none">
                    <label for="reportMonth" class="form-label">Bulan</label>
                    <input type="month" class="form-control" id="reportMonth" value="<?= date('Y-m') ?>">
                </div>

                <div id="yearlyInput" class="mb-3 d-none">
                    <label for="reportPeriod" class="form-label">Periode Akademik</label>
                    <select class="form-select" id="reportPeriod">
                        <?php foreach ($periods as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= ($activePeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                            <?= esc($p['year_name']) ?> — <?= esc($p['semester']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-success" id="btnConfirmSend" onclick="submitSendReport()">
                    <i class="bi bi-whatsapp me-1"></i>Kirim
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const allClassrooms = [
    <?php foreach ($classrooms as $c): ?>
    { id: '<?= $c['id'] ?>', gradeId: '<?= $c['grade_id'] ?>', name: '<?= esc($c['name']) ?>' },
    <?php endforeach; ?>
];

function onReportGradeChange() {
    const gradeId = document.getElementById('reportGrade').value;
    const sel = document.getElementById('reportClassroom');
    sel.innerHTML = '<option value="">-- Semua Kelas --</option>';
    allClassrooms
        .filter(c => !gradeId || c.gradeId === gradeId)
        .forEach(c => sel.appendChild(new Option(c.name, c.id)));
    sel.form.submit();
}

// Checkbox selection
const selectAllCheckbox = document.getElementById('selectAll');
const studentCheckboxes = document.querySelectorAll('.student-check');
const selectedCountEl = document.getElementById('selectedCount');

function updateSelectedCount() {
    const count = document.querySelectorAll('.student-check:checked').length;
    if (selectedCountEl) selectedCountEl.textContent = count;
}

if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', function() {
        document.querySelectorAll('.student-check').forEach(cb => cb.checked = this.checked);
        updateSelectedCount();
    });
}

document.querySelectorAll('.student-check').forEach(cb => {
    cb.addEventListener('change', updateSelectedCount);
});

function getSelectedStudentIds() {
    return Array.from(document.querySelectorAll('.student-check:checked')).map(cb => cb.value);
}

// Modal handling
let sendReportModal = null;

function getSendReportModal() {
    if (!sendReportModal) {
        if (typeof bootstrap === 'undefined') {
            Swal.fire('Error', 'Library Bootstrap tidak tersedia. Silakan refresh halaman atau hubungi admin.', 'error');
            return null;
        }
        sendReportModal = new bootstrap.Modal(document.getElementById('sendReportModal'));
    }
    return sendReportModal;
}

function openSendModal(type) {
    const selected = getSelectedStudentIds();
    if (selected.length === 0) {
        Swal.fire('Perhatian', 'Silakan pilih minimal satu siswa terlebih dahulu.', 'warning');
        return;
    }

    document.getElementById('reportType').value = type;

    // Reset semua input menjadi hidden terlebih dahulu
    document.getElementById('dailyInput').classList.add('d-none');
    document.getElementById('monthlyInput').classList.add('d-none');
    document.getElementById('yearlyInput').classList.add('d-none');

    // Tampilkan input sesuai jenis laporan
    if (type === 'daily') {
        document.getElementById('dailyInput').classList.remove('d-none');
    } else if (type === 'monthly') {
        document.getElementById('monthlyInput').classList.remove('d-none');
    } else if (type === 'yearly') {
        document.getElementById('yearlyInput').classList.remove('d-none');
    }

    const titles = {
        daily: 'Kirim Laporan Harian',
        monthly: 'Kirim Laporan Bulanan',
        yearly: 'Kirim Laporan Tahunan',
    };
    document.getElementById('sendReportModalLabel').textContent = titles[type] ?? 'Kirim Laporan Tabungan';
    updateSelectedCount();
    const modal = getSendReportModal();
    if (modal) {
        modal.show();
    }
}

function submitSendReport() {
    const studentIds = getSelectedStudentIds();
    if (studentIds.length === 0) {
        Swal.fire('Perhatian', 'Silakan pilih minimal satu siswa.', 'warning');
        return;
    }

    const type = document.getElementById('reportType').value;
    const typeLabels = {
        daily: 'Laporan Harian',
        monthly: 'Laporan Bulanan',
        yearly: 'Laporan Tahunan',
    };
    const typeLabel = typeLabels[type] ?? 'Laporan Tabungan';

    const modal = getSendReportModal();
    if (modal) {
        modal.hide();
    }

    Swal.fire({
        title: 'Kirim Laporan?',
        html: `Anda akan mengirim <strong>${typeLabel}</strong> ke <strong>${studentIds.length}</strong> orang tua/wali siswa.<br><br>Apakah Anda yakin?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Ya, Kirim',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#198754',
        reverseButtons: true,
    }).then((result) => {
        if (!result.isConfirmed) {
            return;
        }

        // Validasi input sesuai jenis laporan
        let dateParam = '';
        if (type === 'daily') {
            dateParam = document.getElementById('reportDate').value;
            if (!dateParam) {
                Swal.fire('Perhatian', 'Silakan pilih tanggal laporan.', 'warning');
                return;
            }
        } else if (type === 'monthly') {
            dateParam = document.getElementById('reportMonth').value;
            if (!dateParam) {
                Swal.fire('Perhatian', 'Silakan pilih bulan laporan.', 'warning');
                return;
            }
        } else if (type === 'yearly') {
            dateParam = document.getElementById('reportPeriod').value;
            if (!dateParam) {
                Swal.fire('Perhatian', 'Silakan pilih periode akademik.', 'warning');
                return;
            }
        }

        const params = new URLSearchParams();
        params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
        params.append('report_type', type);
        studentIds.forEach(id => params.append('student_ids[]', id));

        if (type === 'daily') {
            params.append('report_date', dateParam);
        } else if (type === 'monthly') {
            params.append('report_month', dateParam);
        } else if (type === 'yearly') {
            params.append('report_period_id', dateParam);
        }

        Swal.fire({
            title: 'Mengirim...',
            html: 'Mohon tunggu, laporan sedang dikirim.',
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading(),
        });

        fetch('/tabungan/send-report', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
            body: params,
        })
        .then(async (r) => {
            const text = await r.text();
            try {
                return JSON.parse(text);
            } catch (e) {
                throw new Error('Response server bukan JSON: ' + text.substring(0, 200));
            }
        })
        .then(data => {
            let html = data.message ?? 'Tidak ada pesan dari server.';
            if (data.success && Array.isArray(data.errors) && data.errors.length > 0) {
                html += '<hr class="my-2">' + data.errors.slice(0, 5).map(e => '• ' + e).join('<br>');
                if (data.errors.length > 5) {
                    html += `<br><small>...dan ${data.errors.length - 5} error lainnya</small>`;
                }
            }

            if (data.success) {
                Swal.fire({
                    title: 'Berhasil Dikirim',
                    html: html,
                    icon: 'success',
                    confirmButtonText: 'OK',
                });
            } else {
                Swal.fire({
                    title: 'Gagal',
                    html: html,
                    icon: 'error',
                });
            }
        })
        .catch((err) => {
            console.error('Send report error:', err);
            Swal.fire('Error', err.message || 'Terjadi kesalahan koneksi.', 'error');
        });
    });
}
</script>

<?= $this->endSection() ?>
