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

$page_title = 'Setoran Tunai';
$page_icon = 'bi-arrow-down-circle-fill';

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

// === LOGIKA PROSES TRANSAKSI ===
try {
    // 1. Simpan Setoran Baru
    if ($action === 'simpan_setoran') {
        $id_siswa = $_POST['id_siswa'];
        $jumlah = $_POST['jumlah'];
        $tanggal = $_POST['tanggal_transaksi'];
        $keterangan = $_POST['keterangan'] ?? 'Setoran Tunai';
        $role_input = $_SESSION['role'] ?? 'Admin';

        $pdo->prepare("INSERT INTO transaksi (id_siswa, jenis_transaksi, jumlah, keterangan, tanggal_transaksi, status, input_by) 
                       VALUES (?, 'setoran', ?, ?, ?, 'pending', ?)")
            ->execute([$id_siswa, $jumlah, $keterangan, $tanggal, $role_input]);

        $_SESSION['message'] = "Setoran berhasil disimpan dengan status PENDING.";
        header("Location: setoran.php"); exit();
    }

    // 2. Verifikasi Tunggal & Massal
    if (($action === 'verifikasi' && isset($_GET['id'])) || $action === 'verifikasi_massal') {
        $ids = ($action === 'verifikasi_massal') ? ($_POST['trx_ids'] ?? []) : [$_GET['id']];
        
        if (!empty($ids)) {
            $pdo->beginTransaction();
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $pdo->prepare("SELECT id_transaksi, id_siswa, jumlah FROM transaksi WHERE id_transaksi IN ($placeholders) AND status = 'pending'");
            $stmt->execute($ids);
            $to_verify = $stmt->fetchAll();

            foreach ($to_verify as $trx) {
                $pdo->prepare("UPDATE transaksi SET status = 'valid', tanggal_verifikasi = NOW() WHERE id_transaksi = ?")
                    ->execute([$trx['id_transaksi']]);
                $pdo->prepare("UPDATE siswa SET saldo = saldo + ? WHERE id_siswa = ?")
                    ->execute([$trx['jumlah'], $trx['id_siswa']]);
            }
            $pdo->commit();
            $_SESSION['message'] = count($to_verify) . " transaksi berhasil diverifikasi.";
        }
        header("Location: setoran.php"); exit();
    }

    // 3. Batalkan ke Pending
    if ($action === 'kembali_pending' && isset($_GET['id'])) {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT id_siswa, jumlah, status FROM transaksi WHERE id_transaksi = ? AND status = 'valid'");
        $stmt->execute([$_GET['id']]);
        $trx = $stmt->fetch();

        if ($trx) {
            $pdo->prepare("UPDATE siswa SET saldo = saldo - ? WHERE id_siswa = ?")->execute([$trx['jumlah'], $trx['id_siswa']]);
            $pdo->prepare("UPDATE transaksi SET status = 'pending', tanggal_verifikasi = NULL WHERE id_transaksi = ?")->execute([$_GET['id']]);
            $pdo->commit();
            $_SESSION['message'] = "Status kembali ke PENDING. Saldo dikurangi.";
        }
        header("Location: setoran.php"); exit();
    }

    // 4. Update & 5. Hapus
    if ($action === 'update_setoran') {
        $stmt = $pdo->prepare("UPDATE transaksi SET id_siswa = ?, jumlah = ?, tanggal_transaksi = ?, keterangan = ? WHERE id_transaksi = ? AND status = 'pending'");
        $stmt->execute([$_POST['id_siswa'], $_POST['jumlah'], $_POST['tanggal_transaksi'], $_POST['keterangan'], $_POST['id_transaksi']]);
        $_SESSION['message'] = "Data setoran diperbarui.";
        header("Location: setoran.php"); exit();
    }

    if ($action === 'hapus_setoran' && isset($_POST['id'])) {
        $pdo->prepare("DELETE FROM transaksi WHERE id_transaksi = ? AND status = 'pending'")->execute([$_POST['id']]);
        $_SESSION['message'] = "Transaksi berhasil dihapus.";
        header("Location: setoran.php"); exit();
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $_SESSION['error'] = "Kesalahan: " . $e->getMessage();
}

// === DATA FETCHING ===
$filter = $_GET['filter'] ?? 'semua';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$where = "WHERE t.jenis_transaksi = 'setoran'";
$params = [];
if ($filter === 'hari_ini') $where .= " AND DATE(t.tanggal_verifikasi) = CURDATE()";
if ($filter === 'minggu_ini') $where .= " AND t.tanggal_verifikasi >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
if ($search) { $where .= " AND (s.nama_siswa LIKE ? OR s.nis LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }

$total_rows = $pdo->prepare("SELECT COUNT(*) FROM transaksi t JOIN siswa s ON t.id_siswa = s.id_siswa $where");
$total_rows->execute($params);
$total_pages = ceil($total_rows->fetchColumn() / $limit);

$riwayat = $pdo->prepare("SELECT t.*, s.nama_siswa, s.nis, k.nama_kelas FROM transaksi t JOIN siswa s ON t.id_siswa = s.id_siswa JOIN kelas k ON s.id_kelas = k.id_kelas $where ORDER BY t.tanggal_transaksi DESC LIMIT $limit OFFSET $offset");
$riwayat->execute($params);
$list_data = $riwayat->fetchAll();

$siswa_list = $pdo->query("SELECT s.id_siswa, s.nis, s.nama_siswa, k.nama_kelas FROM siswa s JOIN kelas k ON s.id_kelas = k.id_kelas ORDER BY s.nama_siswa ASC")->fetchAll();

include 'header.php';
?>

<div class="content-card shadow-sm p-4 bg-white rounded">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <div>
            <h5 class="mb-0 fw-bold text-primary">Data Setoran Tunai</h5>
            <small class="text-muted">Manajemen mutasi masuk nasabah</small>
        </div>
        <div class="d-flex gap-2">
            <form class="d-flex gap-1">
                <input type="text" name="search" class="form-control form-control-sm" placeholder="Cari..." value="<?= htmlspecialchars($search) ?>">
                <button class="btn btn-sm btn-outline-primary"><i class="bi bi-search"></i></button>
            </form>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalSetoran"><i class="bi bi-plus-circle me-1"></i> Tambah</button>
        </div>
    </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; ?>

    <form method="POST" id="formMassal">
        <input type="hidden" name="action" value="verifikasi_massal">
        <div id="btnMassal" class="mb-3" style="display:none;">
            <button type="submit" class="btn btn-success btn-sm"><i class="bi bi-check-all"></i> Verifikasi Massal (<span id="countSelected">0</span>)</button>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle border">
                <thead class="table-light small ">
                    <tr>
                        <th width="40"><input type="checkbox" id="selectAll" class="form-check-input"></th>
                        <th>Tanggal</th>
                        <th>Nama Nasabah</th>
                        <th>Jumlah</th>
                        <th>Status</th>
                        <th>Input</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php foreach ($list_data as $r): ?>
                    <tr>
                        <td><?php if($r['status'] == 'pending'): ?><input type="checkbox" name="trx_ids[]" value="<?= $r['id_transaksi'] ?>" class="form-check-input checkItem"><?php endif; ?></td>
                        <td><?= date('d/m/y H:i', strtotime($r['tanggal_transaksi'])) ?></td>
                        <td><strong><?= htmlspecialchars($r['nama_siswa']) ?></strong><br><span class="text-muted small"><?= $r['nis'] ?> | <?= $r['nama_kelas'] ?></span></td>
                        <td class="fw-bold text-success">Rp <?= number_format($r['jumlah'], 0, ',', '.') ?></td>
                        <td>
                            <span class="badge rounded-pill bg-<?= $r['status'] == 'valid' ? 'success' : 'warning text-dark' ?>"><?= strtoupper($r['status']) ?></span>
                            <?php if($r['status'] == 'valid' && $r['tanggal_verifikasi']): ?><div class="text-secondary mt-1" style="font-size: 0.7rem;"><?= date('d/m/y H:i', strtotime($r['tanggal_verifikasi'])) ?></div><?php endif; ?>
                        </td>
                        <td><small class="badge bg-light text-dark"><?= strtoupper($r['input_by']) ?></small></td>
                        <td class="text-center">
                            <div class="btn-group btn-group-sm">
                                <?php if($r['status'] == 'pending'): ?>
                                    <a href="?action=verifikasi&id=<?= $r['id_transaksi'] ?>" class="btn btn-outline-success"><i class="bi bi-shield-check"></i></a>
                                    <button type="button" class="btn btn-outline-warning btn-edit" data-bs-toggle="modal" data-bs-target="#modalSetoran" data-id="<?= $r['id_transaksi'] ?>" data-siswa="<?= $r['id_siswa'] ?>" data-jumlah="<?= (int)$r['jumlah'] ?>" data-tgl="<?= date('Y-m-d\TH:i', strtotime($r['tanggal_transaksi'])) ?>" data-ket="<?= $r['keterangan'] ?>"><i class="bi bi-pencil"></i></button>
                                    <button type="button" class="btn btn-outline-secondary btn-action-hapus" data-id="<?= $r['id_transaksi'] ?>"><i class="bi bi-trash"></i></button>
                                <?php else: ?>
                                    <a href="?action=kembali_pending&id=<?= $r['id_transaksi'] ?>" class="btn btn-outline-danger"><i class="bi bi-shield-x"></i></a>
                                    <button class="btn btn-outline-warning opacity-50" disabled><i class="bi bi-pencil"></i></button>
                                    <button class="btn btn-outline-secondary opacity-50" disabled><i class="bi bi-trash"></i></button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </form>

    <?php if($total_pages > 1): ?>
    <nav class="mt-4"><ul class="pagination pagination-sm justify-content-center"><?php for($i=1; $i<=$total_pages; $i++): ?><li class="page-item <?= ($page == $i) ? 'active' : '' ?>"><a class="page-link" href="?page=<?= $i ?>&search=<?= $search ?>"><?= $i ?></a></li><?php endfor; ?></ul></nav>
    <?php endif; ?>
</div>

<div class="modal fade" id="modalSetoran" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="titleForm">Input Setoran Baru</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" id="actionForm" value="simpan_setoran">
                <input type="hidden" name="id_transaksi" id="idTrx">
                
                <div class="mb-3">
                    <label class="form-label">Nama Siswa</label>
                    <select name="id_siswa" id="idSiswa" class="form-select select2-siswa" style="width: 100%;" required>
                        <option value="">Cari siswa...</option>
                        <?php foreach($siswa_list as $s): ?>
                            <option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?> (<?= $s['nama_kelas'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="mb-3"><label class="form-label">Besar Setoran (Rp)</label><input type="number" name="jumlah" id="jumlahTrx" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Tanggal Setoran</label><input type="datetime-local" name="tanggal_transaksi" id="tglTrx" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required></div>
                <div class="mb-3"><label class="form-label">Keterangan (Opsional)</label><input type="text" name="keterangan" id="ketTrx" class="form-control"></div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button><button type="submit" class="btn btn-primary">Simpan</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="action" value="hapus_setoran"><input type="hidden" name="id" id="hapusId"><i class="bi bi-trash text-danger display-4"></i><p class="mt-3">Hapus transaksi?</p><div class="d-flex justify-content-center gap-2 mt-4"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button type="submit" class="btn btn-danger">Hapus</button></div></div></form></div></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Inisialisasi Select2
    $('.select2-siswa').select2({
        theme: 'bootstrap-5',
        dropdownParent: $('#modalSetoran'),
        placeholder: 'Cari NIS atau Nama Siswa...',
        allowClear: true
    });

    // Reset modal saat dibuka untuk tambah data
    $('#modalSetoran').on('hidden.bs.modal', function () {
        $('#actionForm').val('simpan_setoran');
        $('#titleForm').text('Input Setoran Baru');
        $('#idTrx').val('');
        $('#idSiswa').val('').trigger('change');
        $('#jumlahTrx').val('');
        $('#ketTrx').val('');
    });

    // Handler tombol edit
    $('.btn-edit').on('click', function() {
        const d = this.dataset;
        $('#actionForm').val('update_setoran');
        $('#titleForm').text('Edit Data Setoran');
        $('#idTrx').val(d.id);
        $('#idSiswa').val(d.siswa).trigger('change');
        $('#jumlahTrx').val(d.jumlah);
        $('#tglTrx').val(d.tgl);
        $('#ketTrx').val(d.ket);
    });

    // Checkbox Massal
    $('#selectAll').on('change', function() {
        $('.checkItem').prop('checked', this.checked);
        updateMassalUI();
    });

    $('.checkItem').on('change', updateMassalUI);

    function updateMassalUI() {
        const checked = $('.checkItem:checked').length;
        $('#btnMassal').toggle(checked > 0);
        $('#countSelected').text(checked);
    }

    const delModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    $('.btn-action-hapus').on('click', function() {
        $('#hapusId').val(this.dataset.id);
        delModal.show();
    });
});
</script>

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