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

$page_title = 'Transaksi Pembayaran';
$page_icon = 'bi-cart-check-fill';

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

// === AJAX: AMBIL DATA SISWA & JENIS PEMBAYARAN ===
if (isset($_GET['get_info'])) {
    if (isset($_GET['id_siswa'])) {
        $stmt = $pdo->prepare("SELECT saldo FROM siswa WHERE id_siswa = ?");
        $stmt->execute([$_GET['id_siswa']]);
        echo json_encode(['saldo' => number_format($stmt->fetchColumn(), 0, ',', '.')]);
    } elseif (isset($_GET['id_pembayaran'])) {
        $stmt = $pdo->prepare("SELECT nilai_satuan FROM data_pembayaran WHERE id_pembayaran = ?");
        $stmt->execute([$_GET['id_pembayaran']]);
        $val = $stmt->fetchColumn();
        echo json_encode(['satuan' => (float)$val, 'formatted' => number_format($val, 0, ',', '.')]);
    }
    exit;
}

// === LOGIKA PROSES ===
try {
    // 1. Simpan & Update Pembayaran
    if ($action === 'simpan_bayar' || $action === 'update_bayar') {
        $id_siswa = $_POST['id_siswa'];
        $id_pembayaran = $_POST['id_pembayaran'];
        $jumlah = $_POST['jumlah'];
        $tanggal = $_POST['tanggal'];
        $role_input = $_SESSION['role'] ?? 'Admin';

        if ($action === 'update_bayar') {
            $stmt = $pdo->prepare("UPDATE transaksi_payment SET id_siswa=?, id_pembayaran=?, jumlah=?, tanggal_bayar=? WHERE id_payment=? AND status='pending'");
            $stmt->execute([$id_siswa, $id_pembayaran, $jumlah, $tanggal, $_POST['id_payment']]);
            $_SESSION['message'] = "Data pembayaran diperbarui.";
        } else {
            $pdo->prepare("INSERT INTO transaksi_payment (id_siswa, id_pembayaran, jumlah, tanggal_bayar, status, input_by) 
                           VALUES (?, ?, ?, ?, 'pending', ?)")
                ->execute([$id_siswa, $id_pembayaran, $jumlah, $tanggal, $role_input]);
            $_SESSION['message'] = "Pembayaran disimpan (PENDING).";
        }
        header("Location: pembayaran.php"); exit();
    }

    // 2. Verifikasi (Perisai Hijau)
    if ($action === 'verifikasi' && isset($_GET['id'])) {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT tp.*, s.saldo as saldo_siswa FROM transaksi_payment tp 
                               JOIN siswa s ON tp.id_siswa = s.id_siswa WHERE tp.id_payment = ? AND tp.status = 'pending'");
        $stmt->execute([$_GET['id']]);
        $trx = $stmt->fetch();

        if ($trx) {
            if ($trx['saldo_siswa'] < $trx['jumlah']) throw new Exception("Saldo nasabah tidak mencukupi!");
            
            // Potong Saldo Siswa & Tambah Saldo di Tabel Master Pembayaran
            $pdo->prepare("UPDATE siswa SET saldo = saldo - ? WHERE id_siswa = ?")->execute([$trx['jumlah'], $trx['id_siswa']]);
            $pdo->prepare("UPDATE data_pembayaran SET saldo = saldo + ? WHERE id_pembayaran = ?")->execute([$trx['jumlah'], $trx['id_pembayaran']]);
            
            // Set Valid dan isi Tanggal Verifikasi
            $pdo->prepare("UPDATE transaksi_payment SET status = 'valid', tanggal_verifikasi = NOW() WHERE id_payment = ?")->execute([$_GET['id']]);
            
            $pdo->commit();
            $_SESSION['message'] = "Pembayaran Berhasil Diverifikasi.";
        }
        header("Location: pembayaran.php"); exit();
    }

    // 3. Batalkan ke Pending (Perisai Merah - Opsional)
    if ($action === 'kembali_pending' && isset($_GET['id'])) {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT * FROM transaksi_payment WHERE id_payment = ? AND status = 'valid'");
        $stmt->execute([$_GET['id']]);
        $trx = $stmt->fetch();

        if ($trx) {
            // Rollback saldo siswa dan saldo master pembayaran
            $pdo->prepare("UPDATE siswa SET saldo = saldo + ? WHERE id_siswa = ?")->execute([$trx['jumlah'], $trx['id_siswa']]);
            $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['message'] = "Pembayaran dibatalkan dan kembali ke PENDING.";
        }
        header("Location: pembayaran.php"); exit();
    }

    // 4. Hapus (Hanya Pending)
    if ($action === 'hapus_bayar' && isset($_POST['id'])) {
        $pdo->prepare("DELETE FROM transaksi_payment WHERE id_payment = ? AND status = 'pending'")->execute([$_POST['id']]);
        $_SESSION['message'] = "Data berhasil dihapus.";
        header("Location: pembayaran.php"); exit();
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $_SESSION['error'] = $e->getMessage();
    header("Location: pembayaran.php"); exit();
}

// Fetch Data
$riwayat = $pdo->query("SELECT tp.*, s.nama_siswa, s.nis, dp.nama_pembayaran 
                        FROM transaksi_payment tp 
                        JOIN siswa s ON tp.id_siswa = s.id_siswa 
                        JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran 
                        ORDER BY tp.tanggal_bayar DESC LIMIT 100")->fetchAll();

$siswa_list = $pdo->query("SELECT id_siswa, nis, nama_siswa FROM siswa ORDER BY nama_siswa ASC")->fetchAll();
$pembayaran_list = $pdo->query("SELECT * FROM data_pembayaran ORDER BY nama_pembayaran 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">
        <div><h5 class="mb-0 fw-bold text-primary">Transaksi Pembayaran</h5><small class="text-muted">Kelola iuran dan tagihan nasabah</small></div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalBayar" id="btnTambah"><i class="bi bi-cash-stack me-1"></i> Buat 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 small text-uppercase">
                <tr><th>Tanggal</th><th>Nasabah</th><th>Jenis</th><th>Jumlah</th><th>Status</th><th class="text-center">Aksi</th></tr>
            </thead>
            <tbody class="small">
                <?php foreach ($riwayat as $r): ?>
                <tr>
                    <td><?= date('d/m/y H:i', strtotime($r['tanggal_bayar'])) ?></td>
                    <td><strong><?= htmlspecialchars($r['nama_siswa']) ?></strong><br><small><?= $r['nis'] ?></small></td>
                    <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($r['nama_pembayaran']) ?></span></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=<?= $r['id_payment'] ?>" class="btn btn-outline-success" title="Verifikasi"><i class="bi bi-shield-check"></i></a>
                                <button class="btn btn-outline-warning btn-edit" 
                                        data-id="<?= $r['id_payment'] ?>" 
                                        data-siswa="<?= $r['id_siswa'] ?>" 
                                        data-pay="<?= $r['id_pembayaran'] ?>" 
                                        data-jumlah="<?= (int)$r['jumlah'] ?>" 
                                        data-tgl="<?= date('Y-m-d\TH:i', strtotime($r['tanggal_bayar'])) ?>" title="Edit"><i class="bi bi-pencil"></i></button>
                                <button class="btn btn-outline-secondary btn-delete" data-id="<?= $r['id_payment'] ?>" title="Hapus"><i class="bi bi-trash"></i></button>
                            <?php else: ?>
                                <a href="?action=kembali_pending&id=<?= $r['id_payment'] ?>" class="btn btn-outline-danger" title="Batalkan"><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>
</div>

<div class="modal fade" id="modalBayar" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="titleModal">Input Pembayaran</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_bayar">
                <input type="hidden" name="id_payment" id="idPayment">
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Nama Nasabah</label>
                    <select name="id_siswa" id="idSiswa" class="form-select select2-p" style="width:100%" required>
                        <option value="">-- Pilih --</option>
                        <?php foreach($siswa_list as $s): ?><option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSaldo" class="mt-1 small text-muted" style="display:none;">Saldo Siswa: <span class="fw-bold text-success" id="valSaldo">0</span></div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Jenis Pembayaran</label>
                    <select name="id_pembayaran" id="idPay" class="form-select select2-p" style="width:100%" required>
                        <option value="">-- Pilih Jenis --</option>
                        <?php foreach($pembayaran_list as $p): ?><option value="<?= $p['id_pembayaran'] ?>"><?= $p['nama_pembayaran'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSatuan" class="mt-1 small text-muted" style="display:none;">Nilai Satuan: <span class="fw-bold" id="valSatuan">0</span></div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Jumlah (Rp)</label>
                    <input type="number" name="jumlah" id="jumlahBayar" class="form-control form-control-lg fw-bold" required>
                    <small id="manualHint" class="text-info" style="display:none;">* Nilai satuan 0, silakan isi manual.</small>
                </div>

                <div class="mb-3"><label class="form-label">Tanggal</label><input type="datetime-local" name="tanggal" id="tglBayar" 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 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="action" value="hapus_bayar"><input type="hidden" name="id" id="hapusId"><i class="bi bi-trash text-danger display-4"></i><p class="mt-3">Hapus data 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">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-p').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalBayar'), allowClear: true });

    function updateSaldo(id) {
        if(id) $.get('pembayaran.php?get_info=1&id_siswa='+id, function(res) {
            $('#valSaldo').text('Rp '+JSON.parse(res).saldo);
            $('#infoSaldo').fadeIn();
        });
    }

    function updateSatuan(id, manualSet = false) {
        if(id) $.get('pembayaran.php?get_info=1&id_pembayaran='+id, function(res) {
            const data = JSON.parse(res);
            $('#valSatuan').text('Rp '+data.formatted);
            $('#infoSatuan').fadeIn();
            if(!manualSet) {
                if(data.satuan > 0) { 
                    $('#jumlahBayar').val(data.satuan).attr('readonly', true); 
                    $('#manualHint').hide();
                } else { 
                    $('#jumlahBayar').val('').attr('readonly', false); 
                    $('#manualHint').show();
                }
            }
        });
    }

    $('#idSiswa').on('change', function() { updateSaldo($(this).val()); });
    $('#idPay').on('change', function() { updateSatuan($(this).val()); });

    // Tombol Edit
    $('.btn-edit').on('click', function() {
        const d = this.dataset;
        $('#titleModal').text('Edit Pembayaran');
        $('#actionForm').val('update_bayar');
        $('#idPayment').val(d.id);
        $('#idSiswa').val(d.siswa).trigger('change');
        $('#idPay').val(d.pay).trigger('change');
        $('#jumlahBayar').val(d.jumlah);
        $('#tglBayar').val(d.tgl);
        
        // Jika sedang edit, biarkan jumlah bisa diedit jika nilainya berubah manual
        const currentModal = new bootstrap.Modal(document.getElementById('modalBayar'));
        currentModal.show();
    });

    $('#btnTambah').on('click', function() {
        $('#titleModal').text('Input Pembayaran Baru');
        $('#actionForm').val('simpan_bayar');
        $('#idPayment').val('');
        $('#idSiswa, #idPay').val('').trigger('change');
        $('#jumlahBayar').val('').attr('readonly', false);
        $('#infoSaldo, #infoSatuan').hide();
    });

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

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