@extends('layouts.app')

@section('content')
{{-- Select2 CSS --}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">

<style>
/* ═══════════════════════════════════════════
   OVERRIDE SELECT2 agar sesuai tema
═══════════════════════════════════════════ */
.select2-container--default .select2-selection--single {
    height: 44px;
    border: 1.5px solid #d1d9e0;
    border-radius: 10px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    transition: border-color .2s, box-shadow .2s;
    background: #fff;
}
.select2-container--default .select2-selection--single:hover {
    border-color: var(--primary-color, #6FBA9D);
}
.select2-container--default.select2-container--focus .select2-selection--single,
.select2-container--default.select2-container--open .select2-selection--single {
    border-color: var(--primary-color, #6FBA9D);
    box-shadow: 0 0 0 3px rgba(111,186,157,.18);
    outline: none;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 1.4;
    color: #333;
    padding: 0;
    font-size: .93rem;
}
.select2-container--default .select2-selection--single .select2-selection__placeholder {
    color: #aaa;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 42px;
    right: 10px;
}
.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: var(--primary-color, #6FBA9D);
}
.select2-dropdown {
    border: 1.5px solid var(--primary-color, #6FBA9D);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0,0,0,.12);
    overflow: hidden;
}
.select2-search--dropdown .select2-search__field {
    border: 1.5px solid #d1d9e0;
    border-radius: 7px;
    padding: 7px 10px;
    font-size: .88rem;
    outline: none;
}
.select2-search--dropdown .select2-search__field:focus {
    border-color: var(--primary-color, #6FBA9D);
}
.select2-results__option {
    padding: 9px 14px;
    font-size: .88rem;
}

/* ═══════════════════════════════════════════
   LABEL FIELD
═══════════════════════════════════════════ */
.field-label {
    display: block;
    font-weight: 600;
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: .5px;
    color: var(--text-light, #888);
    margin-bottom: 8px;
}
.field-label .fi { margin-right: 5px; color: var(--primary-color, #6FBA9D); }

/* ═══════════════════════════════════════════
   CARD PILIH JENIS TRANSAKSI
═══════════════════════════════════════════ */
.jenis-cards {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
}
.jenis-card {
    position: relative;
    cursor: pointer;
    border-radius: 14px;
    border: 2.5px solid #e0e7ef;
    padding: 18px 16px 16px;
    transition: border-color .2s, box-shadow .2s, transform .15s, background .2s;
    background: #fff;
    user-select: none;
    -webkit-user-select: none;
}
.jenis-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.09); }
.jenis-card input[type="radio"] { position:absolute; opacity:0; width:0; height:0; }
.jenis-card .ji-wrap {
    width: 46px; height: 46px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.25rem;
    margin-bottom: 11px;
    transition: background .2s;
}
.jenis-card .ji-title  { font-weight: 700; font-size: .93rem; margin-bottom: 4px; transition: color .2s; }
.jenis-card .ji-desc   { font-size: .75rem; color: #b0b8c4; line-height: 1.4; }
.jenis-card .ji-check  {
    position: absolute; top: 12px; right: 12px;
    width: 22px; height: 22px; border-radius: 50%;
    border: 2px solid #d1d9e0;
    display: flex; align-items: center; justify-content: center;
    font-size: .68rem; color: transparent;
    transition: all .2s;
}

/* Pemasukan aktif */
.jenis-card.pemasukan.active {
    border-color: #6FBA9D;
    background: linear-gradient(135deg, #f0fdf7 0%, #e6f9f2 100%);
    box-shadow: 0 4px 18px rgba(111,186,157,.22);
}
.jenis-card.pemasukan .ji-wrap       { background: #edf9f4; color: #6FBA9D; }
.jenis-card.pemasukan.active .ji-wrap { background: rgba(111,186,157,.2); color: #38a169; }
.jenis-card.pemasukan.active .ji-title { color: #38a169; }
.jenis-card.pemasukan.active .ji-check { background: #6FBA9D; border-color: #6FBA9D; color: #fff; }

/* Pengeluaran aktif */
.jenis-card.pengeluaran.active {
    border-color: #FF8B94;
    background: linear-gradient(135deg, #fff5f6 0%, #ffe9eb 100%);
    box-shadow: 0 4px 18px rgba(255,139,148,.22);
}
.jenis-card.pengeluaran .ji-wrap       { background: #fff0f1; color: #FF8B94; }
.jenis-card.pengeluaran.active .ji-wrap { background: rgba(255,139,148,.2); color: #e53e3e; }
.jenis-card.pengeluaran.active .ji-title { color: #e53e3e; }
.jenis-card.pengeluaran.active .ji-check { background: #FF8B94; border-color: #FF8B94; color: #fff; }

/* ═══════════════════════════════════════════
   BOX PERINGATAN SALDO
═══════════════════════════════════════════ */
#warning-saldo {
    display: none;
    border-radius: 10px;
    border: 1.5px solid #FC8181;
    background: linear-gradient(135deg, #fff5f5 0%, #ffecec 100%);
    padding: 13px 16px;
    margin-top: 10px;
    animation: warnIn .22s ease;
}
@keyframes warnIn {
    from { opacity: 0; transform: translateY(-6px); }
    to   { opacity: 1; transform: translateY(0); }
}
#warning-saldo .wt { font-weight: 700; color: #c53030; font-size: .87rem; margin-bottom: 5px; }
#warning-saldo .wb { font-size: .8rem; color: #742a2a; line-height: 1.55; }
#warning-saldo .ws-grid {
    display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 10px;
}
#warning-saldo .ws-cell {
    background: rgba(255,255,255,.75); border-radius: 8px;
    padding: 8px 10px; text-align: center;
}
#warning-saldo .ws-cell small { display:block; font-size:.68rem; color:#aaa; margin-bottom:3px; }
#warning-saldo .ws-cell strong { font-size:.86rem; font-weight:700; }

/* ═══════════════════════════════════════════
   INPUT NOMINAL
═══════════════════════════════════════════ */
.nominal-wrap { position: relative; display: flex; align-items: center; }
.nominal-prefix {
    position: absolute; left: 14px;
    font-weight: 700; color: #aaa;
    pointer-events: none; font-size: .93rem; z-index: 1;
}
.nominal-wrap input {
    padding-left: 44px !important;
    font-size: 1rem; font-weight: 600; letter-spacing: .3px;
    height: 44px; border-radius: 10px;
    border: 1.5px solid #d1d9e0;
    transition: border-color .2s, box-shadow .2s;
    width: 100%;
}
.nominal-wrap input:focus {
    border-color: var(--primary-color, #6FBA9D);
    box-shadow: 0 0 0 3px rgba(111,186,157,.18);
    outline: none;
}
.nominal-wrap.danger input {
    border-color: #FC8181 !important;
    box-shadow: 0 0 0 3px rgba(255,139,148,.18) !important;
}

/* form-control radius konsisten */
.form-control { border-radius: 10px !important; border: 1.5px solid #d1d9e0; transition: border-color .2s, box-shadow .2s; }
.form-control:focus {
    border-color: var(--primary-color, #6FBA9D) !important;
    box-shadow: 0 0 0 3px rgba(111,186,157,.18) !important;
    outline: none;
}
textarea.form-control { height: auto; }

/* ═══════════════════════════════════════════
   INFO CARD SANTRI
═══════════════════════════════════════════ */
#santri-info {
    border-radius: 12px; overflow: hidden;
    margin-bottom: 20px;
    border: 1.5px solid var(--primary-color, #6FBA9D);
    box-shadow: 0 4px 14px rgba(111,186,157,.13);
    animation: fadeUp .22s ease;
}
@keyframes fadeUp {
    from { opacity:0; transform:translateY(6px); }
    to   { opacity:1; transform:translateY(0); }
}
.si-header {
    background: linear-gradient(90deg, #6FBA9D 0%, #38a169 100%);
    padding: 10px 16px;
    display: flex; align-items: center; gap: 8px;
    color: #fff; font-weight: 700;
    font-size: .8rem; text-transform: uppercase; letter-spacing: .45px;
}
.si-body { padding: 14px 16px; background: #f9fdfb; }
.si-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 12px; }
.si-stat {
    background: #fff; border-radius: 9px;
    padding: 10px 12px; text-align: center;
    border: 1px solid #e8f5ef;
}
.si-stat small { display:block; font-size:.68rem; color:#aaa; text-transform:uppercase; letter-spacing:.3px; margin-bottom:4px; }
.si-val { font-size: .93rem; font-weight: 800; }

.form-group { margin-bottom: 20px; }
</style>

<div class="page-header">
    <h2><i class="fas fa-plus-circle"></i> Tambah Transaksi Uang Saku</h2>
</div>

<div class="form-container">
    <form action="{{ route('admin.uang-saku.store') }}" method="POST" id="transaksiForm">
        @csrf

        {{-- ══════════════════════════════════════
             1. PILIH SANTRI
        ══════════════════════════════════════ --}}
        <div class="form-group">
            <label class="field-label" for="id_santri">
                <i class="fas fa-user fi"></i> Pilih Santri
                <span style="color:#e53e3e;font-weight:700;">*</span>
            </label>
            <select name="id_santri" id="id_santri"
                    class="form-control @error('id_santri') is-invalid @enderror" required>
                <option value="">Cari ID atau nama santri...</option>
                @foreach($santriList as $santri)
                    <option value="{{ $santri->id_santri }}"
                        {{ (old('id_santri', request('id_santri')) == $santri->id_santri) ? 'selected' : '' }}>
                        {{ $santri->id_santri }} — {{ $santri->nama_lengkap }}
                    </option>
                @endforeach
            </select>
            @error('id_santri')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>

        {{-- Info Card Santri --}}
        <div id="santri-info" style="display:none;">
            <div class="si-header">
                <i class="fas fa-id-card"></i>
                <span id="info-nama">—</span>
            </div>
            <div class="si-body">
                <div class="si-stats">
                    <div class="si-stat">
                        <small>Saldo Saat Ini</small>
                        <div class="si-val" id="info-saldo">—</div>
                    </div>
                    <div class="si-stat">
                        <small>Masuk Bln Ini</small>
                        <div class="si-val" id="info-masuk" style="color:#6FBA9D;">—</div>
                    </div>
                    <div class="si-stat">
                        <small>Keluar Bln Ini</small>
                        <div class="si-val" id="info-keluar" style="color:#FF8B94;">—</div>
                    </div>
                </div>
                <div id="info-riwayat"></div>
            </div>
        </div>

        {{-- ══════════════════════════════════════
             2. JENIS TRANSAKSI — Card pilihan
        ══════════════════════════════════════ --}}
        <div class="form-group">
            <label class="field-label">
                <i class="fas fa-exchange-alt fi"></i> Jenis Transaksi
                <span style="color:#e53e3e;font-weight:700;">*</span>
            </label>

            {{-- Hidden select → dikirim ke server & divalidasi Laravel --}}
            <select name="jenis_transaksi" id="jenis_transaksi" style="display:none;"
                    class="@error('jenis_transaksi') is-invalid @enderror" required>
                <option value=""></option>
                <option value="pemasukan"   {{ old('jenis_transaksi') == 'pemasukan'   ? 'selected' : '' }}>pemasukan</option>
                <option value="pengeluaran" {{ old('jenis_transaksi') == 'pengeluaran' ? 'selected' : '' }}>pengeluaran</option>
            </select>

            <div class="jenis-cards">
                <div class="jenis-card pemasukan {{ old('jenis_transaksi') == 'pemasukan' ? 'active' : '' }}"
                     id="card-pemasukan" onclick="pilihJenis('pemasukan')" role="button" tabindex="0"
                     onkeydown="if(event.key==='Enter'||event.key===' ')pilihJenis('pemasukan')">
                    <input type="radio" name="_jenis_ui" value="pemasukan"
                           {{ old('jenis_transaksi') == 'pemasukan' ? 'checked' : '' }}>
                    <div class="ji-wrap"><i class="fas fa-arrow-circle-down"></i></div>
                    <div class="ji-title">Pemasukan</div>
                    <div class="ji-desc">Santri menerima uang saku dari wali / pesantren</div>
                    <div class="ji-check"><i class="fas fa-check"></i></div>
                </div>

                <div class="jenis-card pengeluaran {{ old('jenis_transaksi') == 'pengeluaran' ? 'active' : '' }}"
                     id="card-pengeluaran" onclick="pilihJenis('pengeluaran')" role="button" tabindex="0"
                     onkeydown="if(event.key==='Enter'||event.key===' ')pilihJenis('pengeluaran')">
                    <input type="radio" name="_jenis_ui" value="pengeluaran"
                           {{ old('jenis_transaksi') == 'pengeluaran' ? 'checked' : '' }}>
                    <div class="ji-wrap"><i class="fas fa-arrow-circle-up"></i></div>
                    <div class="ji-title">Pengeluaran</div>
                    <div class="ji-desc">Santri menggunakan uang saku untuk keperluan</div>
                    <div class="ji-check"><i class="fas fa-check"></i></div>
                </div>
            </div>

            @error('jenis_transaksi')
                <div style="color:#e53e3e;font-size:.82rem;margin-top:6px;">
                    <i class="fas fa-exclamation-circle"></i> {{ $message }}
                </div>
            @enderror
        </div>

        {{-- ══════════════════════════════════════
             3. NOMINAL
        ══════════════════════════════════════ --}}
        <div class="form-group">
            <label class="field-label" for="nominal_display">
                <i class="fas fa-money-bill-wave fi"></i> Nominal (Rp)
                <span style="color:#e53e3e;font-weight:700;">*</span>
            </label>

            <div class="nominal-wrap" id="nominalWrap">
                <span class="nominal-prefix">Rp</span>
                <input type="text"
                       id="nominal_display"
                       class="@error('nominal') is-invalid @enderror"
                       placeholder="0"
                       autocomplete="off"
                       inputmode="numeric"
                       value="{{ old('nominal') ? number_format((int)old('nominal'), 0, ',', '.') : '' }}">
            </div>
            <input type="hidden" name="nominal" id="nominal" value="{{ old('nominal') }}">

            @error('nominal')
                <div style="color:#e53e3e;font-size:.82rem;margin-top:5px;">
                    <i class="fas fa-exclamation-circle"></i> {{ $message }}
                </div>
            @enderror
         

            {{-- ── KOTAK PERINGATAN SALDO TIDAK CUKUP ── --}}
            <div id="warning-saldo">
                <div class="wt">
                    <i class="fas fa-exclamation-triangle"></i>
                    Peringatan: Saldo Tidak Mencukupi!
                </div>
                <div class="wb">
                    Nominal pengeluaran yang dimasukkan melebihi saldo santri saat ini.
                    Sistem akan menolak transaksi ini. Silakan kurangi nominal atau pastikan
                    data saldo sudah benar.
                </div>
                <div class="ws-grid">
                    <div class="ws-cell">
                        <small>Saldo Tersedia</small>
                        <strong id="warn-saldo" style="color:#38a169;">—</strong>
                    </div>
                    <div class="ws-cell">
                        <small>Nominal Diinput</small>
                        <strong id="warn-nominal" style="color:#c53030;">—</strong>
                    </div>
                    <div class="ws-cell">
                        <small>Kekurangan</small>
                        <strong id="warn-kurang" style="color:#c53030;">—</strong>
                    </div>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════
             4. TANGGAL
        ══════════════════════════════════════ --}}
        <div class="form-group">
            <label class="field-label" for="tanggal_transaksi">
                <i class="fas fa-calendar fi"></i> Tanggal Transaksi
                <span style="color:#e53e3e;font-weight:700;">*</span>
            </label>
            <input type="date" name="tanggal_transaksi" id="tanggal_transaksi"
                   class="form-control @error('tanggal_transaksi') is-invalid @enderror"
                   value="{{ old('tanggal_transaksi', date('Y-m-d')) }}" required>
            @error('tanggal_transaksi')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>

        {{-- ══════════════════════════════════════
             5. KETERANGAN
        ══════════════════════════════════════ --}}
        <div class="form-group">
            <label class="field-label" for="keterangan">
                <i class="fas fa-sticky-note fi"></i> Keterangan
                <span style="font-weight:400;text-transform:none;letter-spacing:0;color:#bbb;">(opsional)</span>
            </label>
            <textarea name="keterangan" id="keterangan"
                      class="form-control @error('keterangan') is-invalid @enderror"
                      rows="3"
                      placeholder="Contoh: Uang saku januari">{{ old('keterangan') }}</textarea>
            @error('keterangan')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>

        <div class="btn-group">
            <button type="submit" class="btn btn-success hover-lift" id="btnSubmit">
                <i class="fas fa-save"></i> Simpan Transaksi
            </button>
            <a href="{{ route('admin.uang-saku.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// ═══════════════════════════════════════════
//  STATE GLOBAL
// ═══════════════════════════════════════════
var saldoSantri   = 0;         // saldo raw santri terpilih
var jenisAktif    = '';        // 'pemasukan' | 'pengeluaran' | ''
var nominalBersih = 0;         // nominal tanpa titik

// ═══════════════════════════════════════════
//  FORMAT HELPER
// ═══════════════════════════════════════════
function formatRibuan(val) {
    var b = String(val).replace(/\D/g, '');
    return b ? b.replace(/\B(?=(\d{3})+(?!\d))/g, '.') : '';
}
function stripRibuan(val) { return String(val).replace(/\./g, ''); }
function rpStr(angka)     { return 'Rp\u00a0' + formatRibuan(angka); }

// ═══════════════════════════════════════════
//  PILIH JENIS (kartu)
// ═══════════════════════════════════════════
function pilihJenis(jenis) {
    jenisAktif = jenis;
    document.getElementById('jenis_transaksi').value = jenis;
    document.getElementById('card-pemasukan').classList.toggle('active',   jenis === 'pemasukan');
    document.getElementById('card-pengeluaran').classList.toggle('active', jenis === 'pengeluaran');
    cekPeringatan();
}

// ═══════════════════════════════════════════
//  CEK PERINGATAN SALDO
// ═══════════════════════════════════════════
function cekPeringatan() {
    var box    = document.getElementById('warning-saldo');
    var wrap   = document.getElementById('nominalWrap');
    var btn    = document.getElementById('btnSubmit');

    var kurang = nominalBersih - saldoSantri;
    var tampil = jenisAktif === 'pengeluaran' && nominalBersih > 0 && kurang > 0;

    if (tampil) {
        document.getElementById('warn-saldo').textContent   = rpStr(saldoSantri);
        document.getElementById('warn-nominal').textContent = rpStr(nominalBersih);
        document.getElementById('warn-kurang').textContent  = rpStr(kurang);
        box.style.display = 'block';
        wrap.classList.add('danger');
        btn.style.opacity = '.6';
        btn.title = 'Saldo tidak mencukupi — transaksi akan ditolak!';
    } else {
        box.style.display = 'none';
        wrap.classList.remove('danger');
        btn.style.opacity = '1';
        btn.title = '';
    }
}

// ═══════════════════════════════════════════
//  INPUT NOMINAL — auto titik ribuan
// ═══════════════════════════════════════════
var dispEl   = document.getElementById('nominal_display');
var hiddenEl = document.getElementById('nominal');

dispEl.addEventListener('input', function () {
    var bersih   = stripRibuan(this.value);
    var diformat = formatRibuan(bersih);

    // Jaga posisi kursor agar tidak melompat
    var pos      = this.selectionStart;
    var dotBef   = (this.value.substring(0, pos).match(/\./g) || []).length;
    this.value   = diformat;
    var dotAft   = (diformat.substring(0, pos).match(/\./g) || []).length;
    try { this.setSelectionRange(pos + dotAft - dotBef, pos + dotAft - dotBef); } catch(e) {}

    nominalBersih    = parseInt(bersih) || 0;
    hiddenEl.value   = nominalBersih || '';
    cekPeringatan();
});

// ═══════════════════════════════════════════
//  SUBMIT — konfirmasi ekstra jika saldo kurang
// ═══════════════════════════════════════════
document.getElementById('transaksiForm').addEventListener('submit', function (e) {
    hiddenEl.value = stripRibuan(dispEl.value) || '';

    if (jenisAktif === 'pengeluaran' && nominalBersih > saldoSantri) {
        var lanjut = confirm(
            '\u26a0\ufe0f PERINGATAN: Saldo Tidak Mencukupi!\n\n' +
            'Saldo santri   : ' + rpStr(saldoSantri) + '\n' +
            'Nominal input  : ' + rpStr(nominalBersih) + '\n' +
            'Kekurangan     : ' + rpStr(nominalBersih - saldoSantri) + '\n\n' +
            'Transaksi ini akan DITOLAK oleh sistem.\n' +
            'Yakin tetap ingin melanjutkan?'
        );
        if (!lanjut) { e.preventDefault(); return false; }
    }
});

// ═══════════════════════════════════════════
//  SELECT2 + AJAX INFO SANTRI
// ═══════════════════════════════════════════
$(document).ready(function () {

    $('#id_santri').select2({
        placeholder: 'Cari ID atau nama santri...',
        allowClear: true,
        width: '100%',
        language: {
            noResults:  function () { return 'Santri tidak ditemukan'; },
            searching:  function () { return 'Mencari...'; }
        }
    });

    $('#id_santri').on('change', function () {
        var infoBox = document.getElementById('santri-info');
        var val     = this.value;

        saldoSantri = 0;
        cekPeringatan();

        if (!val) { infoBox.style.display = 'none'; return; }

        fetch('{{ url("admin/uang-saku/santri-info") }}/' + val)
            .then(function (r) { return r.json(); })
            .then(function (d) {
                saldoSantri = d.saldo_raw;

                document.getElementById('info-nama').textContent = d.nama;

                var sc = d.saldo_raw >= 100000 ? '#38a169'
                       : d.saldo_raw >= 20000  ? '#f5a623' : '#e53e3e';
                document.getElementById('info-saldo').innerHTML =
                    '<span style="color:' + sc + '">Rp\u00a0' + d.saldo_terakhir + '</span>';
                document.getElementById('info-masuk').textContent  = 'Rp\u00a0' + d.total_pemasukan_bulan_ini;
                document.getElementById('info-keluar').textContent = 'Rp\u00a0' + d.total_pengeluaran_bulan_ini;

                var html = '';
                if (d.transaksi_terakhir.length > 0) {
                    html  = '<div style="font-size:.7rem;color:#aaa;text-transform:uppercase;letter-spacing:.4px;margin-bottom:7px;">3 Transaksi Terakhir</div>';
                    html += '<table class="data-table" style="font-size:.81rem;"><thead><tr>';
                    html += '<th>Tanggal</th><th>Jenis</th><th>Nominal</th><th>Keterangan</th>';
                    html += '</tr></thead><tbody>';
                    d.transaksi_terakhir.forEach(function (t) {
                        var badge = t.jenis === 'pemasukan'
                            ? '<span class="badge badge-success">Masuk</span>'
                            : '<span class="badge badge-danger">Keluar</span>';
                        html += '<tr><td>' + t.tanggal + '</td><td>' + badge +
                                '</td><td>Rp\u00a0' + t.nominal + '</td><td>' + t.keterangan + '</td></tr>';
                    });
                    html += '</tbody></table>';
                } else {
                    html = '<p style="font-size:.8rem;color:#aaa;margin:0;">Belum ada riwayat transaksi.</p>';
                }
                document.getElementById('info-riwayat').innerHTML = html;
                infoBox.style.display = 'block';

                cekPeringatan();
            })
            .catch(function () {
                document.getElementById('santri-info').style.display = 'none';
                saldoSantri = 0;
            });
    });

    // Trigger jika sudah ada pilihan (dari ?id_santri=xxx atau old())
    if ($('#id_santri').val()) $('#id_santri').trigger('change');

    // Restore jenis dari old() setelah validasi server gagal
    var oldJenis = '{{ old("jenis_transaksi", "") }}';
    if (oldJenis) pilihJenis(oldJenis);
});
</script>
@endsection