<?php
session_start();
require '../config/database.php';

// 1. Validasi Akses: Pastikan role adalah siswa dan id_siswa tersedia di session
if (!isset($_SESSION['user_logged_in']) || $_SESSION['role'] !== 'siswa' || !isset($_SESSION['id_siswa'])) {
    header("Location: ../login.php");
    exit();
}

// KUNCI PERBAIKAN: Menggunakan id_siswa dari session login yang baru
$id_siswa = $_SESSION['id_siswa'];
$siswa = [];

try {
    // 1. Ambil data nasabah dan kelas (menggunakan id_siswa asli)
    $stmt = $pdo->prepare("SELECT s.*, k.nama_kelas FROM siswa s JOIN kelas k ON s.id_kelas = k.id_kelas WHERE s.id_siswa = ?");
    $stmt->execute([$id_siswa]);
    $siswa = $stmt->fetch();

    if (!$siswa) {
        // Jika data siswa tidak ditemukan, paksa logout untuk keamanan
        session_destroy();
        header("Location: ../login.php?error=data_not_found");
        exit();
    }

    // 2. Hitung ringkasan setoran
    $stmt_count = $pdo->prepare("SELECT 
        SUM(CASE WHEN jenis_transaksi = 'setoran' AND status = 'valid' THEN jumlah ELSE 0 END) as setoran_valid,
        SUM(CASE WHEN jenis_transaksi = 'setoran' AND status = 'pending' THEN jumlah ELSE 0 END) as setoran_pending
        FROM transaksi WHERE id_siswa = ?");
    $stmt_count->execute([$id_siswa]);
    $ringkasan = $stmt_count->fetch();

    // 3. Data pendukung modal
    $siswa_list_all = $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();

    /** * 4. DATA REKAP UNTUK WEB (Semua Status, Tanpa Saldo)
     * UPDATE: Ditambahkan JOIN untuk keterangan detail transfer dan pembayaran
     */
    $query_web = "
        SELECT t.tanggal_transaksi as tgl, 
               CASE 
                   WHEN t.jenis_transaksi = 'transfer_keluar' THEN CONCAT('Kirim ke ', s2.nama_siswa)
                   WHEN t.jenis_transaksi = 'transfer_masuk' THEN CONCAT('Terima dari ', s2.nama_siswa)
                   ELSE COALESCE(t.keterangan, t.jenis_transaksi)
               END as ket, 
               t.jumlah, t.status, t.jenis_transaksi as original_ket
        FROM transaksi t
        LEFT JOIN siswa s2 ON t.id_siswa_terkait = s2.id_siswa
        WHERE t.id_siswa = ?
        
        UNION ALL
        
        SELECT tp.tanggal_bayar as tgl, 
               CONCAT('Pembayaran ', dp.nama_pembayaran) as ket, 
               tp.jumlah, tp.status, 'pembayaran' as original_ket
        FROM transaksi_payment tp
        JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran
        WHERE tp.id_siswa = ?
        
        ORDER BY tgl DESC LIMIT 20";

    $stmt_web = $pdo->prepare($query_web);
    $stmt_web->execute([$id_siswa, $id_siswa]);
    $rekap_web = $stmt_web->fetchAll();

    /**
     * 5. DATA REKAP UNTUK PRINT (Hanya Valid, Dengan Saldo Berjalan)
     * UPDATE: Ditambahkan JOIN untuk keterangan detail transfer dan pembayaran
     */
    $query_print = "
        SELECT t.tanggal_transaksi as tgl, 
               CASE 
                   WHEN t.jenis_transaksi = 'transfer_keluar' THEN CONCAT('Kirim ke ', s2.nama_siswa)
                   WHEN t.jenis_transaksi = 'transfer_masuk' THEN CONCAT('Terima dari ', s2.nama_siswa)
                   ELSE COALESCE(t.keterangan, t.jenis_transaksi)
               END as ket, 
               t.jumlah, t.status, t.jenis_transaksi as original_ket
        FROM transaksi t
        LEFT JOIN siswa s2 ON t.id_siswa_terkait = s2.id_siswa
        WHERE t.id_siswa = ? AND t.status = 'valid'
        
        UNION ALL
        
        SELECT tp.tanggal_bayar as tgl, 
               CONCAT('Pembayaran ', dp.nama_pembayaran) as ket, 
               tp.jumlah, tp.status, 'pembayaran' as original_ket
        FROM transaksi_payment tp
        JOIN data_pembayaran dp ON tp.id_pembayaran = dp.id_pembayaran
        WHERE tp.id_siswa = ? AND tp.status = 'valid'
        
        ORDER BY tgl ASC";

    $stmt_print = $pdo->prepare($query_print);
    $stmt_print->execute([$id_siswa, $id_siswa]);
    $all_valid = $stmt_print->fetchAll();

    $rekap_print = [];
    $running_saldo = 0;
    foreach($all_valid as $tr) {
        $debet = 0; $kredit = 0;
        // original_ket digunakan untuk menentukan alur saldo
        if (in_array($tr['original_ket'], ['penarikan', 'transfer_keluar', 'pembayaran'])) {
            $debet = $tr['jumlah'];
            $running_saldo -= $debet;
        } else {
            $kredit = $tr['jumlah'];
            $running_saldo += $kredit;
        }
        $rekap_print[] = [
            'tgl' => $tr['tgl'], 
            'ket' => $tr['ket'], 
            'debet' => $debet, 
            'kredit' => $kredit, 
            'saldo' => $running_saldo
        ];
    }
    $rekap_print = array_reverse($rekap_print);

} catch (PDOException $e) {
    die("Terjadi kesalahan database: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Madu Mandiri Saving - Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #f0f4f8; font-family: 'Segoe UI', sans-serif; }
        .main-container { width: 100%; margin: 0 auto; padding: 20px; }

        @media (min-width: 992px) {
            .main-container { max-width: 1000px; }
            .menu-grid { grid-template-columns: repeat(4, 1fr) !important; }
            .table-rekap { font-size: 14px !important; font-family: 'Arial', sans-serif !important; }
        }
        @media (max-width: 991px) {
            .main-container { max-width: 450px; }
            .menu-grid { grid-template-columns: 1fr 1fr !important; }
            .table-rekap { font-size: 11px !important; font-family: 'Verdana', sans-serif !important; letter-spacing: -0.3px; }
        }

        #table-print, #info-nasabah-print { display: none; }

        @media print {
            body * { visibility: hidden; }
            #printableArea, #printableArea * { visibility: visible; }
            #printableArea { position: absolute; left: 0; top: 0; width: 100%; padding: 0; }
            .no-print { display: none !important; }
            .collapse { display: block !important; }
            #table-web { display: none !important; }
            #table-print { display: table !important; width: 100%; font-size: 11pt !important; border-top: 2px solid #000; }
            #info-nasabah-print { display: block !important; margin-bottom: 20px; }
            .table-rekap th { border-bottom: 1px solid #000 !important; padding: 8px 4px; }
            .table-rekap td { border-bottom: 1px solid #eee; padding: 6px 4px; }
        }

        .card-profile { background: white; border-radius: 20px; padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .card-saldo { background: linear-gradient(135deg, #d4a017 0%, #1abc9c 100%); color: white; border-radius: 25px; padding: 30px; margin-top: 20px; box-shadow: 0 10px 20px rgba(26, 188, 156, 0.3); border: none; }
        .saldo-amount { font-size: 2.5rem; font-weight: bold; display: flex; align-items: center; justify-content: space-between; }
        .btn-eye { background: none; border: none; color: rgba(255, 255, 255, 0.9); font-size: 1.5rem; cursor: pointer; }
        .menu-grid { display: grid; gap: 20px; margin-top: 30px; }
        .menu-item { background: white; border-radius: 20px; padding: 25px; text-align: center; color: #333; box-shadow: 0 5px 15px rgba(0,0,0,0.04); cursor: pointer; }
        .card-rekap { background: white; border-radius: 15px; margin-top: 25px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); overflow: hidden; }
        
        .modal-confirm { border-radius: 20px; overflow: hidden; }
        .modal-confirm .modal-header { background: #f8f9fa; border-bottom: 1px solid #dee2e6; }
        .modal-confirm .modal-footer { border-top: 1px solid #dee2e6; }
    </style>
</head>
<body>

<div class="main-container">
    <div class="card-profile">
        <div class="d-flex align-items-center">
            <i class="bi bi-person-circle fs-2 me-3 text-primary"></i>
            <div><small class="text-muted d-block">Halo,</small><strong><?= htmlspecialchars($siswa['nama_siswa']) ?></strong></div>
        </div>
        <div class="d-flex align-items-center">
            <a href="../logout.php" class="btn border-danger text-danger btn-sm rounded-pill px-3 fw-bold no-print">Logout</a>
            <i class="bi bi-gear fs-4 ms-3 text-muted no-print" style="cursor:pointer;" data-bs-toggle="modal" data-bs-target="#modalKeamanan"></i>
        </div>
    </div>

    <div class="card-saldo no-print">
        <div class="saldo-title">Saldo Tabungan Anda <strong>Rp.</strong></div>
        <div class="saldo-amount">
            <span id="saldo-text">******.000</span>
            <button class="btn-eye" onclick="toggleSaldo()"><i class="bi bi-eye-slash" id="eye-icon"></i></button>
        </div>
        <div class="saldo-detail mt-2 small opacity-75 pt-2 border-top">
            <div>Setoran Valid : <strong>Rp <?= number_format($ringkasan['setoran_valid'] ?? 0, 0, ',', '.') ?></strong></div>
            <div>Setoran Pending : <strong>Rp <?= number_format($ringkasan['setoran_pending'] ?? 0, 0, ',', '.') ?></strong></div>
        </div>
    </div>

    <div class="menu-grid no-print">
        <div class="menu-item" data-bs-toggle="modal" data-bs-target="#modalSetoran"><i class="bi bi-cash-stack text-success fs-2"></i><br><small class="text-secondary fw-bold">SETORAN</small></div>
        <div class="menu-item" data-bs-toggle="modal" data-bs-target="#modalPenarikan"><i class="bi bi-wallet2 text-danger fs-2"></i><br><small class="text-secondary fw-bold">PENARIKAN</small></div>
        <div class="menu-item" data-bs-toggle="modal" data-bs-target="#modalTransfer"><i class="bi bi-arrow-left-right text-primary fs-2"></i><br><small class="text-secondary fw-bold">TRANSFER</small></div>
        <div class="menu-item" data-bs-toggle="modal" data-bs-target="#modalPayment"><i class="bi bi-credit-card-2-front text-warning fs-2"></i><br><small class="text-secondary fw-bold">PAYMENT</small></div>
    </div>

    <div class="card-rekap shadow-sm" id="printableArea">
        <div class="p-3 d-flex justify-content-between align-items-center border-bottom no-print">
            <div class="d-flex align-items-center" style="cursor:pointer; flex-grow: 1;" data-bs-toggle="collapse" data-bs-target="#collapseRekap">
                <i class="bi bi-journal-text text-primary fs-4 me-3"></i>
                <span class="fw-bold">Rekap Transaksi (Buku Tabungan)</span>
            </div>
            <button onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="bi bi-printer"></i></button>
        </div>
        
        <div class="collapse show" id="collapseRekap">
            <div class="p-3">
                <div id="info-nasabah-print">
                    <h5 class="fw-bold mb-3 text-center">LAPORAN BUKU TABUNGAN</h5>
                    <table style="width: 100%;" class="mb-3">
                        <tr><td style="width: 150px;">Nama Nasabah</td><td>: <?= htmlspecialchars($siswa['nama_siswa']) ?></td></tr>
                        <tr><td>Nomor Rekening (NIS)</td><td>: <?= htmlspecialchars($siswa['nis']) ?></td></tr>
                        <tr><td>Kelas</td><td>: <?= htmlspecialchars($siswa['nama_kelas']) ?></td></tr>
                    </table>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover table-rekap mb-0" id="table-web">
                        <thead class="table-light">
                            <tr><th>Waktu</th><th>Keterangan</th><th class="text-end">Jumlah</th><th class="text-center">Status</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($rekap_web)): ?>
                                <tr><td colspan="4" class="text-center py-4 text-muted">Belum ada transaksi.</td></tr>
                            <?php else: ?>
                                <?php foreach($rekap_web as $tr): 
                                    $is_kredit = in_array($tr['original_ket'], ['setoran', 'transfer_masuk']); 
                                ?>
                                <tr class="align-middle">
                                    <td class="text-muted"><?= date('d/m H:i', strtotime($tr['tgl'])) ?></td>
                                    <td class="text-uppercase fw-bold"><?= htmlspecialchars($tr['ket']) ?></td>
                                    <td class="text-end fw-bold <?= $is_kredit ? 'text-success' : 'text-danger' ?>"><?= ($is_kredit ? '+' : '-') . number_format($tr['jumlah'], 0, ',', '.') ?></td>
                                    <td class="text-center"><span class="badge" style="background-color: <?= $tr['status'] == 'valid' ? '#2ecc71' : '#f1c40f' ?>;"><?= $tr['status'] ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <table class="table table-rekap mb-0" id="table-print">
                        <thead>
                            <tr><th>Tanggal</th><th>Keterangan</th><th class="text-end">Debet</th><th class="text-end">Kredit</th><th class="text-end">Saldo</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach($rekap_print as $p): ?>
                            <tr>
                                <td><?= date('d-m-Y', strtotime($p['tgl'])) ?></td>
                                <td class="text-uppercase"><?= htmlspecialchars($p['ket']) ?></td>
                                <td class="text-end"><?= $p['debet'] > 0 ? number_format($p['debet'], 0, ',', '.') : '-' ?></td>
                                <td class="text-end"><?= $p['kredit'] > 0 ? number_format($p['kredit'], 0, ',', '.') : '-' ?></td>
                                <td class="text-end fw-bold"><?= number_format($p['saldo'], 0, ',', '.') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalKonfirmasi" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content modal-confirm">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-center w-100">Konfirmasi</h5>
            </div>
            <div class="modal-body text-center py-4">
                <i class="bi bi-question-circle fs-1 text-primary mb-3"></i>
                <p id="konfirmasiPesan" class="mb-0">Apakah Anda yakin ingin melakukan transaksi ini?</p>
            </div>
            <div class="modal-footer border-0 justify-content-center">
                <button type="button" class="btn btn-secondary rounded-pill px-4" id="konfirmasiBatal">Batal</button>
                <button type="button" class="btn btn-primary rounded-pill px-4" id="konfirmasiYa">Ya, Lanjutkan</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalKeamanan" tabindex="-1" aria-labelledby="modalKeamananLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius: 20px;">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold" id="modalKeamananLabel">Pengaturan Keamanan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-pills nav-fill mb-3 p-1 bg-light" style="border-radius: 12px;">
                    <li class="nav-item">
                        <button class="nav-link active rounded-pill" data-bs-toggle="pill" data-bs-target="#pills-password" type="button">Password</button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link rounded-pill" data-bs-toggle="pill" data-bs-target="#pills-pin" type="button">PIN Transaksi</button>
                    </li>
                </ul>

                <div class="tab-content mt-4">
                    <div class="tab-pane fade show active" id="pills-password">
                        <form id="formGantiPassword">
                            <input type="hidden" name="action" value="password">
                            <div class="mb-3">
                                <label class="small fw-bold">Password Lama</label>
                                <input type="password" name="pass_lama" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="small fw-bold">Password Baru</label>
                                <input type="password" name="pass_baru" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="small fw-bold">Konfirmasi Password Baru</label>
                                <input type="password" name="pass_konf" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold py-2 mt-2">Simpan Password</button>
                        </form>
                    </div>

                    <div class="tab-pane fade" id="pills-pin">
                        <form id="formGantiPIN">
                            <input type="hidden" name="action" value="pin">
                            <div class="mb-3">
                                <label class="small fw-bold">PIN Lama (6 Digit)</label>
                                <input type="password" name="pin_lama" class="form-control" maxlength="6" inputmode="numeric" required>
                            </div>
                            <div class="mb-3">
                                <label class="small fw-bold">PIN Baru (6 Digit)</label>
                                <input type="password" name="pin_baru" class="form-control" maxlength="6" inputmode="numeric" required>
                            </div>
                            <div class="mb-3">
                                <label class="small fw-bold">Konfirmasi PIN Baru</label>
                                <input type="password" name="pin_konf" class="form-control" maxlength="6" inputmode="numeric" required>
                            </div>
                            <button type="submit" class="btn btn-success w-100 rounded-pill fw-bold py-2 mt-2">Simpan PIN</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalSetoran" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form id="formSetoran" class="modal-content form-transaksi" style="border-radius: 20px;">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">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" value="simpan_setoran">
                <input type="hidden" name="id_siswa" value="<?= $id_siswa ?>">
                
                <div class="mb-3">
                    <label class="form-label small fw-bold">Besar Setoran (Rp)</label>
                    <input type="number" name="jumlah" class="form-control" placeholder="0" min="1000" step="1000" required>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">Keterangan</label>
                    <input type="text" name="keterangan" class="form-control" value="Setoran Tunai">
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">Tanggal</label>
                    <input type="datetime-local" name="tanggal_transaksi" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="submit" class="btn btn-primary w-100 rounded-pill py-2">Kirim Pengajuan Setoran</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalPenarikan" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form id="formPenarikan" class="modal-content form-transaksi" style="border-radius: 20px;">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-danger">Tarik Saldo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="action" value="simpan_penarikan">
                <input type="hidden" name="id_siswa" value="<?= $id_siswa ?>">
                
                <div class="alert alert-info small border-0">
                    Saldo Tersedia: <strong>Rp <?= number_format($siswa['saldo'] ?? 0, 0, ',', '.') ?></strong>
                </div>
                
                <div class="mb-3">
                    <label class="form-label small fw-bold">Jumlah Penarikan (Rp)</label>
                    <input type="number" name="jumlah" class="form-control text-danger fw-bold" min="1000" max="<?= $siswa['saldo'] ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">PIN Transaksi</label>
                    <input type="password" name="pin_verifikasi" class="form-control text-center" maxlength="6" placeholder="Masukkan 6 Digit PIN" required>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="submit" class="btn btn-danger w-100 rounded-pill py-2">Tarik Tunai</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalTransfer" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form id="formTransfer" class="modal-content form-transaksi" style="border-radius: 20px;">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-primary">Transfer Saldo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="action" value="simpan_transfer">
                <input type="hidden" name="id_pengirim" value="<?= $id_siswa ?>">
                
                <div class="mb-3">
                    <label class="form-label small fw-bold">Penerima (Cari NIS/Nama)</label>
                    <select name="id_penerima" class="form-select select2-nasabah" style="width: 100%;" required>
                        <option value="">-- Pilih Penerima --</option>
                        <?php foreach($siswa_list_all as $s): ?>
                            <?php if($s['id_siswa'] != $id_siswa): ?>
                                <option value="<?= $s['id_siswa'] ?>"><?= $s['nis'] ?> - <?= $s['nama_siswa'] ?></option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">Jumlah Transfer (Rp)</label>
                    <input type="number" name="jumlah" class="form-control fw-bold" min="1000" required>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">PIN Transaksi</label>
                    <input type="password" name="pin_verifikasi" class="form-control text-center" maxlength="6" required>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="submit" class="btn btn-primary w-100 rounded-pill py-2">Kirim Sekarang</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalPayment" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form id="formPayment" class="modal-content form-transaksi" style="border-radius: 20px;">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold text-warning">Bayar Tagihan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="action" value="simpan_bayar">
                <input type="hidden" name="id_siswa" value="<?= $id_siswa ?>">
                
                <div class="mb-3">
                    <label class="form-label small fw-bold">Jenis Pembayaran</label>
                    <select name="id_pembayaran" id="nasabahIdPay" class="form-select" required>
                        <option value="">-- Pilih Jenis --</option>
                        <?php foreach($pembayaran_list as $p): ?>
                            <option value="<?= $p['id_pembayaran'] ?>" data-satuan="<?= $p['nilai_satuan'] ?>">
                                <?= $p['nama_pembayaran'] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-bold">Jumlah (Rp)</label>
                    <input type="number" name="jumlah" id="nasabahJumlahBayar" class="form-control fw-bold" min="1000" required>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="submit" class="btn btn-warning w-100 rounded-pill py-2 fw-bold">Bayar Sekarang</button>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />

<script>
$(document).ready(function() {
    if ($.fn.select2) {
        $('.select2-nasabah').select2({
            theme: 'bootstrap-5',
            dropdownParent: $('#modalTransfer'),
            width: '100%'
        });
    }

    $('#nasabahIdPay').on('change', function() {
        const selected = $(this).find('option:selected');
        const satuan = parseFloat(selected.data('satuan'));
        if (satuan > 0) {
            $('#nasabahJumlahBayar').val(satuan).attr('readonly', true);
        } else {
            $('#nasabahJumlahBayar').val('').attr('readonly', false);
        }
    });

    let currentForm = null;
    let currentModal = null;
    let formData = null;

    $('.form-transaksi').on('submit', function(e) {
        e.preventDefault();
        currentForm = $(this);
        currentModal = currentForm.closest('.modal').attr('id');
        formData = currentForm.serialize();
        if (!validateForm(currentForm)) return;
        
        const modalTitle = currentForm.find('.modal-title').text();
        const jumlah = currentForm.find('input[name="jumlah"]').val();
        $('#' + currentModal).modal('hide');
        
        setTimeout(() => {
            $('#konfirmasiPesan').html(`Apakah Anda yakin ingin melakukan <strong>${modalTitle}</strong> sebesar <strong>Rp ${formatRupiah(jumlah)}</strong>?`);
            $('#modalKonfirmasi').modal('show');
        }, 300);
    });

    $('#konfirmasiBatal').on('click', function() {
        $('#modalKonfirmasi').modal('hide');
        setTimeout(() => {
            if (currentModal) $('#' + currentModal).modal('show');
        }, 300);
    });

    $('#konfirmasiYa').on('click', function() {
        if (!currentForm || !formData) return;
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Memproses...');
        
        $.ajax({
            url: 'proses_transaksi.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                btn.prop('disabled', false).html(originalText);
                if (response.success) {
                    $('#modalKonfirmasi').modal('hide');
                    showAlert('success', response.message);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showAlert('danger', response.message);
                    setTimeout(() => {
                        if (currentModal) $('#' + currentModal).modal('show');
                    }, 300);
                }
            },
            error: function(xhr, status, error) {
                btn.prop('disabled', false).html(originalText);
                showAlert('danger', 'Terjadi kesalahan pada server: ' + error);
                $('#modalKonfirmasi').modal('hide');
                setTimeout(() => {
                    if (currentModal) $('#' + currentModal).modal('show');
                }, 300);
            }
        });
    });

    function validateForm(form) {
        const jumlahInput = form.find('input[name="jumlah"]');
        const jumlah = parseFloat(jumlahInput.val());
        if (isNaN(jumlah) || jumlah <= 0) {
            showAlert('warning', 'Jumlah harus lebih dari 0');
            jumlahInput.focus();
            return false;
        }
        if (jumlah < 1000) {
            showAlert('warning', 'Jumlah minimal Rp 1.000');
            jumlahInput.focus();
            return false;
        }
        return true;
    }

    function showAlert(type, message) {
        $('.alert-dismissible').remove();
        const alertClass = type === 'success' ? 'alert-success' : type === 'warning' ? 'alert-warning' : 'alert-danger';
        const icon = type === 'success' ? 'bi-check-circle' : type === 'warning' ? 'bi-exclamation-triangle' : 'bi-x-circle';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3" role="alert" style="z-index: 9999; min-width: 300px;">
                <i class="bi ${icon} me-2"></i>
                <strong>${type === 'success' ? 'Berhasil!' : type === 'warning' ? 'Peringatan!' : 'Gagal!'}</strong> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
        $('body').append(alertHtml);
        setTimeout(() => $('.alert-dismissible').alert('close'), type === 'success' ? 3000 : 5000);
    }

    function formatRupiah(angka) {
        if (!angka) return '0';
        const number = parseInt(angka);
        return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

    $('#formGantiPassword, #formGantiPIN').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const btn = form.find('button');
        const originalText = btn.text();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Memproses...');
        $.ajax({
            url: 'proses_keamanan.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showAlert('success', response.message);
                    form[0].reset();
                    $('#modalKeamanan').modal('hide');
                } else {
                    showAlert('danger', response.message);
                }
            },
            error: function() {
                showAlert('danger', 'Terjadi kesalahan pada server.');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('.modal').on('hidden.bs.modal', function () {
        const form = $(this).find('form');
        if (form.length > 0) {
            form[0].reset();
            if (form.find('.select2-nasabah').length > 0) {
                form.find('.select2-nasabah').val(null).trigger('change');
            }
        }
    });
});

let saldoVisible = false;
const realSaldo = "<?= number_format($siswa['saldo'] ?? 0, 0, ',', '.') ?>";
function toggleSaldo() {
    const text = document.getElementById('saldo-text');
    const icon = document.getElementById('eye-icon');
    saldoVisible = !saldoVisible;
    text.innerText = saldoVisible ? realSaldo : "******.000";
    icon.classList.replace(saldoVisible ? 'bi-eye-slash' : 'bi-eye', saldoVisible ? 'bi-eye' : 'bi-eye-slash');
}
</script>

</body>
</html>