<?php
session_start();
//error_reporting(0);
include('../koneksi.php');

// Check if the form is submitted
if (isset($_POST['simpanansyahriah'])) {
   $dataTable = "bulanan" ?? ''; 
$faktur = [
    "bulanan" => "BS",
    "iktibar" => "BR",
    "imni" => "BI",
    "imda1" => "B1",
    "imda2" => "B2",
    "imda3" => "B3",
    "seragam" => "BG",
    "kitab" => "BK",
    "iuran" => "BN"
];
 
$rekening = [
    "bulanan" => "4.400.20",
    "iktibar" => "4.400.28",
    "imni" => "4.400.27",
    "imda1" => "4.400.22",
    "imda2" => "4.400.23",
    "imda3" => "4.400.24",
    "seragam" => "4.400.26",
    "kitab" => "4.400.21",
    "iuran" => "4.400.25"
];
$rekeningBayar = $rekening[$dataTable] ?? null;

// Menggunakan isset untuk memastikan bahwa $no_bukti ada dalam array $faktur.
$checked_array = $_POST['idM2'];
    foreach ($_POST['idM2'] as $key => $value) {
        if (in_array($_POST['idM2'][$key], $checked_array)) {
            $id = $_POST['idM2'][$key];
            $nim = $_POST['nim2'][$key];
            $no_bukti = $faktur[$dataTable] . (isset($_SESSION['nokode']) ? $_SESSION['nokode'] : "") . date("YmdHis") . sprintf("%03d", $key);
            $tglmasehi2 = $_POST['tglmasehi2'][$key];
            $bayar2 = str_replace(",", "", $_POST['bayar2'])[$key];
            $bulan = $_POST['bulan2'][$key];
            $tgl = date('Y-m-d');
            $kls2 = $_POST['kelas2'][$key];
            $byr_ke2 = $_POST['byr_ke2'][$key];
            $tahun = $_POST['tahun2'][$key];
            $kewajiban = 0;
            $thnArab = $_POST['thnArab2'][$key]; 
            $username = $_SESSION['username'];
            $keterangan = ($_POST['keterangan'] ?? '') . ($_POST['keterangan2'] ?? '');


    $username = $_SESSION['username'];
    $kode = $_SESSION['kode'];
    $tgl = date('Y-m-d');
     $tglmasehi = $_POST['tglmasehi'];
    $bayar = str_replace(",", "", $_POST['bayar']);
     // Ensure both exist
    $kelas = $_POST['kelas'] ?? ''; // Default to empty if not set
    $tahun = $_POST['tahun'] ?? ''; // Default to empty if not set
    $kewajiban = 0;
    $kewajibanWa = str_replace(",", "",$_POST['kewajiban']);
    $terbayar = str_replace(",", "", $_POST['bayarpokok']);
    $sisa   = str_replace(",", "", $_POST['kewajiban'])-$bayar;
    $tglnow = date("Y-m-d H:i:s");
    

    // Retrieve registrant data
//$register = substr($rekening, 0, 10);
$pesan = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT a.nama AS nama,a.wali AS wali, a.nohp AS nohp, SUM(b.kewajiban) AS kewajiban,sum(b.kewajiban-b.bayar) AS sisaKewajiban,b.keterangan as keterangan FROM registrasi a LEFT JOIN  $dataTable b ON a.id=b.id WHERE b.id='$id'"));
    $nohp = $pesan['nohp'];
    $penErima = $pesan['nama'];
    $sisaKewajiban =($terbayar+$bayar)-$kewajibanWa;
    $kewajiban = $kewajibanWa;
    $judul = "*MMU A-39 REJOSARI*";
    $tglpsn = $tgl;                
    // Set payment method
    $metodebayar = 'SYAHRIAH';
    //$jmlangsuran = number_format($jumlah, 0);
    $kantor = "*MMU A-39*";
    //$rekeningpesan = $rekening;
    $ket2 = $keterangan;
    $hasilket = preg_replace('/104.*$/', '', $ket2);
    $keteranganpesan = trim($hasilket);

$rekBank =  '105';
$nameBank = 'bca';
$waCenter = '082245392496';
// Wa

    
    // Validate rekening length
    /*if (strlen($_POST['idM']) !== 10) {
        echo "<script>alert('ID yang diinput salah...! Cek ulang');</script>";
        echo "<script>window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    } */   
        
    // Check if the transaction already exists
    $check_querya = mysqli_query($koneksi, "SELECT no_bukti FROM $dataTable WHERE no_bukti='$no_bukti'");
   
    
    if (mysqli_num_rows($check_querya) > 0) {
        echo "<script>alert('Transaksi sudah ada untuk rekening ini.');</script>";
        echo "<script>window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    }
    if ($sisa < 0) {
        echo "<script>alert('Kewajiban sudah lunas/Kelebihan Bayar.');</script>";
        echo "<script>window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    }

    
    // Continue with the insertion
    $query1 = mysqli_query($koneksi, "INSERT INTO $dataTable SET id='$id',nim='$nim', no_bukti='$no_bukti',tglmasehi='$tglmasehi2', tgl='$tgl',no_kls='$kls2',tahun='$thnArab',bulan='$bulan',byr_ke='$byr_ke2', kewajiban='0', bayar='$bayar2',keterangan='$keterangan', username='$username'") or die(mysqli_error($koneksi));
    
   
    // Insert first entry to bukubesar
    $query_bukubesar1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET no_bukti='$no_bukti', tanggal='$tglmasehi2', kode_akun='1.100.10', debet='$bayar2', kredit='0', keterangan='$keterangan', kode='$kode', tglsystem='$tglnow', username='$username'") or die(mysqli_error($koneksi));

    // Insert second entry to bukubesar with the rekeningBayar
    if ($rekeningBayar) {
        $query_bukubesar2 = mysqli_query($koneksi, "INSERT INTO bukubesar SET no_bukti='$no_bukti', tanggal='$tglmasehi2', kode_akun='$rekeningBayar', debet='0', kredit='$bayar2', keterangan='$keterangan', kode='$kode', tglsystem='$tglnow', username='$username'") or die(mysqli_error($koneksi));
    } else {
        echo "<script>alert('Rekening tidak valid.'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    }

    // Success message and redirection
    echo "<script>alert('Pembayaran Tagihan berhasil'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
              
        // Success message and redirection
        echo "<script>alert('Pembayaran Tagihan berhasil');</script>";
        echo "<script>window.location = '../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";

} else {
    echo "<script>alert('Tombol belum diklik');</script>"; 
    echo "<script>window.location = '../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>"; 
}

}
}

// Insert message into the database
    $waTagihan = mysqli_query($koneksi, "INSERT INTO message SET number='$nohp',tgl='$tglmasehi2',judul='$judul', penErima='$penErima', PenGirim='$kantor', rekening='$nim',kewajiban='$kewajiban',sisaKewajiban='$sisaKewajiban', nominal='$bayar', keterangan='$keteranganpesan', metodeBayar='$metodebayar',kodeFilTer='bayar' ") or die(mysqli_error($koneksi));
    $WaDelete = mysqli_query($koneksi, "DELETE FROM message WHERE status = '1' OR status = '2' ") or die(mysqli_error($koneksi));
?>