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

// Check if the form is submitted
if (isset($_POST['simpanansyahriah'])) {
   $dataTable = $_POST['dataTable'] ?? ''; 
$faktur = [
    "bulanan" => "SY",
    "iktibar" => "IK",
    "imni" => "IM",
    "imda1" => "D1",
    "imda2" => "D2",
    "imda3" => "D3",
    "seragam" => "SE",
    "kitab" => "KI",
    "alquran" => "AQ",
    "iuran" => "IU"
];
 /* $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",
    "alquran" => "4.400.29",
    "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"
];

$nama_nonSyahriah = [
    "bulanan" => "SYAHRIAH",
    "iktibar" => "IKTIBAR",
    "imni" => "IMNI",
    "imda1" => "IMDA-I",
    "imda2" => "IMDA-II",
    "imda3" => "IMDA-III",
    "alquran" => "AL QURAN",
    "seragam" => "SERAGAM",
    "kitab" => "KITAB",
    "iuran" => "IURAN"
];
$rekeningBayar = $rekening[$dataTable] ?? null;

// Menggunakan isset untuk memastikan bahwa $no_bukti ada dalam array $faktur.

    $no_bukti = $faktur[$dataTable].$_SESSION['nokode'].date("YmdHis");
    $username = $_SESSION['username'];
    $kode = $_SESSION['kode'];
    $id = $_POST['idM'];
    $nim = $_POST['nim'];
    $tglmasehi = date('Y-m-d', strtotime($_POST['tgl']));
    $tgl = date('Y-m-d');
    $bayar = str_replace(",", "", $_POST['bayar']);
    $keterangan = ($_POST['keterangan'] ?? '') . ($_POST['keterangan2'] ?? ''); // Ensure both exist
    $kelas = $_POST['kelas'] ?? ''; // Default to empty if not set
    $tahun = $_POST['tahun'] ?? ''; // Default to empty if not set
    $kewajiban = 0;
    //$kewajiban = str_replace(",", "", $_POST['kewajiban'] ?? 0); // Default to 0 if not set
    $sisa   = str_replace(",", "", $_POST['kewajiban'])-$bayar;
    $tglnow = date("Y-m-d H:i:s");
    $thnArab = $_POST['thnArab'] ?? ''; 

    // 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'];
    $nama = $pesan['nama'];
    $penErima = $pesan['nama'];
    $bayarWa =  $_POST['bayar'];
    $sisaKewajiban =number_format($pesan['sisaKewajiban'],0);
    $kewajiban = number_format($pesan['kewajiban'],0);
    $judul = "*MMU A-39 REJOSARI*";
    $tglpsn = $tgl;                
    // Set payment method
    $metodebayar = strtoupper($nama_nonSyahriah[$dataTable] ?? null);
    //$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=d180bfac75dc4d69e954b823b33a3521';</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=d180bfac75dc4d69e954b823b33a3521';</script>";
        exit;
    }
    if ($sisa < 0) {
        echo "<script>alert('Kewajiban sudah lunas/Kelebihan Bayar.');</script>";
        echo "<script>window.location='../home.php?home=d180bfac75dc4d69e954b823b33a3521';</script>";
        exit;
    }

    // Continue with the insertion
    $query1 = mysqli_query($koneksi, "INSERT INTO $dataTable SET id='$id',nim='$nim', no_bukti='$no_bukti',tglmasehi='$tglmasehi', tgl='$tgl',no_kls='$kelas',tahun='$thnArab', kewajiban='0', bayar='$bayar',keterangan='$keterangan', username='$username'") or die(mysqli_error($koneksi));
    
   // Insert message into the database
    $waTagihan = mysqli_query($koneksi, "INSERT INTO message SET number='$nohp',tgl='$tglmasehi',judul='$judul', penErima='$penErima', PenGirim='$kantor', rekening='$nim',kewajiban='$kewajiban',sisaKewajiban='$sisaKewajiban', nominal='$bayarWa', keterangan='$keteranganpesan', metodeBayar='$metodebayar',kodeFilTer='NonSyahriah' ") or die(mysqli_error($koneksi));
    $DeleteWA = mysqli_query($koneksi, "DELETE FROM message WHERE status='1' ") or die(mysqli_error($koneksi));
    // Insert first entry to bukubesar
    $query_bukubesar1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET no_bukti='$no_bukti', tanggal='$tglmasehi', kode_akun='1.100.10', debet='$bayar', 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='$tglmasehi', kode_akun='$rekeningBayar', debet='0', kredit='$bayar', 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=d180bfac75dc4d69e954b823b33a3521';</script>";
        exit;
    }

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

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