<?php
session_start();
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_type'] != 'siswa') {
    header("Location: ../login.php");
    exit();
}

include '../config/koneksi.php';

$id_siswa = $_SESSION['id_user'];
$nama_siswa = $_SESSION['nama_user'];

// Ambil data saldo dari transaksi yang valid
try {
    // Hitung saldo akhir dari transaksi valid
    $stmt_saldo = $pdo->prepare("SELECT 
        SUM(CASE WHEN jenis_transaksi IN ('setoran', 'transfer_masuk') THEN jumlah ELSE 0 END) -
        SUM(CASE WHEN jenis_transaksi IN ('penarikan', 'transfer_keluar', 'pembayaran') THEN jumlah ELSE 0 END)
        AS saldo_akhir 
        FROM transaksi WHERE id_siswa = ? AND status = 'valid'");
    $stmt_saldo->execute([$id_siswa]);
    $total_saldo = $stmt_saldo->fetchColumn() ?? 0;

    // Ambil nama kelas
    $stmt_kelas = $pdo->prepare("SELECT nama_kelas FROM siswa s JOIN kelas k ON s.id_kelas = k.id_kelas WHERE id_siswa = ?");
    $stmt_kelas->execute([$id_siswa]);
    $siswa = $stmt_kelas->fetch();
    $nama_kelas = $siswa['nama_kelas'];

    // Hitung setoran valid
    $stmt_setoran = $pdo->prepare("SELECT SUM(jumlah) FROM transaksi WHERE id_siswa = ? AND jenis_transaksi = 'setoran' AND status = 'valid'");
    $stmt_setoran->execute([$id_siswa]);
    $setoran_valid = $stmt_setoran->fetchColumn() ?? 0;

    // Hitung setoran pending
    $stmt_pending = $pdo->prepare("SELECT SUM(jumlah) FROM transaksi WHERE id_siswa = ? AND jenis_transaksi = 'setoran' AND status = 'pending'");
    $stmt_pending->execute([$id_siswa]);
    $setoran_pending = $stmt_pending->fetchColumn() ?? 0;

} catch (PDOException $e) {
    $total_saldo = $setoran_valid = $setoran_pending = 0;
    $nama_kelas = '';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Siswa</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-blue: #4a4ff2;
            --secondary-blue: #5b64ff;
            --bg-color: #f0f4f9;
            --text-color: #343a40;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        body {
            font-family: 'Nunito', sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
        }
        .header {
            background-color: #fff;
            box-shadow: var(--card-shadow);
            padding: 1rem;
        }
        .saldo-card {
            background: linear-gradient(135deg, var(--primary-blue), var(--secondary-blue));
            color: #fff;
            border-radius: 1.5rem;
            padding: 2rem;
            box-shadow: var(--card-shadow);
        }
        .saldo-card .saldo-title {
            font-size: 1.2rem;
            opacity: 0.8;
        }
        .saldo-card .saldo-amount {
            font-size: 3rem;
            font-weight: 700;
        }
        .saldo-card .saldo-detail {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        .menu-card {
            border-radius: 1rem;
            box-shadow: var(--card-shadow);
            transition: transform 0.2s;
            text-decoration: none;
            color: var(--text-color);
        }
        .menu-card:hover {
            transform: translateY(-5px);
        }
        .menu-card .card-body {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }
        .menu-card .menu-icon {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
        }
        .menu-title {
            font-weight: 600;
        }
        .rekap-transaksi-table th, .rekap-transaksi-table td {
            font-size: 0.85rem;
            font-weight: 400;
        }
        .rekap-transaksi-table th {
            font-weight: 600;
        }
        .header .d-flex.align-items-center {
            cursor: pointer;
        }
        input[type="date"]::-webkit-calendar-picker-indicator {
            display: block;
            opacity: 1;
        }

            /* Aturan CSS khusus untuk modal Ganti Password/PIN */
    #gantiPasswordModal .modal-content {
        font-family: 'Arial Narrow', Arial, sans-serif; /* Ganti font */
    }

    #gantiPasswordModal .modal-dialog {
        max-width: 300px; /* Ukuran modal yang lebih kecil */
        margin: 1.75rem auto; /* Atur posisi agar tetap di tengah */
    }

    #gantiPasswordModal .modal-header h5 {
        font-size: 1rem; /* Perkecil ukuran judul */
    }

    #gantiPasswordModal .modal-body .form-label,
    #gantiPasswordModal .modal-body .form-control,
    #gantiPasswordModal .modal-body button {
        font-size: 0.85rem; /* Perkecil ukuran font untuk label, input, dan tombol */
    }

    #gantiPasswordModal .modal-body .mb-3 {
        margin-bottom: 0.75rem !important; /* Buat form lebih rapat */
    }

    #gantiPasswordModal .modal-body hr {
        margin: 0.5rem 0 !important; /* Perkecil margin pada garis pemisah */
    }
    
    </style>
</head>
<body>
    <div class="container py-4">
        <header class="d-flex justify-content-between align-items-center mb-4 header rounded-pill">
            <div class="d-flex align-items-center" role="button" data-bs-toggle="modal" data-bs-target="#gantiPasswordModal">
                <i class="bi bi-person-circle fs-3 me-2"></i>
                <h4 class="mb-0"><i>Halo,</i><b> <?= htmlspecialchars($nama_siswa) ?></b></h4>
            </div>
            <a href="logout.php" class="btn btn-outline-danger btn-sm">
                <i class="bi bi-box-arrow-right"></i> Logout
            </a>
        </header>

        <div class="row g-4 mb-4">
            <div class="col-12">
                <div class="saldo-card">
                    <p class="saldo-title mb-1">Saldo Tabungan Anda <B>Rp.</B></p>
                    <div class="d-flex justify-content-between align-items-center">
                        <h2 class="saldo-amount" id="saldo-hidden">
                            *****<?= substr(number_format($total_saldo, 0, ',', '.'), -4) ?>
                        </h2>
                        <h2 class="saldo-amount d-none" id="saldo-visible">
                            <?= number_format($total_saldo, 0, ',', '.') ?>
                        </h2>
                        
                        <i class="bi bi-eye-slash-fill fs-3" id="toggle-saldo" role="button"></i>
                    </div>
                    <div class="mt-2 saldo-detail">
                        <p class="mb-0">Setoran Valid : Rp<?= number_format($setoran_valid, 0, ',', '.') ?></p>
                        <p class="mb-0">Setoran Pending : Rp<?= number_format($setoran_pending, 0, ',', '.') ?></p>
                    </div>
                </div>
            </div>
        </div>
        <p class="text-center"><b>Madu Mandiri Saving</b></p>

        <div class="row row-cols-2 row-cols-md-4 g-4 text-center">
            <div class="col">
                <a href="#" class="card menu-card h-100" data-bs-toggle="modal" data-bs-target="#setoranModal">
                    <div class="card-body">
                        <i class="bi bi-cash-stack menu-icon text-success"></i>
                        <p class="menu-title">Setoran</p>
                    </div>
                </a>
            </div>
            <div class="col">
                <a href="#" class="card menu-card h-100" data-bs-toggle="modal" data-bs-target="#penarikanModal">
                    <div class="card-body">
                        <i class="bi bi-cash-stack menu-icon text-danger"></i>
                        <p class="menu-title">Penarikan</p>
                    </div>
                </a>
            </div>
            <div class="col">
                <a href="#" class="card menu-card h-100" data-bs-toggle="modal" data-bs-target="#transferModal">
                    <div class="card-body">
                        <i class="bi bi-arrow-left-right menu-icon text-primary"></i>
                        <p class="menu-title">Transfer</p>
                    </div>
                </a>
            </div>
            <div class="col">
                <a href="#" class="card menu-card h-100" data-bs-toggle="modal" data-bs-target="#paymentModal">
                    <div class="card-body">
                        <i class="bi bi-credit-card menu-icon text-warning"></i>
                        <p class="menu-title">Payment</p>
                    </div>
                </a>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-12">
                <div class="card menu-card h-100 p-3" role="button" data-bs-toggle="collapse" data-bs-target="#rekapTransaksiCollapse" aria-expanded="false" aria-controls="rekapTransaksiCollapse">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-journal-text me-3 fs-3 text-info"></i>
                        <p class="menu-title mb-0">Rekap Transaksi (Buku Tabungan)</p>
                        <i class="bi bi-chevron-down ms-auto" id="rekap-chevron"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="collapse mt-4" id="rekapTransaksiCollapse">
            <div class="card card-body">
                <div id="transaksi-content">
                    <p class="text-center text-muted mt-3">Memuat data...</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="setoranModal" tabindex="-1" aria-labelledby="setoranModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="setoranModalLabel">Formulir Setoran</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formSetoran">
                        <div class="mb-3">
                            <label for="tanggal_setoran" class="form-label">Tanggal Setoran</label>
                            <input type="date" class="form-control" id="tanggal_setoran" name="tanggal" required>
                        </div>
                        <div class="mb-3">
                            <label for="jumlah_setoran" class="form-label">Jumlah Setoran (Rp)</label>
                            <input type="number" class="form-control" id="jumlah_setoran" name="jumlah" required>
                        </div>
                        <p class="text-muted"><small>Setoran akan divalidasi oleh Admin.</small></p>
                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-primary">Ajukan Setoran</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="penarikanModal" tabindex="-1" aria-labelledby="penarikanModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="penarikanModalLabel">Formulir Penarikan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formPenarikan">
                        <div class="mb-3">
                            <label for="jumlah_penarikan" class="form-label">Jumlah Penarikan (Rp)</label>
                            <input type="number" class="form-control" id="jumlah_penarikan" name="jumlah" required>
                        </div>
                        <p class="text-muted"><small>Penarikan akan divalidasi oleh Admin.</small></p>
                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-danger">Ajukan Penarikan</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="transferModal" tabindex="-1" aria-labelledby="transferModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="transferModalLabel">Formulir Transfer</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formTransfer">
                        <div class="mb-3">
                            <label for="siswa_tujuan" class="form-label">Siswa Tujuan</label>
                            <select class="form-select" id="siswa_tujuan" name="id_siswa_tujuan" required>
                                <option value="" disabled selected>Pilih siswa</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="jumlah_transfer" class="form-label">Jumlah Transfer (Rp)</label>
                            <input type="number" class="form-control" id="jumlah_transfer" name="jumlah" required>
                            <p class="text-muted"><small>PERHATIAN : Pembayaran akan dieksekusi langsung, tanpa divalidasi oleh Admin.</small></p>
                        </div>
                        
                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-primary">Transfer Sekarang</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="pinTransferModal" tabindex="-1" aria-labelledby="pinTransferModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="pinTransferModalLabel">Masukkan PIN</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formPinTransfer">
                        <div class="mb-3">
                            <label for="pin_transfer" class="form-label">PIN</label>
                            <input type="password" class="form-control" id="pin_transfer" name="pin" required>
                        </div>
                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-primary">Konfirmasi Transfer</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paymentModalLabel">Formulir Pembayaran</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formPayment">
                        <div class="mb-3">
                            <label for="jenis_payment" class="form-label">Jenis Pembayaran</label>
                            <select class="form-select" id="jenis_payment" name="jenis_payment" required>
                                <option value="" disabled selected>Pilih Jenis Pembayaran</option>
                                <option value="Biaya PPDB">Biaya PPDB</option>
                                <option value="SPP">SPP</option>
                                <option value="Baju Batik">Baju Batik</option>
                                <option value="Baju Olga">Baju Olga</option>
                                <option value="Kerudung">Kerudung</option>
                                <option value="Peci">Peci</option>
                                <option value="Dasi">Dasi</option>
                                <option value="Lain-lain">Lain-lain</option>
                            </select>
                        </div>
                        <div class="mb-3" id="lain-lain-group" style="display: none;">
                            <label for="payment_lain_lain" class="form-label">Keterangan Lain-lain</label>
                            <input type="text" class="form-control" id="payment_lain_lain" name="keterangan_lain">
                        </div>
                        <div class="mb-3">
                            <label for="jumlah_payment" class="form-label">Jumlah Pembayaran (Rp)</label>
                            <input type="number" class="form-control" id="jumlah_payment" name="jumlah" required>
                        </div>
                        
                        <p class="text-muted"><small>Pembayaran akan divalidasi oleh Admin.</small></p>
                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-warning">Ajukan Pembayaran</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="gantiPasswordModal" tabindex="-1" aria-labelledby="gantiPasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="gantiPasswordModalLabel"><b>Ganti Password</b></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="formGantiPassword">
                    <div class="mb-3">
                        <label for="password_lama" class="form-label">Password Lama</label>
                        <input type="password" class="form-control" id="password_lama" name="password_lama" required>
                    </div>
                    <div class="mb-3">
                        <label for="password_baru" class="form-label">Password Baru</label>
                        <input type="password" class="form-control" id="password_baru" name="password_baru" required>
                    </div>
                    <div class="mb-3">
                        <label for="konfirmasi_password" class="form-label">Konfirmasi Password Baru</label>
                        <input type="password" class="form-control" id="konfirmasi_password" name="konfirmasi_password" required>
                    </div>
                    <div class="d-grid mt-3">
                        <button type="submit" class="btn btn-primary">Simpan Password Baru</button>
                    </div>
                </form>
                <hr class="my-4">
                <h5 class="modal-title"><b>Ganti PIN</b></h5>

                <form id="formGantiPin">
                    <div class="mb-3">
                        <label for="pin_lama" class="form-label">PIN Lama</label>
                        <input type="password" class="form-control" id="pin_lama" name="pin_lama" required>
                    </div>
                    <div class="mb-3">
                        <label for="pin_baru" class="form-label">PIN Baru</label>
                        <input type="password" class="form-control" id="pin_baru" name="pin_baru" required>
                    </div>
                    <div class="mb-3">
                        <label for="konfirmasi_pin" class="form-label">Konfirmasi PIN Baru</label>
                        <input type="password" class="form-control" id="konfirmasi_pin" name="konfirmasi_pin" required>
                    </div>
                    <div class="d-grid mt-3">
                        <button type="submit" class="btn btn-primary">Simpan PIN Baru</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

    
    <div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">Pesan Notifikasi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <i id="statusIcon" class="bi fs-1 mb-3"></i>
                    <p id="statusMessage" class="fw-bold"></p>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Data sementara untuk transfer
            let transferData = {};

            // Fungsi untuk menampilkan modal status kustom
            function showStatusModal(status, message) {
                const modal = new bootstrap.Modal(document.getElementById('statusModal'));
                const icon = document.getElementById('statusIcon');
                const msg = document.getElementById('statusMessage');

                if (status === 'success') {
                    icon.className = 'bi bi-check-circle-fill text-success fs-1 mb-3';
                } else {
                    icon.className = 'bi bi-exclamation-triangle-fill text-danger fs-1 mb-3';
                }
                msg.textContent = message;
                modal.show();
            }

            // Logika untuk form transaksi (selain transfer)
            function handleFormSubmit(formId, url, modalId) {
                const form = document.getElementById(formId);
                if (form) {
                    form.addEventListener('submit', function(event) {
                        event.preventDefault();
                        
                        const formData = new FormData(form);
                        // Tambahkan jenis transaksi ke formData
                        if (formId === 'formSetoran') formData.append('jenis_transaksi', 'setoran');
                        if (formId === 'formPenarikan') formData.append('jenis_transaksi', 'penarikan');
                        if (formId === 'formPayment') formData.append('jenis_transaksi', 'payment');

                        fetch(url, {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            showStatusModal(data.status, data.message);
                            if (data.status === 'success') {
                                const modalElement = document.getElementById(modalId);
                                const modalInstance = bootstrap.Modal.getInstance(modalElement);
                                if (modalInstance) {
                                    modalInstance.hide();
                                }
                                // Beri sedikit waktu sebelum reload agar modal status terlihat
                                setTimeout(() => window.location.reload(), 1500);
                            }
                        })
                        .catch(error => {
                            showStatusModal('error', 'Terjadi kesalahan saat memproses transaksi.');
                            console.error('Error:', error);
                        });
                    });
                }
            }
            
            // Inisialisasi event listener untuk form setoran, penarikan, dan payment
            handleFormSubmit('formSetoran', 'proses_transaksi.php', 'setoranModal');
            handleFormSubmit('formPenarikan', 'proses_transaksi.php', 'penarikanModal');
            handleFormSubmit('formPayment', 'proses_transaksi.php', 'paymentModal');
            
            // Logika untuk form TRANSFER (khusus)
            const formTransfer = document.getElementById('formTransfer');
            formTransfer.addEventListener('submit', function(event) {
                event.preventDefault();

                // Simpan data transfer ke variabel sementara
                transferData.id_siswa_tujuan = document.getElementById('siswa_tujuan').value;
                transferData.jumlah = document.getElementById('jumlah_transfer').value;

                // Tutup modal transfer
                const transferModal = bootstrap.Modal.getInstance(document.getElementById('transferModal'));
                transferModal.hide();

                // Tampilkan modal PIN
                const pinTransferModal = new bootstrap.Modal(document.getElementById('pinTransferModal'));
                pinTransferModal.show();
            });

            const formPinTransfer = document.getElementById('formPinTransfer');
            formPinTransfer.addEventListener('submit', function(event) {
                event.preventDefault();

                const formData = new FormData();
                formData.append('jenis_transaksi', 'transfer');
                formData.append('id_siswa_tujuan', transferData.id_siswa_tujuan);
                formData.append('jumlah', transferData.jumlah);
                formData.append('pin', document.getElementById('pin_transfer').value);

                fetch('proses_transaksi.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    showStatusModal(data.status, data.message);
                    if (data.status === 'success') {
                        const modalElement = document.getElementById('pinTransferModal');
                        const modalInstance = bootstrap.Modal.getInstance(modalElement);
                        if (modalInstance) {
                            modalInstance.hide();
                        }
                        setTimeout(() => window.location.reload(), 1500);
                    }
                })
                .catch(error => {
                    showStatusModal('error', 'Terjadi kesalahan saat memproses transfer.');
                    console.error('Error:', error);
                });
            });

            // Logika untuk Modal Payment
            const jenisPaymentSelect = document.getElementById('jenis_payment');
            const lainLainGroup = document.getElementById('lain-lain-group');

            jenisPaymentSelect.addEventListener('change', function() {
                if (this.value === 'Lain-lain') {
                    lainLainGroup.style.display = 'block';
                    document.getElementById('payment_lain_lain').setAttribute('required', 'required');
                } else {
                    lainLainGroup.style.display = 'none';
                    document.getElementById('payment_lain_lain').removeAttribute('required');
                }
            });

            // Logika untuk Modal Transfer
            const transferModal = document.getElementById('transferModal');
            transferModal.addEventListener('show.bs.modal', function() {
                const siswaTujuanSelect = document.getElementById('siswa_tujuan');
                siswaTujuanSelect.innerHTML = '<option value="" disabled selected>Memuat...</option>';
                
                fetch('fetch_siswa_for_transfer.php')
                    .then(response => response.json())
                    .then(data => {
                        let options = '<option value="" disabled selected>Pilih siswa</option>';
                        data.forEach(siswa => {
                            options += `<option value="${siswa.id_siswa}">${siswa.nama_siswa} (${siswa.nama_kelas})</option>`;
                        });
                        siswaTujuanSelect.innerHTML = options;
                    })
                    .catch(error => {
                        siswaTujuanSelect.innerHTML = '<option value="" disabled selected>Gagal memuat data</option>';
                        console.error('Error:', error);
                    });
            });

            // Logika untuk Collapse Rekap Transaksi
            const rekapCollapse = document.getElementById('rekapTransaksiCollapse');
            rekapCollapse.addEventListener('show.bs.collapse', function () {
                loadRekapTransaksi();
            });
            rekapCollapse.addEventListener('shown.bs.collapse', function () {
                document.getElementById('rekap-chevron').classList.remove('bi-chevron-down');
                document.getElementById('rekap-chevron').classList.add('bi-chevron-up');
            });
            rekapCollapse.addEventListener('hide.bs.collapse', function () {
                document.getElementById('rekap-chevron').classList.remove('bi-chevron-up');
                document.getElementById('rekap-chevron').classList.add('bi-chevron-down');
            });

            function loadRekapTransaksi() {
                const contentArea = document.getElementById('transaksi-content');
                if (!contentArea) {
                    console.error('Elemen content transaksi tidak ditemukan.');
                    return;
                }
                contentArea.innerHTML = '<p class="text-center text-muted mt-3">Memuat data...</p>';
                
                fetch('fetch_rekap_transaksi.php?filter=all')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Respons jaringan tidak OK');
                        }
                        return response.text();
                    })
                    .then(data => {
                        contentArea.innerHTML = data;
                    })
                    .catch(error => {
                        console.error('Terjadi kesalahan saat memuat rekap transaksi:', error);
                        contentArea.innerHTML = `<div class="alert alert-danger">Gagal memuat rekap transaksi. Silakan coba lagi.</div>`;
                    });
            }


            // Logika untuk form Ganti Password
            const formGantiPassword = document.getElementById('formGantiPassword');
            if (formGantiPassword) {
                formGantiPassword.addEventListener('submit', function(event) {
                    event.preventDefault();

                    const passwordBaru = document.getElementById('password_baru').value;
                    const konfirmasiPassword = document.getElementById('konfirmasi_password').value;

                    if (passwordBaru !== konfirmasiPassword) {
                        showStatusModal('error', 'Password baru dan konfirmasi password tidak cocok.');
                        return;
                    }

                    const formData = new FormData(formGantiPassword);
                    fetch('proses_ganti_password.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        showStatusModal(data.status, data.message);
                        if (data.status === 'success') {
                            formGantiPassword.reset();
                        }
                    })
                    .catch(error => {
                        showStatusModal('error', 'Terjadi kesalahan saat mengganti password.');
                        console.error('Error:', error);
                    });
                });
            }
            
            // Logika untuk form Ganti PIN
            const formGantiPin = document.getElementById('formGantiPin');
            if (formGantiPin) {
                formGantiPin.addEventListener('submit', function(event) {
                    event.preventDefault();
                    
                    const pinBaru = document.getElementById('pin_baru').value;
                    const konfirmasiPin = document.getElementById('konfirmasi_pin').value;

                    if (pinBaru.length !== 6) {
                        showStatusModal('error', 'PIN harus 6 digit angka.');
                        return;
                    }

                    if (pinBaru !== konfirmasiPin) {
                        showStatusModal('error', 'PIN baru dan konfirmasi PIN tidak cocok.');
                        return;
                    }

                    const formData = new FormData(formGantiPin);
                    fetch('proses_ganti_pin.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        showStatusModal(data.status, data.message);
                        if (data.status === 'success') {
                            formGantiPin.reset();
                            const modalElement = document.getElementById('gantiPasswordModal');
                            const modalInstance = bootstrap.Modal.getInstance(modalElement);
                            if (modalInstance) {
                                modalInstance.hide();
                            }
                        }
                    })
                    .catch(error => {
                        showStatusModal('error', 'Terjadi kesalahan saat mengganti PIN.');
                        console.error('Error:', error);
                    });
                });
            }

            // --- LOGIKA TOGGLE SALDO ---
            const toggleSaldoBtn = document.getElementById('toggle-saldo');
            const saldoHidden = document.getElementById('saldo-hidden');
            const saldoVisible = document.getElementById('saldo-visible');
            
            if (toggleSaldoBtn && saldoHidden && saldoVisible) {
                toggleSaldoBtn.addEventListener('click', function() {
                    // Toggle class 'd-none' untuk menyembunyikan/menampilkan saldo
                    saldoHidden.classList.toggle('d-none');
                    saldoVisible.classList.toggle('d-none');

                    // Ganti ikon mata
                    if (this.classList.contains('bi-eye-slash-fill')) {
                        this.classList.remove('bi-eye-slash-fill');
                        this.classList.add('bi-eye-fill');
                    } else {
                        this.classList.remove('bi-eye-fill');
                        this.classList.add('bi-eye-slash-fill');
                    }
                });
            }
            // --- END LOGIKA TOGGLE SALDO ---

        });
    </script>
</body>
</html>