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

$page_title = 'Manajemen Penarikan';
$page_icon = 'bi-arrow-up-circle-fill';

$active_tab = $_GET['tab'] ?? 'nasabah';
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// === FITUR AJAX UNTUK CEK SALDO ===
if (isset($_GET['get_saldo'])) {
    $id = $_GET['id'];
    if ($_GET['type'] == 'nasabah') {
        $stmt = $pdo->prepare("SELECT saldo FROM siswa WHERE id_siswa = ?");
    } else {
        $stmt = $pdo->prepare("SELECT saldo FROM data_pembayaran WHERE id_pembayaran = ?");
    }
    $stmt->execute([$id]);
    echo number_format($stmt->fetchColumn(), 0, ',', '.');
    exit;
}

// === LOGIKA PROSES TRANSAKSI ===
try {
    // 1. Simpan & Update Penarikan Nasabah
    if ($action === 'simpan_penarikan' || $action === 'update_penarikan') {
        if ($action === 'update_penarikan') {
            $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['msg'] = "Data penarikan nasabah diperbarui.";
        } else {
            $pdo->prepare("INSERT INTO transaksi (id_siswa, jenis_transaksi, jumlah, keterangan, tanggal_transaksi, status, input_by) 
                           VALUES (?, 'penarikan', ?, ?, ?, 'pending', ?)")
                ->execute([$_POST['id_siswa'], $_POST['jumlah'], $_POST['keterangan'], $_POST['tanggal_transaksi'], $_SESSION['role']]);
            $_SESSION['msg'] = "Penarikan nasabah disimpan (PENDING).";
        }
        header("Location: penarikan.php?tab=nasabah"); exit();
    }

    // 2. Simpan & Update Penarikan Kantong (transaksi_payment)
    if ($action === 'simpan_penarikan_pay' || $action === 'update_penarikan_pay') {
        if ($action === 'update_penarikan_pay') {
            $stmt = $pdo->prepare("UPDATE transaksi_payment SET id_pembayaran = ?, jumlah = ?, tanggal_bayar = ?, keterangan = ? WHERE id_payment = ? AND status = 'pending'");
            $stmt->execute([$_POST['id_pembayaran'], $_POST['jumlah'], $_POST['tanggal'], $_POST['keterangan'], $_POST['id_payment']]);
            $_SESSION['msg'] = "Data penarikan kantong diperbarui.";
        } else {
            $pdo->prepare("INSERT INTO transaksi_payment (id_siswa, id_pembayaran, jumlah, tanggal_bayar, status, input_by, keterangan) 
                           VALUES (0, ?, ?, ?, 'pending', ?, ?)")
                ->execute([$_POST['id_pembayaran'], $_POST['jumlah'], $_POST['tanggal'], $_SESSION['role'], $_POST['keterangan']]);
            $_SESSION['msg'] = "Penarikan kantong disimpan (PENDING).";
        }
        header("Location: penarikan.php?tab=pembayaran"); exit();
    }

    // 3. Verifikasi (Perisai Hijau)
    if (isset($_GET['action']) && $_GET['action'] === 'verifikasi') {
        $pdo->beginTransaction();
        if ($active_tab == 'nasabah') {
            $stmt = $pdo->prepare("SELECT t.*, s.saldo FROM transaksi t JOIN siswa s ON t.id_siswa = s.id_siswa WHERE t.id_transaksi = ? AND t.status = 'pending'");
            $stmt->execute([$_GET['id']]);
            $trx = $stmt->fetch();
            if ($trx && $trx['saldo'] >= $trx['jumlah']) {
                $pdo->prepare("UPDATE transaksi SET status = 'valid', tanggal_verifikasi = NOW() WHERE id_transaksi = ?")->execute([$_GET['id']]);
                $pdo->prepare("UPDATE siswa SET saldo = saldo - ? WHERE id_siswa = ?")->execute([$trx['jumlah'], $trx['id_siswa']]);
                $_SESSION['msg'] = "Penarikan Nasabah Berhasil.";
            } else { throw new Exception("Saldo nasabah tidak mencukupi!"); }
        } else {
            $stmt = $pdo->prepare("SELECT tp.*, dp.saldo FROM transaksi_payment tp JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran WHERE tp.id_payment = ? AND tp.status = 'pending'");
            $stmt->execute([$_GET['id']]);
            $trx = $stmt->fetch();
            if ($trx && $trx['saldo'] >= $trx['jumlah']) {
                $pdo->prepare("UPDATE transaksi_payment SET status = 'valid', tanggal_verifikasi = NOW() WHERE id_payment = ?")->execute([$_GET['id']]);
                $pdo->prepare("UPDATE data_pembayaran SET saldo = saldo - ? WHERE id_pembayaran = ?")->execute([$trx['jumlah'], $trx['id_pembayaran']]);
                $_SESSION['msg'] = "Penarikan Kantong Berhasil.";
            } else { throw new Exception("Saldo kantong tidak mencukupi!"); }
        }
        $pdo->commit();
        header("Location: penarikan.php?tab=".$active_tab); exit();
    }

    // 4. Rollback (Perisai Merah)
    if (isset($_GET['action']) && $_GET['action'] === 'kembali_pending') {
        $pdo->beginTransaction();
        if ($active_tab == 'nasabah') {
            $stmt = $pdo->prepare("SELECT * 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']]);
            }
        } else {
            $stmt = $pdo->prepare("SELECT * FROM transaksi_payment WHERE id_payment = ? AND status = 'valid'");
            $stmt->execute([$_GET['id']]);
            $trx = $stmt->fetch();
            if ($trx) {
                $pdo->prepare("UPDATE data_pembayaran SET saldo = saldo + ? WHERE id_pembayaran = ?")->execute([$trx['jumlah'], $trx['id_pembayaran']]);
                $pdo->prepare("UPDATE transaksi_payment SET status = 'pending', tanggal_verifikasi = NULL WHERE id_payment = ?")->execute([$_GET['id']]);
            }
        }
        $pdo->commit();
        $_SESSION['msg'] = "Status kembali ke PENDING.";
        header("Location: penarikan.php?tab=".$active_tab); exit();
    }

    // 5. Hapus (Hanya Pending)
    if ($action === 'hapus_trx' && isset($_POST['id'])) {
        if ($_POST['type'] == 'nasabah') {
            $pdo->prepare("DELETE FROM transaksi WHERE id_transaksi = ? AND status = 'pending'")->execute([$_POST['id']]);
        } else {
            $pdo->prepare("DELETE FROM transaksi_payment WHERE id_payment = ? AND status = 'pending'")->execute([$_POST['id']]);
        }
        $_SESSION['msg'] = "Data transaksi dihapus.";
        header("Location: penarikan.php?tab=".$_POST['type']); exit();
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $_SESSION['error'] = $e->getMessage();
    header("Location: penarikan.php?tab=".$active_tab); exit();
}

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

include 'header.php';
?>

<div class="container-fluid mt-4">
    <?php if(isset($_SESSION['msg'])): ?>
        <div class="alert alert-success alert-dismissible fade show"><?= $_SESSION['msg']; unset($_SESSION['msg']); ?><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; ?>

    <nav>
        <div class="nav nav-tabs" id="nav-tab">
            <a class="nav-link <?= $active_tab == 'nasabah' ? 'active' : '' ?>" href="?tab=nasabah"><i class="bi bi-person-lines-fill"></i> Tabungan Nasabah</a>
            <a class="nav-link <?= $active_tab == 'pembayaran' ? 'active' : '' ?>" href="?tab=pembayaran"><i class="bi bi-wallet2"></i> Kantong Pembayaran</a>
        </div>
    </nav>

    <div class="tab-content content-card shadow-sm p-4 bg-white border border-top-0 rounded-bottom">
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0 fw-bold <?= $active_tab == 'nasabah' ? 'text-danger' : 'text-primary' ?>">
                Riwayat Penarikan <?= $active_tab == 'nasabah' ? 'Nasabah' : 'Kantong' ?>
            </h5>
            <?php if($active_tab == 'nasabah'): ?>
                <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#modalNasabah" id="btnTambahNasabah"><i class="bi bi-plus-circle me-1"></i> Tambah Penarikan</button>
            <?php else: ?>
                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalPay" id="btnTambahPay"><i class="bi bi-box-arrow-up me-1"></i> Tarik Kas Kantong</button>
            <?php endif; ?>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle border">
                <thead class="table-light small text-uppercase">
                    <tr>
                        <th>Tanggal</th>
                        <th><?= $active_tab == 'nasabah' ? 'Nama Nasabah' : 'Jenis Kas' ?></th>
                        <th>Jumlah</th>
                        <th>Status</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php 
                    if ($active_tab == 'nasabah') {
                        $riwayat = $pdo->query("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 t.jenis_transaksi = 'penarikan' ORDER BY t.tanggal_transaksi DESC LIMIT 50")->fetchAll();
                    } else {
                        $riwayat = $pdo->query("SELECT tp.*, dp.nama_pembayaran as nama_siswa, dp.no_rekening as nis FROM transaksi_payment tp JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran WHERE tp.id_siswa = 0 ORDER BY tp.tanggal_bayar DESC LIMIT 50")->fetchAll();
                    }

                    foreach ($riwayat as $r): 
                        $id_trx = ($active_tab == 'nasabah') ? $r['id_transaksi'] : $r['id_payment'];
                        $tgl = ($active_tab == 'nasabah') ? $r['tanggal_transaksi'] : $r['tanggal_bayar'];
                    ?>
                    <tr>
                        <td><?= date('d/m/y H:i', strtotime($tgl)) ?></td>
                        <td><strong><?= htmlspecialchars($r['nama_siswa']) ?></strong><br><small class="text-muted"><?= $r['nis'] ?></small></td>
                        <td class="fw-bold text-danger">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 class="text-center">
                            <div class="btn-group btn-group-sm">
                                <?php if($r['status'] == 'pending'): ?>
                                    <a href="?action=verifikasi&id=<?= $id_trx ?>&tab=<?= $active_tab ?>" class="btn btn-outline-success"><i class="bi bi-shield-check"></i></a>
                                    
                                    <?php if($active_tab == 'nasabah'): ?>
                                        <button class="btn btn-outline-warning btn-edit-nasabah" data-id="<?= $r['id_transaksi'] ?>" data-siswa="<?= $r['id_siswa'] ?>" data-jumlah="<?= (int)$r['jumlah'] ?>" data-ket="<?= $r['keterangan'] ?>" data-tgl="<?= date('Y-m-d\TH:i', strtotime($r['tanggal_transaksi'])) ?>"><i class="bi bi-pencil"></i></button>
                                    <?php else: ?>
                                        <button class="btn btn-outline-warning btn-edit-pay" data-id="<?= $r['id_payment'] ?>" data-pay="<?= $r['id_pembayaran'] ?>" data-jumlah="<?= (int)$r['jumlah'] ?>" data-ket="<?= $r['keterangan'] ?>" data-tgl="<?= date('Y-m-d\TH:i', strtotime($r['tanggal_bayar'])) ?>"><i class="bi bi-pencil"></i></button>
                                    <?php endif; ?>

                                    <button class="btn btn-outline-danger btn-del-trx" data-id="<?= $id_trx ?>" data-type="<?= $active_tab ?>"><i class="bi bi-trash"></i></button>
                                <?php else: ?>
                                    <a href="?action=kembali_pending&id=<?= $id_trx ?>&tab=<?= $active_tab ?>" class="btn btn-outline-danger"><i class="bi bi-shield-x"></i></a>
                                    <button class="btn btn-outline-secondary 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>
    </div>
</div>

<div class="modal fade" id="modalNasabah" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header bg-danger text-white"><h5 id="titleNasabah">Tarik Saldo Nasabah</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" id="actionNasabah" value="simpan_penarikan">
                <input type="hidden" name="id_transaksi" id="idTrxNasabah">
                <div class="mb-3">
                    <label class="form-label fw-bold text-primary">Pilih Nasabah</label>
                    <select name="id_siswa" id="selSiswa" class="form-select select2-siswa" style="width:100%" required>
                        <option value="">-- Cari --</option>
                        <?php foreach($siswa_list as $s): ?><option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSaldoSiswa" class="mt-2 p-2 rounded bg-light border" style="display:none;">Saldo: <span class="fw-bold text-success" id="valSaldoSiswa">0</span></div>
                </div>
                <div class="mb-3"><label class="form-label">Jumlah (Rp)</label><input type="number" name="jumlah" id="jumlahNasabah" class="form-control fw-bold text-danger" required></div>
                <div class="mb-3"><label class="form-label">Keterangan</label><input type="text" name="keterangan" id="ketNasabah" class="form-control" value="Penarikan Tunai"></div>
                <div class="mb-3"><label class="form-label">Tanggal</label><input type="datetime-local" name="tanggal_transaksi" id="tglNasabah" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required></div>
            </div>
            <div class="modal-footer"><button type="submit" class="btn btn-danger w-100">Simpan Transaksi</button></div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalPay" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header bg-primary text-white"><h5 id="titlePay">Tarik Kas Kantong</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" id="actionPay" value="simpan_penarikan_pay">
                <input type="hidden" name="id_payment" id="idTrxPay">
                <div class="mb-3">
                    <label class="form-label fw-bold text-primary">Pilih Kantong Kas</label>
                    <select name="id_pembayaran" id="selPay" class="form-select select2-siswa" style="width:100%" required>
                        <option value="">-- Pilih --</option>
                        <?php foreach($pay_list as $p): ?><option value="<?= $p['id_pembayaran'] ?>"><?= $p['nama_pembayaran'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSaldoPay" class="mt-2 p-2 rounded bg-light border" style="display:none;">Saldo Kantong: <span class="fw-bold text-primary" id="valSaldoPay">0</span></div>
                </div>
                <div class="mb-3"><label class="form-label">Jumlah Penarikan (Rp)</label><input type="number" name="jumlah" id="jumlahPay" class="form-control fw-bold" required></div>
                <div class="mb-3"><label class="form-label">Keterangan</label><input type="text" name="keterangan" id="ketPay" class="form-control" placeholder="Tujuan penarikan kas"></div>
                <div class="mb-3"><label class="form-label">Tanggal</label><input type="datetime-local" name="tanggal" id="tglPay" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required></div>
            </div>
            <div class="modal-footer"><button type="submit" class="btn btn-primary w-100">Simpan Transaksi</button></div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalDel" 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_trx"><input type="hidden" name="id" id="idDel"><input type="hidden" name="type" id="typeDel">
        <i class="bi bi-trash text-danger display-4"></i><p class="mt-3">Hapus transaksi pending ini?</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">Ya, 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() {
    // Select2 Initialization
    function initSelect2(selector, parent) {
        $(selector).select2({ theme: 'bootstrap-5', dropdownParent: $(parent), allowClear: true });
    }
    initSelect2('#selSiswa', '#modalNasabah');
    initSelect2('#selPay', '#modalPay');

    // AJAX Get Saldo
    function loadSaldo(id, type, target, wrapper) {
        if(id) {
            $.get(`penarikan.php?get_saldo=1&type=${type}&id=${id}`, function(d) {
                $(target).text('Rp ' + d);
                $(wrapper).fadeIn();
            });
        } else { $(wrapper).hide(); }
    }
    $('#selSiswa').on('change', function() { loadSaldo($(this).val(), 'nasabah', '#valSaldoSiswa', '#infoSaldoSiswa'); });
    $('#selPay').on('change', function() { loadSaldo($(this).val(), 'pay', '#valSaldoPay', '#infoSaldoPay'); });

    // Reset Modal on Hidden
    $('#modalNasabah').on('hidden.bs.modal', function(){
        $('#actionNasabah').val('simpan_penarikan'); $('#titleNasabah').text('Tarik Saldo Nasabah');
        $('#selSiswa').val('').trigger('change'); $('#jumlahNasabah, #idTrxNasabah').val('');
    });
    $('#modalPay').on('hidden.bs.modal', function(){
        $('#actionPay').val('simpan_penarikan_pay'); $('#titlePay').text('Tarik Kas Kantong');
        $('#selPay').val('').trigger('change'); $('#jumlahPay, #idTrxPay, #ketPay').val('');
    });

    // Edit Nasabah
    $('.btn-edit-nasabah').on('click', function() {
        const d = this.dataset;
        $('#actionNasabah').val('update_penarikan'); $('#titleNasabah').text('Edit Penarikan Nasabah');
        $('#idTrxNasabah').val(d.id); $('#selSiswa').val(d.siswa).trigger('change');
        $('#jumlahNasabah').val(d.jumlah); $('#ketNasabah').val(d.ket); $('#tglNasabah').val(d.tgl);
        new bootstrap.Modal($('#modalNasabah')).show();
    });

    // Edit Pay
    $('.btn-edit-pay').on('click', function() {
        const d = this.dataset;
        $('#actionPay').val('update_penarikan_pay'); $('#titlePay').text('Edit Penarikan Kantong');
        $('#idTrxPay').val(d.id); $('#selPay').val(d.pay).trigger('change');
        $('#jumlahPay').val(d.jumlah); $('#ketPay').val(d.ket); $('#tglPay').val(d.tgl);
        new bootstrap.Modal($('#modalPay')).show();
    });

    // Delete
    $('.btn-del-trx').on('click', function() {
        $('#idDel').val($(this).data('id'));
        $('#typeDel').val($(this).data('type'));
        new bootstrap.Modal($('#modalDel')).show();
    });
});
</script>

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