<?php  
session_start();
include './../koneksi.php'; 
include './../cek_login.php';    
ini_set('display_errors', 1);
error_reporting(E_ALL);
      
if (isset($_POST['id'])) {
    
    $checked_array = $_POST['no'];
    $dataTable = "bulanan";
    
    function faktur($kodefaktur) {
        switch ($kodefaktur) {
            case "bulanan": return "SY";
            case "iktibar": return "IK";
            case "imni": return "IM";
            case "imda1": return "D1";
            case "imda2": return "D2";
            case "imda3": return "D3";
            case "seragam": return "SE";
            case "kitab": return "KI";
            case "iuran": return "IU";
            default: return ""; // Default case
        }
    }

    foreach ($_POST['id'] as $key => $value) {
        if (in_array($_POST['id'][$key], $checked_array)) {
            $id = $_POST['id'][$key];
            $nim = $_POST['nim'][$key];
            $no_bukti = faktur($dataTable) . $_SESSION['nokode'] . date("YmdHis") . sprintf("%03d", $key);
            $tglmasehi = $_POST['tglmasehi'][$key];
            //$bulan = date('m', strtotime($tglmasehi));
            $bulan = $_POST['bulan'];
            $tgl = date('Y-m-d');
            $kls = $_POST['kls'][$key];
            $tahun = $_POST['tahun'][$key];
            $kewajiban = str_replace(",", "", $_POST['kewajiban'][$key]);
            $username = $_SESSION['username'];
            $keterangan = "Tagihan " . $dataTable;
            $bayar = 0;

            // Use prepared statements to prevent SQL injection
            $stmt = $koneksi->prepare("INSERT INTO $dataTable (no, id, nim, no_bukti, tglmasehi, tgl, no_kls, tahun, bulan, kewajiban, bayar, keterangan, username, koreksi) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            if ($stmt) {
                $stmt->bind_param("sssssssssssss", $id, $nim, $no_bukti, $tglmasehi, $tgl, $kls, $tahun, $bulan, $kewajiban, $bayar, $keterangan, $username, $username);
                
                if ($stmt->execute()) {
                    echo "Data Berhasil Disimpan<br>";
                    
                    // Update registrasi
                    $updateKls = mysqli_query($koneksi, "UPDATE registrasi SET klsNow='$kls' WHERE id='$id'") or die(mysqli_error($koneksi));
                } else {
                    echo "Error executing statement: " . $stmt->error . "<br>";
                }
                // Close the statement
                $stmt->close();    
            } else {
                die('Error preparing statement: ' . mysqli_error($koneksi));
            }
        }
    }
}
?>
