<?php
error_reporting(E_ALL^(E_NOTICE|E_WARNING));
ini_set('display_errors',1);
error_reporting(0);
include('koneksi.php'); 
require './kalenderhijriah.php';

$kode = $_SESSION['kode'];

// Check if no_bukti is passed for editing
if(isset($_GET['no_bukti'])) {
$no_bukti = $_GET['no_bukti'];

// Fetch transaction data from mutasitabungan
$query = mysqli_query($koneksi, "SELECT * FROM mutasitabungan WHERE no_bukti='$no_bukti'");
$data = mysqli_fetch_assoc($query);

if($data) {
    $rekening = $data['rekening'];
    $tgl = $data['tgl'];
    $kodetab = $data['kodetab'];
    $nominal = ($kodetab == 'S') ? $data['kredit'] : $data['debet'];
    $keterangan = $data['keterangan'];
    
    // Get rekening parts
    $rekening_parts = explode('.', $rekening);
    $rekening1 = $rekening_parts[0];
    $rekening2 = $rekening_parts[1];
    $rekening3 = substr($rekening_parts[2], 0, 6);
    $rekening4 = $rekening_parts[3];
    
    // Fetch registrant data
    $register = $rekening1.".".sprintf("%06d",$rekening3);
    $reg = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT tgl as tgl, nama as nama, alamat as alamat, ibu as ibu FROM registrasi WHERE id='".$register."' GROUP BY id"));
    
    // Get account balance
    $total = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT sum(kredit-debet) AS total FROM mutasitabungan WHERE rekening='".$rekening."' GROUP BY rekening"));
} else {
    echo "<script>alert('Data tidak ditemukan!'); window.location='home.php?home=".md5("angsuran")."';</script>";
    exit;
}
} elseif(isset($_POST['rekening3'])) {
$id = $_POST['rekening1'].".11".".".sprintf("%06d",$_POST['rekening3']);
$register = $_POST['rekening1'].".".sprintf("%06d",$_POST['rekening3']);
$rekening = $_POST['rekening1'].".11".".".sprintf("%06d",$_POST['rekening3']).".".sprintf("%02d",$_POST['rekening4']);

$reg = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT tgl as tgl, nama as nama, alamat as alamat, ibu as ibu FROM registrasi WHERE id='".$register."' GROUP BY id"));

$rekak = mysqli_query($koneksi,"SELECT count(id) as kodea FROM bukutabungan where rekening='$id2'");
$rekakhir = mysqli_fetch_row($rekak);
$total = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT sum(kredit-debet) AS total FROM mutasitabungan WHERE rekening='".$rekening."' GROUP BY rekening"));
}

function Rp($angka) { 
$jadi = number_format($angka,0,'.',',');
return $jadi;
}
?>

<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
    <div class="row mb-2">
        <div class="col-sm-12">
            <!-- <h1 class="m-0 text-dark">Judul Atas</h1> -->
        </div><!-- /.col -->
    </div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->

<!-- Main content -->
<section class="content">
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <!-- Default box -->
            <div class="card">
                <div class="card-header bg-info">
                    <h3 class="card-title">Edit Transaksi Tabungan</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                        <button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                    <style>
                        .form-control {
                            height: 30px;
                            border-radius: 5px;
                            border: 2px solid #ccc;
                            border-radius: 3px;
                            font-size: 13px;
                            background-color: white;
                            padding: 4px 10px;
                            box-sizing: border-box;
                        }
                        .btn {
                            border-radius: 5px;
                        }
                        .custom-spacing {
                            margin-bottom: 2px;
                        }
                        label {
                            font-family: 'Arial', sans-serif;
                            font-size: 12px;
                            font-weight: bold;
                            color: #333;
                            margin-bottom: 5px;
                            padding: 4px 10px;
                        }
                        .custom-input1 {
                            width: 50px;
                            margin-right: 10px;
                        }
                        .custom-input2 {
                            width: 40px;
                            margin-right: 10px;
                        }
                        .custom-input3 {
                            width: 140px;
                            margin-right: 10px;
                        }
                        .custom-input4 {
                            width: 40px;
                            margin-right: 10px;
                        }
                        .cariid {
                            width: 20px;
                        }
                    </style>

                    <?php if(!isset($_GET['no_bukti'])) { ?>
                    <!-- Search form for finding transaction to edit -->
                    <form action="home.php?home=<?php echo md5("edit_mutasitabungan"); ?>" method="POST">
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="form-group row custom-spacing">
                                    <label for="nama" class="col-sm-4">No. Rekening</label>
                                    <input type="text" name="rekening1" id="rekening1" class="form-control custom-input1" placeholder="Rekening 1" value="<?php echo $kode; ?>" onKeyDown="changeFocus(event,'rekening3')" /> <!-- readonly -->
                                    <input type="text" name="rekening3" id="rekening3" required class="form-control custom-input3" value="<?php if(isset($_POST['rekening3'])){echo sprintf("%06d",$_POST['rekening3']); }?>" onKeyDown="changeFocus(event,'rekening4')"/> 
                                    <input type="text" name="rekening4" id="rekening4" required class="form-control custom-input4" value="<?php if(isset($_POST['rekening4'])){echo sprintf("%02d",$_POST['rekening4']);} ?>" />
                                    <button type="submit" id="cariid" name="cariid" style="width:40px;"><i class="fas fa-search"></i></button>
                                </div>
                            </div>
                        </div>
                    </form>
                    <?php } ?>

                    <!-- Display transaction list for the selected account -->
                    <?php if(isset($rekening) && !isset($_GET['no_bukti'])) { ?>
                    <div class="table-responsive mt-4">
                        <h5>Transaksi Tabungan untuk Rekening: <?php echo $rekening; ?></h5>
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>No Bukti</th>
                                    <th>Tanggal</th>
                                    <th>Jenis</th>
                                    <th>Nominal</th>
                                    <th>Keterangan</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $no = 1;
                                $query = mysqli_query($koneksi, "SELECT * FROM mutasitabungan WHERE rekening='$rekening' ORDER BY tgl DESC");
                                while($row = mysqli_fetch_assoc($query)) {
                                    $nominal = ($row['kodetab'] == 'S') ? $row['kredit'] : $row['debet'];
                                    $jenis = ($row['kodetab'] == 'S') ? 'Setor' : 'Tarik';
                                ?>
                                <tr>
                                    <td><?php echo $no++; ?></td>
                                    <td><?php echo $row['no_bukti']; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['tgl'])); ?></td>
                                    <td><?php echo $jenis; ?></td>
                                    <td><?php echo number_format($nominal, 0, ',', ','); ?></td>
                                    <td><?php echo $row['keterangan']; ?></td>
                                    <td>
                                        <a href="home.php?home=<?php echo md5("edit_mutasitabungan"); ?>&no_bukti=<?php echo $row['no_bukti']; ?>" class="btn btn-sm btn-warning">Edit</a>
                                    </td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <?php } ?>

                    <!-- Edit form for a specific transaction -->
                  <!-- Edit form for a specific transaction -->
<?php if(isset($_GET['no_bukti'])) { ?>
<form name="myform" action="simpan/simpan_tabungan_edit.php" method="POST" id="form-mutasisimpanan">
    <input type="hidden" name="no_bukti" value="<?php echo $no_bukti; ?>">
    <input type="hidden" name="rekening" id="rekening" required value="<?php echo $rekening; ?>" />
    
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group row custom-spacing">
                <label for="tgl" class="col-sm-4">Tanggal</label>
                <input type="text" name="tgl" id="tgl" class="tgl form-control col-sm-8" value="<?php echo date('d-m-Y', strtotime($tgl)); ?>" required onKeyDown="changeFocus(event,'jtabungan')" />
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-4">Jenis Tabungan</label>
                <div class="custom-control custom-radio col-sm-2">
                    <input type="radio" class="custom-control-input" id="customRadio1" name="jtabungan" value="S" onKeyDown="changeFocus(event,'nominal')" <?php if($kodetab == 'S') echo 'checked'; ?> />
                    <label for="customRadio1" class="custom-control-label">Setor</label>
                </div>
                <div class="custom-control custom-radio col-sm-2">
                    <input class="custom-control-input" type="radio" id="customRadio2" name="jtabungan" value="T" onKeyDown="changeFocus(event,'nominal')" <?php if($kodetab == 'T') echo 'checked'; ?> />
                    <label for="customRadio2" class="custom-control-label">Tarik</label>
                </div>
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-4">Nominal</label>
                <input type="text" name="nominal" id="nominal" required class="form-control col-sm-8" value="<?php echo number_format($nominal, 0, '.', ','); ?>" onKeyDown="changeFocus(event,'keterangan')" /> 
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-4">Keterangan</label>
                <input type="text" name="keterangan" id="keterangan" class="form-control col-sm-8" value="<?php echo $keterangan; ?>" required onKeyDown="changeFocus(event,'update_btn')" />
            </div>
        </div>
        <div class="col-sm-6">
            <div class="form-group row custom-spacing"> 
                <label for="nama" class="col-sm-3" style="margin-left: 12px;">Nama</label> 
                <input type="text" name="nama" id="nama" class="form-control col-sm-8" readonly value="<?php echo $reg["nama"]; ?>" />
            </div> 
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3" style="margin-left: 12px;">Ibu</label> 
                <input type="text" name="kls" id="kls" class="form-control col-sm-8" readonly value="<?php echo $reg['ibu']; ?>" />
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3" style="margin-left: 12px;">Alamat</label> 
                <input type="text" name="alamat" id="alamat" class="form-control col-sm-8" readonly value="<?php echo $reg['alamat']; ?>" />
            </div> 
            <div class="form-group row"> 
                <label for="nama" class="col-sm-3" style="margin-left: 12px;">Saldo</label> 
                <input type="text" name="totalmargin" id="totalmargin" class="form-control col-sm-8" readonly value="<?php echo Rp($total['total']); ?>" />
            </div>
        </div>
    </div>
    <div class="card-footer">
        <div class="row">
            <div class="col">
                <button type="button" id="update_btn" class="btn btn-primary">Update</button>
                <a href="home.php?home=<?php echo md5("edit_mutasitabungan"); ?>" class="btn btn-secondary">Kembali</a>
            </div>
        </div>
    </div>
</form>
<?php } ?>
</div>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
<!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->

<script>
function changeFocus(event, nextFieldId) {
    if (event.key === 'Enter') {
        event.preventDefault(); // Mencegah pengiriman form saat Enter ditekan
        const nextField = document.getElementById(nextFieldId);
        if (nextField) {
            nextField.focus(); // Pindah fokus ke field berikutnya
        }
    }
}

// Format number with commas
$('#nominal').on('keyup', function() {
    var angka = $(this).val();
    var hasilAngka = formatRibuan(angka);
    $(this).val(hasilAngka);
});

function formatRibuan(angka) {
    var number_string = angka.replace(/[^\d]/g, '').toString(),
    split = number_string.split('.'),
    sisa = split[0].length % 3,
    angka_hasil = split[0].substr(0, sisa),
    ribuan = split[0].substr(sisa).match(/\d{3}/gi);

    // tambahkan titik jika yang di input sudah menjadi angka ribuan
    if (ribuan) {
        separator = sisa ? ',' : '';
        angka_hasil += separator + ribuan.join(',');
    }

    return angka_hasil;
}

// Langsung submit form saat tombol update ditekan
$(document).ready(function() {
    // Inisialisasi datepicker jika tersedia
    if($.fn.datepicker) {
        $(".tgl").datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            todayHighlight: true
        });
    }

    $("#update_btn").click(function(e) {
        e.preventDefault(); // Prevent default button behavior
        
        // Prepare nominal value - remove commas before submitting
        var nominalField = document.getElementById('nominal');
        var cleanedValue = nominalField.value.replace(/,/g, '');
        
        // Create a hidden field to store cleaned nominal value
        var hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'nominal_clean';
        hiddenInput.value = cleanedValue;
        document.getElementById('form-mutasisimpanan').appendChild(hiddenInput);
        
        // Submit form immediately without confirmation dialog
        document.getElementById('form-mutasisimpanan').submit();
    });
});
</script>