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

$kode = $_SESSION['kode'];

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

    // Verify dataTable name to prevent SQL injection
    $validTables = ['bulanan', 'seragam', 'kitab', 'imda1', 'imda2', 'imda3', 'iuran', 'imni', 'ikhtibar'];
    if(!in_array($dataTable, $validTables)) {
        echo "<script>alert('Tabel tidak valid!'); window.location='home.php?home=".md5("angsuran")."';</script>";
        exit;
    }

    // Fetch transaction data from the selected table
    $query = mysqli_query($koneksi, "SELECT id, tglmasehi as tgl, no_kls as kls, kewajiban, bayar, keterangan, username 
                                     FROM $dataTable WHERE no_bukti='$no_bukti'");
    $data = mysqli_fetch_assoc($query);

    if($data) {
        $id = $data['id'];
        $tgl = $data['tgl'];
        $kls = $data['kls'];
        $kewajiban = $data['kewajiban'];
        $bayar = $data['bayar'];
        $nominal = ($bayar == '0') ? $kewajiban : $bayar;
        $keterangan = $data['keterangan'];
        $is_payment = ($bayar > 0) ? true : false;
        
        // Get rekening parts
        $rekening_parts = explode('.', $id);
        $rekening1 = $rekening_parts[0];
        $rekening3 = isset($rekening_parts[1]) ? substr($rekening_parts[1], 0, 6) : '';
        
        // Fetch registrant data
        $register = $rekening1.".".sprintf("%06d",$rekening3);
         $reg = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT b.tgl, a.nama, a.alamat, a.ibu, b.kewajiban, b.bayar, 
                                                     (b.kewajiban-b.bayar) as sisa, a.nim, b.no_kls AS kls 
                                                     FROM registrasi a LEFT JOIN $dataTable b ON a.id=b.id WHERE a.id='".$register."' GROUP BY b.id"));
        if(!$reg) {
            $reg = array('nama' => '', 'alamat' => '', 'ibu' => '', 'kewajiban' => 0, 'bayar' => 0, 'sisa' => 0, 'nim' => '', 'kls' => '');
        }
    } else {
        echo "<script>alert('Data tidak ditemukan!'); window.location='home.php?home=".md5("angsuran")."';</script>";
        exit;
    }
} elseif(isset($_POST['rekening3']) && isset($_POST['dataTable'])) {
    $rekening1 = mysqli_real_escape_string($koneksi, $_POST['rekening1']); 
    $rekening3 = mysqli_real_escape_string($koneksi, $_POST['rekening3']);
    $rekening4 = isset($_POST['rekening4']) ? mysqli_real_escape_string($koneksi, $_POST['rekening4']) : '';
    $dataTable = mysqli_real_escape_string($koneksi, $_POST['dataTable']);
    
    // Verify dataTable name to prevent SQL injection
    $validTables = ['bulanan', 'seragam', 'kitab', 'imda1', 'imda2', 'imda3', 'iuran', 'imni', 'ikhtibar'];
    if(!in_array($dataTable, $validTables)) {
        echo "<script>alert('Tabel tidak valid!'); window.location='home.php?home=".md5("angsuran")."';</script>";
        exit;
    }
    
    // Construct rekening ID
    $register = $rekening1.".".sprintf("%06d",$rekening3);
    
    // Fetch registrant data
    $reg = mysqli_fetch_assoc(mysqli_query($koneksi,"SELECT b.tgl, a.nama, a.alamat, a.ibu, b.kewajiban, b.bayar, 
                                                     (b.kewajiban-b.bayar) as sisa, a.nim, b.no_kls AS kls 
                                                     FROM registrasi a LEFT JOIN $dataTable b ON a.id=b.id WHERE a.id='".$register."' GROUP BY b.id"));
    if(!$reg) {
        $reg = array('nama' => '', 'alamat' => '', 'ibu' => '', 'kewajiban' => 0, 'bayar' => 0, 'sisa' => 0, 'nim' => '', 'kls' => '');
    }
}

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 Kewajiban</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_tagihansyahriah"); ?>" method="POST">
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="form-group row custom-spacing">
                                        <label for="dataTable" class="col-sm-4">Kewajiban</label>
                                        <select id="dataTable" name="dataTable" class="form-control col-sm-6 select2" onkeydown="changeFocus(event,'rekening3')" required>
                                            <option value="">PILIH----</option>
                                            <option value="bulanan" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'bulanan') ? 'selected' : ''; ?>>Syahriah</option>
                                            <option value="seragam" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'seragam') ? 'selected' : ''; ?>>Seragam</option>
                                            <option value="kitab" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'kitab') ? 'selected' : ''; ?>>Kitab</option>
                                            <option value="imda1" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'imda1') ? 'selected' : ''; ?>>Imda-I</option>
                                            <option value="imda2" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'imda2') ? 'selected' : ''; ?>>Imda-II</option>
                                            <option value="imda3" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'imda3') ? 'selected' : ''; ?>>Imda-III</option>
                                            <option value="iuran" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'iuran') ? 'selected' : ''; ?>>Iuran Maulid</option>
                                            <option value="imni" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'imni') ? 'selected' : ''; ?>>Imni</option>
                                            <option value="ikhtibar" <?php echo (isset($_POST['dataTable']) && $_POST['dataTable'] == 'ikhtibar') ? 'selected' : ''; ?>>Iktibar</option>
                                        </select>
                                    </div>
                                    <div class="form-group row custom-spacing">
                                        <label for="rekening1" 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" placeholder="Rekening 3" value="<?php if(isset($_POST['rekening3'])){echo sprintf("%06d",$_POST['rekening3']); }?>" onKeyDown="changeFocus(event,'cariid')"/> 
                                       
                                        <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($register) && !isset($_GET['no_bukti']) && isset($dataTable)) { ?>
                        <div class="table-responsive mt-4">
                            <h5>Transaksi untuk Rekening: <?php echo htmlspecialchars($register); ?></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 $dataTable WHERE id='$register' ORDER BY tglmasehi DESC");
                                    if(mysqli_num_rows($query) > 0) {
                                        while($row = mysqli_fetch_assoc($query)) {
                                            $nominal = ($row['bayar'] == '0') ? $row['kewajiban'] : $row['bayar'];
                                            $jenis = ($row['bayar'] == '0') ? 'Tagihan' : 'Bayar';
                                    ?>
                                    <tr>
                                        <td><?php echo $no++; ?></td>
                                        <td><?php echo htmlspecialchars($row['no_bukti']); ?></td>
                                        <td><?php echo date('d-m-Y', strtotime($row['tglmasehi'])); ?></td>
                                        <td><?php echo $jenis; ?></td>
                                        <td><?php echo number_format($nominal, 0, '.', ','); ?></td>
                                        <td><?php echo htmlspecialchars($row['keterangan']); ?></td>
                                        <td>
                                            <a href="home.php?home=<?php echo md5("edit_tagihansyahriah"); ?>&no_bukti=<?php echo urlencode($row['no_bukti']); ?>&dataTable=<?php echo urlencode($dataTable); ?>" class="btn btn-sm btn-warning">Edit</a>
                                        </td>
                                    </tr>
                                    <?php 
                                        }
                                    } else {
                                        echo '<tr><td colspan="7" class="text-center">Tidak ada data transaksi</td></tr>';
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <?php } ?>

                        <!-- Edit form for a specific transaction -->
                        <?php if(isset($_GET['no_bukti'])) { ?>
                        <form name="myform" action="simpan/simpan_bayar_syahriah_murid_edit.php" method="POST" id="form-tagihansyahriah">
                            <input type="hidden" name="no_bukti" value="<?php echo htmlspecialchars($no_bukti); ?>">
                            <input type="hidden" name="dataTable" value="<?php echo htmlspecialchars($dataTable); ?>">
                            <input type="hidden" name="register" value="<?php echo htmlspecialchars($register); ?>" />
                            <input type="hidden" name="is_payment" value="<?php echo $is_payment ? '1' : '0'; ?>" />
                            
                            <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,'nominal')" />
                                    </div>
                                   
                                    <div class="form-group row custom-spacing">
                                        <label for="nominal" 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="keterangan" class="col-sm-4">Keterangan</label>
                                        <input type="text" name="keterangan" id="keterangan" class="form-control col-sm-8" value="<?php echo htmlspecialchars($keterangan); ?>" required onKeyDown="changeFocus(event,'update_btn')" />
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group row custom-spacing"> 
                                        <label for="nama_santri" class="col-sm-3" style="margin-left: 12px;">Nama</label> 
                                        <input type="text" name="nama_santri" id="nama_santri" class="form-control col-sm-8" readonly value="<?php echo htmlspecialchars($reg['nama']); ?>" />
                                    </div> 
                                    <div class="form-group row custom-spacing">
                                        <label for="ibu" class="col-sm-3" style="margin-left: 12px;">Ibu</label> 
                                        <input type="text" name="ibu" id="ibu" class="form-control col-sm-8" readonly value="<?php echo htmlspecialchars($reg['ibu']); ?>" />
                                    </div>
                                    <div class="form-group row custom-spacing">
                                        <label for="alamat_santri" class="col-sm-3" style="margin-left: 12px;">Alamat</label> 
                                        <input type="text" name="alamat_santri" id="alamat_santri" class="form-control col-sm-8" readonly value="<?php echo htmlspecialchars($reg['alamat']); ?>" />
                                    </div> 
                                    
                                    <div class="form-group row custom-spacing"> 
                                        <label for="kewajiban_val" class="col-sm-3" style="margin-left: 12px;">Kwajiban</label> 
                                        <input type="text" name="kewajiban_val" id="kewajiban_val" class="form-control col-sm-8" readonly value="<?php echo number_format($reg['kewajiban'], 0); ?>" />
                                    </div> 
                                    <input type="hidden" name="nim" id="nim" class="form-control col-sm-7" value="<?php echo htmlspecialchars($reg['nim']); ?>"/>
                                    <div class="form-group row custom-spacing"> 
                                        <label for="bayarpokok" class="col-sm-3" style="margin-left: 12px;">Terbayar</label> 
                                        <input type="text" name="bayarpokok" id="bayarpokok" class="form-control col-sm-8" readonly value="<?php echo Rp($reg['bayar']); ?>"/>
                                    </div>

                                    <div class="form-group row custom-spacing"> 
                                        <label for="sisa" class="col-sm-3" style="margin-left: 12px;">Sisa</label> 
                                        <input type="text" name="sisa" id="sisa" class="form-control col-sm-8" readonly value="<?php echo Rp($reg['sisa']); ?>"/>
                                    </div>

                                    <div class="form-group row custom-spacing"> 
                                        <label for="kelas" class="col-sm-3" style="margin-left: 12px;">Kelas</label> 
                                        <input type="text" name="kelas" id="kelas" class="form-control col-sm-8" readonly value="<?php echo htmlspecialchars($reg['kls']); ?>"/>
                                    </div>
                                </div>
                            </div>
                            <div class="card-footer">
                                <div class="row">
                                    <div class="col">
                                        <button type="submit" id="update_btn" class="btn btn-primary">Update</button>
                                        <a href="home.php?home=<?php echo md5("edit_tagihansyahriah"); ?>" 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;
}

// Form submission handler
$(document).ready(function() {
    // Inisialisasi datepicker jika tersedia
    if($.fn.datepicker) {
        $(".tgl").datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            todayHighlight: true
        });
    }

    // Process form submission to clean up data
    $("#form-tagihansyahriah").on('submit', function(e) {
        // Get nominal value and clean it
        var nominalValue = $("#nominal").val();
        var cleanedNominal = nominalValue.replace(/,/g, '');
        
        // Create hidden field with cleaned value
        $('<input>').attr({
            type: 'hidden',
            name: 'nominal_clean',
            value: cleanedNominal
        }).appendTo('#form-tagihansyahriah');
        
        // Continue with form submission
        return true;
    });
});
</script>