<?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();
}

$id_siswa = $_SESSION['id_siswa'];
$siswa = [];

try {
    // 1. Ambil data nasabah dan kelas
    $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) {
        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)
    $query_web = "
        SELECT 
            t.tanggal_transaksi as tgl, 
            t.jenis_transaksi as ket, 
            t.jumlah, 
            t.status,
            t.keterangan,
            NULL as id_pembayaran,
            NULL as no_rekening,
            NULL as nama_pembayaran_ext
        FROM transaksi t 
        WHERE t.id_siswa = ?
        
        UNION ALL
        
        SELECT 
            tp.tanggal_bayar as tgl, 
            'pembayaran' as ket, 
            tp.jumlah, 
            tp.status,
            dp.nama_pembayaran as keterangan,
            tp.id_pembayaran,
            dp.no_rekening,
            dp.nama_pembayaran as nama_pembayaran_ext
        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_all = $stmt_web->fetchAll();

    // Proses rekap web untuk menambahkan detail transfer
    $rekap_web = [];
    foreach($rekap_web_all as $tr) {
        $keterangan = $tr['keterangan'] ?? '';
        $no_rekening = $tr['no_rekening'] ?? '';
        
        // Jika transfer, parse keterangan untuk mendapatkan detail
        if (in_array($tr['ket'], ['transfer_masuk', 'transfer_keluar'])) {
            // Cari ID target dari berbagai pola keterangan
            $target_id = null;
            
            // Pattern 1: "Transfer ke ID: 123"
            if (preg_match('/ID:\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 2: "Transfer dari ID: 123"
            elseif (preg_match('/dari ID:\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 3: "Transfer to/from ID 123"
            elseif (preg_match('/ID\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 4: Cari angka dalam string
            elseif (preg_match('/(\d+)/', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            
            if ($target_id && is_numeric($target_id)) {
                // Ambil nama siswa berdasarkan ID
                $stmt_nama = $pdo->prepare("SELECT nama_siswa, nis FROM siswa WHERE id_siswa = ?");
                $stmt_nama->execute([$target_id]);
                $target_siswa = $stmt_nama->fetch();
                
                if ($target_siswa) {
                    if ($tr['ket'] == 'transfer_keluar') {
                        $keterangan = "Transfer ke " . $target_siswa['nama_siswa'] . " (" . $target_siswa['nis'] . ")";
                    } else {
                        $keterangan = "Terima dari " . $target_siswa['nama_siswa'] . " (" . $target_siswa['nis'] . ")";
                    }
                } else {
                    // Jika tidak ditemukan, tetap tampilkan keterangan asli
                    $keterangan = str_replace('_', ' ', $tr['ket']) . " (ID: $target_id)";
                }
            }
        }
        // Jika pembayaran, tambahkan no rekening jika ada
        elseif ($tr['ket'] == 'pembayaran') {
            $nama_pembayaran = $tr['nama_pembayaran_ext'] ?? $keterangan;
            if (!empty($no_rekening)) {
                $keterangan = $nama_pembayaran . " (" . $no_rekening . ")";
            } else {
                $keterangan = $nama_pembayaran;
            }
        } else {
            // Untuk transaksi lainnya, pastikan keterangan ada
            if (empty($keterangan)) {
                $keterangan = str_replace('_', ' ', $tr['ket']);
            }
        }
        
        $rekap_web[] = [
            'tgl' => $tr['tgl'],
            'ket' => $tr['ket'],
            'jumlah' => $tr['jumlah'],
            'status' => $tr['status'],
            'keterangan' => $keterangan
        ];
    }

    // 5. DATA REKAP UNTUK PRINT (Hanya Valid, Dengan Saldo Berjalan)
    $query_print = "
        SELECT 
            t.tanggal_transaksi as tgl, 
            t.jenis_transaksi as ket, 
            t.jumlah, 
            t.status,
            t.keterangan,
            NULL as id_pembayaran,
            NULL as no_rekening,
            NULL as nama_pembayaran_ext
        FROM transaksi t 
        WHERE t.id_siswa = ? AND t.status = 'valid'
        
        UNION ALL
        
        SELECT 
            tp.tanggal_bayar as tgl, 
            'pembayaran' as ket, 
            tp.jumlah, 
            tp.status,
            dp.nama_pembayaran as keterangan,
            tp.id_pembayaran,
            dp.no_rekening,
            dp.nama_pembayaran as nama_pembayaran_ext
        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_raw = $stmt_print->fetchAll();

    // Proses untuk print
    $all_valid = [];
    foreach($all_valid_raw as $tr) {
        $keterangan = $tr['keterangan'] ?? '';
        $no_rekening = $tr['no_rekening'] ?? '';
        
        // Jika transfer, parse keterangan untuk mendapatkan detail
        if (in_array($tr['ket'], ['transfer_masuk', 'transfer_keluar'])) {
            // Cari ID target dari berbagai pola keterangan
            $target_id = null;
            
            // Pattern 1: "Transfer ke ID: 123"
            if (preg_match('/ID:\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 2: "Transfer dari ID: 123"
            elseif (preg_match('/dari ID:\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 3: "Transfer to/from ID 123"
            elseif (preg_match('/ID\s*(\d+)/i', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            // Pattern 4: Cari angka dalam string
            elseif (preg_match('/(\d+)/', $keterangan, $matches)) {
                $target_id = $matches[1];
            }
            
            if ($target_id && is_numeric($target_id)) {
                // Ambil nama siswa berdasarkan ID
                $stmt_nama = $pdo->prepare("SELECT nama_siswa, nis FROM siswa WHERE id_siswa = ?");
                $stmt_nama->execute([$target_id]);
                $target_siswa = $stmt_nama->fetch();
                
                if ($target_siswa) {
                    if ($tr['ket'] == 'transfer_keluar') {
                        $keterangan = "Transfer ke " . $target_siswa['nama_siswa'] . " (" . $target_siswa['nis'] . ")";
                    } else {
                        $keterangan = "Terima dari " . $target_siswa['nama_siswa'] . " (" . $target_siswa['nis'] . ")";
                    }
                } else {
                    // Jika tidak ditemukan, tetap tampilkan keterangan asli
                    $keterangan = str_replace('_', ' ', $tr['ket']) . " (ID: $target_id)";
                }
            }
        }
        // Jika pembayaran, tambahkan no rekening jika ada
        elseif ($tr['ket'] == 'pembayaran') {
            $nama_pembayaran = $tr['nama_pembayaran_ext'] ?? $keterangan;
            if (!empty($no_rekening)) {
                $keterangan = $nama_pembayaran . " (" . $no_rekening . ")";
            } else {
                $keterangan = $nama_pembayaran;
            }
        } else {
            // Untuk transaksi lainnya, pastikan keterangan ada
            if (empty($keterangan)) {
                $keterangan = str_replace('_', ' ', $tr['ket']);
            }
        }
        
        $all_valid[] = [
            'tgl' => $tr['tgl'],
            'ket' => $tr['ket'],
            'jumlah' => $tr['jumlah'],
            'keterangan' => $keterangan
        ];
    }

    $rekap_print = [];
    $running_saldo = 0;
    foreach($all_valid as $tr) {
        $debet = 0; $kredit = 0;
        if (in_array($tr['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'], 
            'keterangan' => $tr['keterangan'],
            '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; }
            .keterangan-cell { max-width: 250px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        }
        @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; }
            .keterangan-cell { max-width: 150px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        }

        #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; }
            .keterangan-print { max-width: 200px; }
        }

        .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 konfirmasi styling */
        .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">
    <!-- Bagian atas dashboard tetap sama -->
    <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>
                        <tr><td>Saldo Akhir</td><td>: Rp <?= number_format($siswa['saldo'] ?? 0, 0, ',', '.') ?></td></tr>
                    </table>
                </div>

                <div class="table-responsive">
                    <!-- TABEL UNTUK TAMPILAN WEB -->
                    <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['ket'], ['setoran', 'transfer_masuk']);
                                    $keterangan_display = !empty($tr['keterangan']) ? $tr['keterangan'] : str_replace('_', ' ', $tr['ket']);
                                ?>
                                <tr class="align-middle">
                                    <td class="text-muted"><?= date('d/m H:i', strtotime($tr['tgl'])) ?></td>
                                    <td class="keterangan-cell" title="<?= htmlspecialchars($keterangan_display) ?>">
                                        <div class="fw-bold text-uppercase">
                                            <?php 
                                            // Tampilkan jenis transaksi singkat
                                            switch($tr['ket']) {
                                                case 'setoran': echo 'SETORAN'; break;
                                                case 'penarikan': echo 'PENARIKAN'; break;
                                                case 'transfer_keluar': echo 'TRANSFER KELUAR'; break;
                                                case 'transfer_masuk': echo 'TRANSFER MASUK'; break;
                                                case 'pembayaran': echo 'PEMBAYARAN'; break;
                                                default: echo strtoupper($tr['ket']);
                                            }
                                            ?>
                                        </div>
                                        <div class="small text-muted" style="font-size: 0.85em;">
                                            <?= htmlspecialchars(mb_strimwidth($keterangan_display, 0, 50, '...')) ?>
                                        </div>
                                    </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">
                                        <?php if($tr['status'] == 'valid'): ?>
                                            <span class="badge bg-success">Valid</span>
                                        <?php elseif($tr['status'] == 'pending'): ?>
                                            <span class="badge bg-warning text-dark">Pending</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary"><?= $tr['status'] ?></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <!-- TABEL UNTUK CETAK/PRINT -->
                    <table class="table table-rekap mb-0" id="table-print">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th class="keterangan-print">Keterangan</th>
                                <th class="text-end">Debet</th>
                                <th class="text-end">Kredit</th>
                                <th class="text-end">Saldo</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($rekap_print)): ?>
                                <tr>
                                    <td colspan="5" class="text-center py-4 text-muted">Belum ada transaksi.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach($rekap_print as $p): 
                                    $keterangan_display = !empty($p['keterangan']) ? $p['keterangan'] : str_replace('_', ' ', $p['ket']);
                                ?>
                                <tr>
                                    <td><?= date('d-m-Y', strtotime($p['tgl'])) ?></td>
                                    <td class="keterangan-print">
                                        <div class="text-uppercase">
                                            <?php 
                                            // Tampilkan jenis transaksi singkat
                                            switch($p['ket']) {
                                                case 'setoran': echo 'SETORAN'; break;
                                                case 'penarikan': echo 'PENARIKAN'; break;
                                                case 'transfer_keluar': echo 'TRANSFER KELUAR'; break;
                                                case 'transfer_masuk': echo 'TRANSFER MASUK'; break;
                                                case 'pembayaran': echo 'PEMBAYARAN'; break;
                                                default: echo strtoupper($p['ket']);
                                            }
                                            ?>
                                        </div>
                                        <div class="small" style="font-size: 0.9em;"><?= htmlspecialchars($keterangan_display) ?></div>
                                    </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; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4" class="text-end fw-bold">SALDO AKHIR</td>
                                <td class="text-end fw-bold border-top">Rp <?= number_format($siswa['saldo'] ?? 0, 0, ',', '.') ?></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Konfirmasi dan Modal lainnya tetap sama -->
<!-- ... kode modal tetap sama seperti sebelumnya ... -->

<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" />

<!-- JavaScript tetap sama seperti sebelumnya -->
<script>
$(document).ready(function() {
    // Inisialisasi Select2 untuk modal Transfer
    if ($.fn.select2) {
        $('.select2-nasabah').select2({
            theme: 'bootstrap-5',
            dropdownParent: $('#modalTransfer'),
            width: '100%'
        });
    }

    // Otomatisasi jumlah pembayaran saat jenis dipilih
    $('#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);
        }
    });

    // Variabel global untuk menyimpan form yang sedang diproses
    let currentForm = null;
    let currentModal = null;
    let formData = null;

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

    // Handle tombol Batal di modal konfirmasi
    $('#konfirmasiBatal').on('click', function() {
        $('#modalKonfirmasi').modal('hide');
        // Kembalikan ke modal transaksi
        setTimeout(() => {
            if (currentModal) {
                $('#' + currentModal).modal('show');
            }
        }, 300);
    });

    // Handle tombol Ya di modal konfirmasi
    $('#konfirmasiYa').on('click', function() {
        if (!currentForm || !formData) return;
        
        const btn = $(this);
        const originalText = btn.html();
        
        // Disable tombol dan ubah teks
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Memproses...');
        
        // Kirim data via AJAX
        $.ajax({
            url: 'proses_transaksi.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                btn.prop('disabled', false).html(originalText);
                
                if (response.success) {
                    // Tampilkan pesan sukses
                    $('#modalKonfirmasi').modal('hide');
                    showAlert('success', response.message);
                    
                    // Tutup modal transaksi dan reload halaman
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    // Tampilkan pesan error
                    showAlert('danger', response.message);
                    // Kembalikan ke modal transaksi
                    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);
            }
        });
    });

    // Fungsi validasi form
    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;
    }

    // Fungsi untuk menampilkan alert Bootstrap
    function showAlert(type, message) {
        // Hapus alert sebelumnya jika ada
        $('.alert-dismissible').remove();
        
        // Buat alert baru
        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);
        
        // Auto dismiss setelah beberapa detik
        setTimeout(() => {
            $('.alert-dismissible').alert('close');
        }, type === 'success' ? 3000 : 5000);
    }

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

    // Proses Ganti Password & PIN via AJAX
    $('#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);
            }
        });
    });

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

// Fungsi toggle saldo
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>