<?php
// admin/data_pembayaran.php
include_once 'init.php'; 

$page_title = 'Data Jenis Pembayaran';
$page_icon = 'bi-credit-card-2-front-fill';

$action = $_POST['action'] ?? $_GET['action'] ?? '';

// === LOGIKA AJAX: BUKU TABUNGAN KANTONG PEMBAYARAN ===
if (isset($_GET['get_riwayat'])) {
    $id = $_GET['id_pembayaran'];
    
    // JOIN ke tabel siswa untuk mendapatkan nama pembayar
    $stmt = $pdo->prepare("SELECT tp.*, s.nama_siswa, dp.nama_pembayaran 
                           FROM transaksi_payment tp
                           LEFT JOIN siswa s ON tp.id_siswa = s.id_siswa
                           JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran
                           WHERE tp.id_pembayaran = ? AND tp.status = 'valid' 
                           ORDER BY tp.tanggal_verifikasi ASC");
    $stmt->execute([$id]);
    $riwayat = $stmt->fetchAll();
    
    $html = '';
    $saldo_berjalan = 0;
    foreach ($riwayat as $r) {
        $debet = ($r['id_siswa'] > 0) ? $r['jumlah'] : 0;
        $kredit = ($r['id_siswa'] == 0) ? $r['jumlah'] : 0;
        $saldo_berjalan += ($debet - $kredit);
        
        // Buat keterangan dinamis
        if ($debet > 0) {
            $ket = "Pembayaran " . $r['nama_pembayaran'] . " oleh " . ($r['nama_siswa'] ?: 'Siswa Dihapus');
        } else {
            $ket = "Penarikan Kas: " . ($r['keterangan'] ?: 'Tanpa Keterangan');
        }
        
        $html .= "<tr>
            <td class='text-start'>".date('d/m/y H:i', strtotime($r['tanggal_verifikasi']))."</td>
            <td class='text-start'>".htmlspecialchars($ket)."</td>
            <td class='text-end'>".($debet > 0 ? number_format($debet, 0, ',', '.') : '-')."</td>
            <td class='text-end'>".($kredit > 0 ? number_format($kredit, 0, ',', '.') : '-')."</td>
            <td class='text-end fw-bold'>".number_format($saldo_berjalan, 0, ',', '.')."</td>
        </tr>";
    }
    echo $html ?: '<tr><td colspan="5" class="text-center text-muted">Belum ada mutasi valid.</td></tr>';
    exit;
}
// === LOGIKA PROSES ===
try {
    if ($action === 'tambah_pembayaran') {
        $stmt = $pdo->prepare("INSERT INTO data_pembayaran (no_rekening, nama_pembayaran, nilai_satuan, saldo) VALUES (?, ?, ?, 0)");
        $stmt->execute([$_POST['no_rekening'], $_POST['nama_pembayaran'], $_POST['nilai_satuan']]);
        $_SESSION['message'] = "Jenis pembayaran baru berhasil ditambahkan.";
        header("Location: data_pembayaran.php"); exit();
    }

    if ($action === 'update_pembayaran') {
        $stmt = $pdo->prepare("UPDATE data_pembayaran SET no_rekening = ?, nama_pembayaran = ?, nilai_satuan = ? WHERE id_pembayaran = ?");
        $stmt->execute([$_POST['no_rekening'], $_POST['nama_pembayaran'], $_POST['nilai_satuan'], $_POST['id_pembayaran']]);
        $_SESSION['message'] = "Data pembayaran berhasil diperbarui.";
        header("Location: data_pembayaran.php"); exit();
    }

    if ($action === 'hapus_pembayaran' && isset($_POST['id_pembayaran_hapus'])) {
        $stmt = $pdo->prepare("DELETE FROM data_pembayaran WHERE id_pembayaran = ?");
        $stmt->execute([$_POST['id_pembayaran_hapus']]);
        $_SESSION['message'] = "Data pembayaran berhasil dihapus.";
        header("Location: data_pembayaran.php"); exit();
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Terjadi kesalahan: " . $e->getMessage();
    header("Location: data_pembayaran.php"); exit();
}

$pembayaranList = $pdo->query("SELECT * FROM data_pembayaran ORDER BY no_rekening ASC")->fetchAll(PDO::FETCH_ASSOC);

include 'header.php';
?>

<style>
    /* CSS Khusus Cetak Buku Tabungan Kantong */
    @media print {
        body * { visibility: hidden; }
        #modalView, #modalView .modal-content, #modalView .modal-content * { visibility: visible; }
        #modalView .modal-content { position: absolute; left: 0; top: 0; width: 100%; border: none; }
        #identitas_cetak_kantong {
            background-color: #f0f0f0 !important;
            -webkit-print-color-adjust: exact;
            padding: 15px;
            border: 1px solid #000;
            margin-bottom: 10px;
            text-align: left !important;
        }
        .table-print { width: 100%; border-collapse: collapse; }
        .table-print th, .table-print td {
            border: 1px solid #000 !important;
            padding: 6px;
            font-size: 12px;
        }
        .btn-printer-none, .btn-close, .modal-footer { display: none !important; }
        .table-responsive { overflow: visible !important; }
    }
</style>

<div class="content-card shadow-sm p-4 bg-white rounded">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h5 class="mb-0 fw-bold text-primary">Daftar Jenis Pembayaran</h5>
            <small class="text-muted">Kelola kategori tagihan dan nilai satuan pembayaran</small>
        </div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalPembayaran">
            <i class="bi bi-plus-circle me-1"></i> Tambah Jenis Pembayaran
        </button>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-success alert-dismissible fade show"><?= $_SESSION['message']; unset($_SESSION['message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="table table-hover align-middle border">
            <thead class="table-light">
                <tr>
                    <th width="5%">No</th>
                    <th>Nomor Rekening</th>
                    <th>Nama Pembayaran</th>
                    <th>Nilai Satuan</th>
                    <th class="text-end">Saldo</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php $no=1; foreach ($pembayaranList as $p): ?>
                <tr>
                    <td><?= $no++ ?></td>
                    <td><code><?= htmlspecialchars($p['no_rekening']) ?></code></td>
                    <td><strong><?= htmlspecialchars($p['nama_pembayaran']) ?></strong></td>
                    <td>Rp <?= number_format($p['nilai_satuan'], 0, ',', '.') ?></td>
                    <td class="text-end fw-bold text-primary">Rp <?= number_format($p['saldo'], 0, ',', '.') ?></td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary btn-view" 
                                    data-id="<?= $p['id_pembayaran'] ?>" 
                                    data-nama="<?= htmlspecialchars($p['nama_pembayaran']) ?>"
                                    data-rekening="<?= $p['no_rekening'] ?>"
                                    title="Lihat Buku Tabungan Kantong"><i class="bi bi-eye"></i></button>
                            <button class="btn btn-outline-warning btn-edit" 
                                    data-bs-toggle="modal" data-bs-target="#modalPembayaran"
                                    data-id="<?= $p['id_pembayaran'] ?>"
                                    data-rekening="<?= $p['no_rekening'] ?>"
                                    data-nama="<?= $p['nama_pembayaran'] ?>"
                                    data-nilai="<?= (int)$p['nilai_satuan'] ?>"><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-outline-danger btn-delete" 
                                    data-id="<?= $p['id_pembayaran'] ?>" 
                                    data-nama="<?= $p['nama_pembayaran'] ?>"><i class="bi bi-trash"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($pembayaranList)): ?>
                <tr><td colspan="6" class="text-center text-muted py-4">Belum ada data pembayaran.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalView" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white btn-printer-none">
                <h5 class="modal-title"><i class="bi bi-journal-text me-2"></i>Buku Tabungan Kantong</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div id="identitas_cetak_kantong" class="p-3 bg-light border-bottom text-start">
                    <h5 class="mb-1 fw-bold" id="view_nama_kantong"></h5>
                    <p class="mb-0 text-muted small">Nomor Rekening: <span id="view_rek_kantong" class="text-dark fw-bold"></span></p>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm table-striped mb-0 table-print">
                        <thead class="table-secondary small text-uppercase">
                            <tr>
                                <th class="text-start ps-3">Tanggal</th>
                                <th class="text-start">Keterangan</th>
                                <th class="text-end">Debet (+)</th>
                                <th class="text-end">Kredit (-)</th>
                                <th class="text-end pe-3">Saldo</th>
                            </tr>
                        </thead>
                        <tbody id="riwayat_body" class="small"></tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer btn-printer-none">
                <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Tutup</button>
                <button class="btn btn-primary btn-sm" onclick="window.print()"><i class="bi bi-printer me-1"></i> Cetak</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPembayaran" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="title_form">Input Data Pembayaran</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="id_pembayaran" id="id_pembayaran">
                <input type="hidden" name="action" id="action_form" value="tambah_pembayaran">
                <div class="mb-3"><label class="form-label small fw-bold">Nomor Rekening</label><input type="text" name="no_rekening" id="no_rekening" class="form-control" required></div>
                <div class="mb-3"><label class="form-label small fw-bold">Nama Pembayaran</label><input type="text" name="nama_pembayaran" id="nama_pembayaran" class="form-control" required></div>
                <div class="mb-3"><label class="form-label small fw-bold">Nilai Satuan (Rp)</label><input type="number" name="nilai_satuan" id="nilai_satuan" class="form-control" required></div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button><button type="submit" class="btn btn-primary btn-sm">Simpan Data</button></div>
        </form>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <form class="modal-content" method="POST">
            <div class="modal-body text-center py-4">
                <input type="hidden" name="id_pembayaran_hapus" id="delete_id">
                <input type="hidden" name="action" value="hapus_pembayaran">
                <i class="bi bi-exclamation-octagon text-danger display-4"></i>
                <h5 class="mt-3">Hapus Pembayaran <br><b id="nama_del"></b>?</h5>
                <div class="d-flex justify-content-center gap-2 mt-4"><button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button><button type="submit" class="btn btn-danger btn-sm">Ya, Hapus</button></div>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const viewModal = new bootstrap.Modal(document.getElementById('modalView'));
    document.querySelectorAll('.btn-view').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.dataset.id;
            document.getElementById('view_nama_kantong').innerText = this.dataset.nama;
            document.getElementById('view_rek_kantong').innerText = this.dataset.rekening;
            document.getElementById('riwayat_body').innerHTML = '<tr><td colspan="5" class="text-center py-3">Memuat data...</td></tr>';
            viewModal.show();
            fetch(`data_pembayaran.php?get_riwayat=1&id_pembayaran=${id}`)
                .then(r => r.text()).then(data => { document.getElementById('riwayat_body').innerHTML = data; });
        });
    });

    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', function() {
            document.getElementById('id_pembayaran').value = this.dataset.id;
            document.getElementById('no_rekening').value = this.dataset.rekening;
            document.getElementById('nama_pembayaran').value = this.dataset.nama;
            document.getElementById('nilai_satuan').value = this.dataset.nilai;
            document.getElementById('title_form').innerText = 'Update Data Pembayaran';
            document.getElementById('action_form').value = 'update_pembayaran';
        });
    });

    $('#modalPembayaran').on('hidden.bs.modal', function () {
        document.getElementById('action_form').value = 'tambah_pembayaran';
        document.getElementById('title_form').innerText = 'Input Data Pembayaran';
        document.getElementById('id_pembayaran, no_rekening, nama_pembayaran, nilai_satuan').value = '';
    });

    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            document.getElementById('delete_id').value = this.dataset.id;
            document.getElementById('nama_del').textContent = this.dataset.nama;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        });
    });
});
</script>

<?php include 'footer.php'; ?>