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

$page_title = 'Transfer Sesama Anggota';
$page_icon = 'bi-arrow-left-right';

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

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

// === LOGIKA PROSES TRANSAKSI ===
try {
    // 1. Simpan & Update Transfer
    if ($action === 'simpan_transfer' || $action === 'update_transfer') {
        $id_pengirim = $_POST['id_pengirim'];
        $id_penerima = $_POST['id_penerima'];
        $jumlah = $_POST['jumlah'];
        $tanggal = $_POST['tanggal_transaksi'];
        $role_input = $_SESSION['role'] ?? 'Admin';

        if ($id_pengirim == $id_penerima) {
            $_SESSION['error'] = "Gagal: Pengirim dan penerima tidak boleh sama.";
        } else {
            $pdo->beginTransaction();
            
            if ($action === 'update_transfer') {
                $group_id = $_POST['group_transfer'];
                // Hapus pasangan lama, lalu masukkan yang baru agar saldo tetap konsisten saat pending
                $pdo->prepare("DELETE FROM transaksi WHERE group_transfer = ? AND status = 'pending'")->execute([$group_id]);
            } else {
                $group_id = 'TRF' . time() . rand(10, 99);
            }

            // Sisi Pengirim
            $pdo->prepare("INSERT INTO transaksi (id_siswa, jenis_transaksi, jumlah, keterangan, tanggal_transaksi, status, input_by, id_siswa_terkait, group_transfer) 
                           VALUES (?, 'transfer_keluar', ?, 'Transfer ke...', ?, 'pending', ?, ?, ?)")
                ->execute([$id_pengirim, $jumlah, $tanggal, $role_input, $id_penerima, $group_id]);

            // Sisi Penerima
            $pdo->prepare("INSERT INTO transaksi (id_siswa, jenis_transaksi, jumlah, keterangan, tanggal_transaksi, status, input_by, id_siswa_terkait, group_transfer) 
                           VALUES (?, 'transfer_masuk', ?, 'Terima dari...', ?, 'pending', ?, ?, ?)")
                ->execute([$id_penerima, $jumlah, $tanggal, $role_input, $id_pengirim, $group_id]);
            
            $pdo->commit();
            $_SESSION['message'] = ($action === 'update_transfer') ? "Data transfer berhasil diperbarui." : "Transfer disimpan (PENDING).";
        }
        header("Location: transfer.php"); exit();
    }

    // 2. Verifikasi (Perisai Hijau)
    if ($action === 'verifikasi' && isset($_GET['group'])) {
        $group = $_GET['group'];
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("SELECT t.*, s.nama_siswa as nama_penerima, p.saldo as saldo_pengirim, p.nama_siswa as nama_pengirim 
                               FROM transaksi t 
                               JOIN siswa s ON t.id_siswa_terkait = s.id_siswa 
                               JOIN siswa p ON t.id_siswa = p.id_siswa
                               WHERE t.group_transfer = ? AND t.jenis_transaksi = 'transfer_keluar' AND t.status = 'pending'");
        $stmt->execute([$group]);
        $out = $stmt->fetch();

        if ($out) {
            if ($out['saldo_pengirim'] < $out['jumlah']) {
                throw new Exception("Saldo " . $out['nama_pengirim'] . " tidak mencukupi!");
            }
            $pdo->prepare("UPDATE transaksi SET status = 'valid', tanggal_verifikasi = NOW(), keterangan = CONCAT('Kirim ke ', ?) WHERE group_transfer = ? AND jenis_transaksi = 'transfer_keluar'")->execute([$out['nama_penerima'], $group]);
            $pdo->prepare("UPDATE transaksi SET status = 'valid', tanggal_verifikasi = NOW(), keterangan = CONCAT('Terima dari ', ?) WHERE group_transfer = ? AND jenis_transaksi = 'transfer_masuk'")->execute([$out['nama_pengirim'], $group]);
            $pdo->prepare("UPDATE siswa SET saldo = saldo - ? WHERE id_siswa = ?")->execute([$out['jumlah'], $out['id_siswa']]);
            $pdo->prepare("UPDATE siswa SET saldo = saldo + ? WHERE id_siswa = ?")->execute([$out['jumlah'], $out['id_siswa_terkait']]);
            $pdo->commit();
            $_SESSION['message'] = "Transfer Berhasil Diverifikasi.";
        }
        header("Location: transfer.php"); exit();
    }

    // 3. Rollback (Perisai Merah)
    if ($action === 'kembali_pending' && isset($_GET['group'])) {
        $group = $_GET['group'];
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT * FROM transaksi WHERE group_transfer = ? AND jenis_transaksi = 'transfer_keluar' AND status = 'valid'");
        $stmt->execute([$group]);
        $out = $stmt->fetch();
        if ($out) {
            $pdo->prepare("UPDATE siswa SET saldo = saldo + ? WHERE id_siswa = ?")->execute([$out['jumlah'], $out['id_siswa']]);
            $pdo->prepare("UPDATE siswa SET saldo = saldo - ? WHERE id_siswa = ?")->execute([$out['jumlah'], $out['id_siswa_terkait']]);
            $pdo->prepare("UPDATE transaksi SET status = 'pending', tanggal_verifikasi = NULL WHERE group_transfer = ?")->execute([$group]);
            $pdo->commit();
            $_SESSION['message'] = "Status kembali ke PENDING. Saldo dikembalikan.";
        }
        header("Location: transfer.php"); exit();
    }

    // 4. Hapus
    if ($action === 'hapus_transfer' && isset($_POST['group'])) {
        $pdo->prepare("DELETE FROM transaksi WHERE group_transfer = ? AND status = 'pending'")->execute([$_POST['group']]);
        $_SESSION['message'] = "Data transaksi dihapus.";
        header("Location: transfer.php"); exit();
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $_SESSION['error'] = "Kesalahan: " . $e->getMessage();
}

// === DATA FETCHING ===
$riwayat = $pdo->query("SELECT t.*, s.nama_siswa as pengirim, s.nis as nis_pengirim, p.nama_siswa as penerima, p.nis as nis_penerima 
                        FROM transaksi t 
                        JOIN siswa s ON t.id_siswa = s.id_siswa 
                        LEFT JOIN siswa p ON t.id_siswa_terkait = p.id_siswa 
                        WHERE t.jenis_transaksi = 'transfer_keluar' 
                        ORDER BY t.tanggal_transaksi DESC LIMIT 100")->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">
        <div><h5 class="mb-0 fw-bold text-primary">Transfer Antar Anggota</h5><small class="text-muted">Fasilitasi mutasi saldo antar nasabah</small></div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalTransfer"><i class="bi bi-send me-1"></i> Buat Transfer</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 ">
                <tr><th>Tanggal</th><th>Pengirim</th><th>Penerima</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_transaksi'])) ?></td>
                    <td><strong><?= htmlspecialchars($r['pengirim']) ?></strong><br><small><?= $r['nis_pengirim'] ?></small></td>
                    <td><strong><?= htmlspecialchars($r['penerima']) ?></strong><br><small><?= $r['nis_penerima'] ?></small></td>
                    <td class="fw-bold text-primary">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&group=<?= $r['group_transfer'] ?>" class="btn btn-outline-success"><i class="bi bi-shield-check"></i></a>
                                <button class="btn btn-outline-warning btn-edit" data-bs-toggle="modal" data-bs-target="#modalTransfer" 
                                        data-group="<?= $r['group_transfer'] ?>" data-pengirim="<?= $r['id_siswa'] ?>" 
                                        data-penerima="<?= $r['id_siswa_terkait'] ?>" data-jumlah="<?= (int)$r['jumlah'] ?>" 
                                        data-tgl="<?= date('Y-m-d\TH:i', strtotime($r['tanggal_transaksi'])) ?>"><i class="bi bi-pencil"></i></button>
                                <button class="btn btn-outline-secondary btn-action-hapus" data-group="<?= $r['group_transfer'] ?>"><i class="bi bi-trash"></i></button>
                            <?php else: ?>
                                <a href="?action=kembali_pending&group=<?= $r['group_transfer'] ?>" 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>
</div>

<div class="modal fade" id="modalTransfer" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="titleForm">Transfer Saldo</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_transfer">
                <input type="hidden" name="group_transfer" id="idGroup">
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Dari (Pengirim)</label>
                    <select name="id_pengirim" id="idPengirim" class="form-select select2-siswa" style="width: 100%;" required>
                        <option value="">-- Pilih Pengirim --</option>
                        <?php foreach($siswa_list as $s): ?><option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSaldoPengirim" class="mt-2 small p-2 rounded bg-light border" style="display:none;">Saldo: <span class="fw-bold text-danger" id="valSaldoPengirim">0</span></div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Ke (Penerima)</label>
                    <select name="id_penerima" id="idPenerima" class="form-select select2-siswa" style="width: 100%;" required>
                        <option value="">-- Pilih Penerima --</option>
                        <?php foreach($siswa_list as $s): ?><option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?></option><?php endforeach; ?>
                    </select>
                    <div id="infoSaldoPenerima" class="mt-2 small p-2 rounded bg-light border" style="display:none;">Saldo: <span class="fw-bold text-success" id="valSaldoPenerima">0</span></div>
                </div>

                <div class="mb-3"><label class="form-label fw-bold">Jumlah (Rp)</label><input type="number" name="jumlah" id="jumlahTrx" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Tanggal</label><input type="datetime-local" name="tanggal_transaksi" id="tglTrx" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required></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 Transfer</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_transfer"><input type="hidden" name="group" id="hapusGroup"><i class="bi bi-trash text-danger display-4"></i><p class="mt-3">Hapus transfer 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-siswa').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalTransfer'), placeholder: 'Pilih...', allowClear: true });

    function getSaldo(id, targetVal, targetWrap) {
        if (id) $.get('transfer.php?get_saldo=1&id_siswa=' + id, function(data) { $(targetVal).text('Rp ' + data); $(targetWrap).fadeIn(); });
        else $(targetWrap).hide();
    }

    $('#idPengirim').on('change', function() { getSaldo($(this).val(), '#valSaldoPengirim', '#infoSaldoPengirim'); });
    $('#idPenerima').on('change', function() { getSaldo($(this).val(), '#valSaldoPenerima', '#infoSaldoPenerima'); });

    $('#modalTransfer').on('hidden.bs.modal', function () {
        $('#actionForm').val('simpan_transfer'); $('#titleForm').text('Transfer Saldo'); $('#idGroup').val('');
        $('#idPengirim, #idPenerima').val('').trigger('change'); $('#jumlahTrx').val(''); $('#infoSaldoPengirim, #infoSaldoPenerima').hide();
    });

    $('.btn-edit').on('click', function() {
        const d = this.dataset;
        $('#actionForm').val('update_transfer'); $('#titleForm').text('Edit Data Transfer');
        $('#idGroup').val(d.group);
        $('#idPengirim').val(d.pengirim).trigger('change');
        $('#idPenerima').val(d.penerima).trigger('change');
        $('#jumlahTrx').val(d.jumlah); $('#tglTrx').val(d.tgl);
    });

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

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