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

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit;
}

// Check if the form is submitted
if (isset($_POST['simpanansyahriah'])) {
    // Define constants and lookup arrays
    $dataTable = "bulanan"; // Define the data table
    $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"
    ];

    // Validate table exists in our defined arrays
    if (!isset($rekening[$dataTable]) || !isset($faktur[$dataTable])) {
        echo "<script>alert('Data tabel tidak valid.'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    }

    $rekeningBayar = $rekening[$dataTable];
    
    // Ensure required POST data exists
    if (!isset($_POST['byr_ke2']) || !isset($_POST['idM2']) || !is_array($_POST['byr_ke2']) || !is_array($_POST['idM2'])) {
        echo "<script>alert('Data tidak lengkap.'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        exit;
    }
    
    $checked_array = $_POST['idM2'];
    $success_count = 0;
    $error_count = 0;

    // Begin transaction
    mysqli_begin_transaction($koneksi);
    
    try {
        foreach ($_POST['idM2'] as $key => $value) {
            if (in_array($_POST['idM2'][$key], $checked_array)) {
                // Sanitize and validate inputs
                $id = mysqli_real_escape_string($koneksi, $_POST['idM2'][$key]);
                
                // Validate ID length
                if (strlen($id) !== 10) {
                    throw new Exception("ID yang diinput salah! Cek ulang.");
                }
                
                $nim = mysqli_real_escape_string($koneksi, $_POST['nim2'][$key]);
                $no_bukti = $faktur[$dataTable] . (isset($_SESSION['nokode']) ? $_SESSION['nokode'] : "") . date("YmdHis") . sprintf("%03d", $key);
                
                // Validate date format
                if (!isset($_POST['tgl']) || !strtotime($_POST['tgl'])) {
                    throw new Exception("Format tanggal tidak valid.");
                }
                
                $tglmasehi = date('Y-m-d', strtotime($_POST['tgl']));
                
                // Numeric validations
                if (!isset($_POST['bayar2'][$key]) || !isset($_POST['bayar']) || !isset($_POST['kewajiban']) || !isset($_POST['bayarpokok'])) {
                    throw new Exception("Data pembayaran tidak lengkap.");
                }

                $bayar2 = str_replace(",", "", $_POST['bayar2'][$key]);
                if (!is_numeric($bayar2)) {
                    throw new Exception("Nilai pembayaran tidak valid.");
                }
                
                // Additional field validations
                if (!isset($_POST['bulan2'][$key]) || !isset($_POST['kelas2'][$key]) || !isset($_POST['tahun2'][$key])) {
                    throw new Exception("Data periode pembayaran tidak lengkap.");
                }
                
                $bulan = mysqli_real_escape_string($koneksi, $_POST['bulan2'][$key]);
                $kls = mysqli_real_escape_string($koneksi, $_POST['kelas2'][$key]);
                $byr_ke = mysqli_real_escape_string($koneksi, $_POST['byr_ke2'][$key]);
                $tahun = mysqli_real_escape_string($koneksi, $_POST['tahun2'][$key]);
                $username = $_SESSION['username'];
                
                // Combine and sanitize keterangan
                $keterangan = '';
                if (isset($_POST['keterangan'])) {
                    $keterangan .= mysqli_real_escape_string($koneksi, $_POST['keterangan']);
                }
                if (isset($_POST['keterangan2'])) {
                    $keterangan .= mysqli_real_escape_string($koneksi, $_POST['keterangan2']);
                }

                // Handling values
                $tgl = date('Y-m-d');
                $bayar = str_replace(",", "", $_POST['bayar']);
                $kewajibanWa = str_replace(",", "", $_POST['kewajiban']);
                $terbayar = str_replace(",", "", $_POST['bayarpokok']);
                $kewajiban= 0;
                
                // Validate numeric values after parsing
                if (!is_numeric($bayar) || !is_numeric($kewajibanWa) || !is_numeric($terbayar)) {
                    throw new Exception("Nilai keuangan tidak valid.");
                }
                
                $sisa = $kewajibanWa - ($terbayar + $bayar);
                $tglnow = date("Y-m-d H:i:s");

                // Check if transaction already exists
                $check_query = "SELECT no_bukti FROM $dataTable WHERE no_bukti = ?";
                $check_stmt = $koneksi->prepare($check_query);
                $check_stmt->bind_param("s", $no_bukti);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    throw new Exception("Transaksi sudah ada untuk rekening ini.");
                }
                $check_stmt->close();
                
                if ($sisa < 0) {
                    throw new Exception("Kewajiban sudah lunas/Kelebihan Bayar.");
                }

                // Retrieve registrant data with prepared statement
                $query_pesan = "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 = ?
                               GROUP BY a.nama, a.wali, a.nohp, b.keterangan";
                               
                $stmt_pesan = $koneksi->prepare($query_pesan);
                $stmt_pesan->bind_param("s", $id);
                $stmt_pesan->execute();
                $result_pesan = $stmt_pesan->get_result();
                $pesan = $result_pesan->fetch_assoc();
                $stmt_pesan->close();
                
                // Check if data is found
                if (!$pesan) {
                    throw new Exception("Data siswa tidak ditemukan.");
                }

                $nohp = $pesan['nohp'];
                $penErima = $pesan['nama'];
                $sisaKewajiban = ($terbayar + $bayar) - $kewajibanWa;
                $judul = "*MMU A-39 REJOSARI*";
                $metodebayar = 'SYAHRIAH';
                $kantor = "*MMU A-39*";
                $keteranganpesan = trim(preg_replace('/104.*$/', '', $keterangan));

                // Insert into main data table with prepared statement
                $insert_query = "INSERT INTO $dataTable (no, id, nim, no_bukti, tglmasehi, tgl, no_kls, tahun, bulan, byr_ke, kewajiban, bayar, keterangan, username) 
                                VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                                
                $stmt = $koneksi->prepare($insert_query);
                $stmt->bind_param("sssssssssddss", 
                    $id, $nim, $no_bukti, $tglmasehi, $tgl, $kls, $tahun, $bulan, $byr_ke, 
                    $kewajiban, $bayar2, $keterangan, $username);
                
                if (!$stmt->execute()) {
                    throw new Exception("Gagal menyimpan data pembayaran: " . $stmt->error);
                }
                $stmt->close();

                // Insert message with prepared statement
                $insert_message = "INSERT INTO message (number, tgl, judul, penErima, PenGirim, rekening, kewajiban, sisaKewajiban, nominal, keterangan, metodeBayar, kodeFilTer) 
                                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'bayar')";
                                  
                $stmt_message = $koneksi->prepare($insert_message);
                $stmt_message->bind_param("sssssdddsss", 
                    $nohp, $tglmasehi, $judul, $penErima, $kantor, $nim, $kewajibanWa, 
                    $sisaKewajiban, $bayar, $keteranganpesan, $metodebayar);
                
                if (!$stmt_message->execute()) {
                    throw new Exception("Gagal menyimpan pesan: " . $stmt_message->error);
                }
                $stmt_message->close();

                // Delete old messages with prepared statement
                $delete_wa = "DELETE FROM message WHERE status='1'";
                $stmt_delete = $koneksi->prepare($delete_wa);
                if (!$stmt_delete->execute()) {
                    throw new Exception("Gagal menghapus pesan lama: " . $stmt_delete->error);
                }
                $stmt_delete->close();

                // Insert entry into bukubesar with prepared statement - Debit entry
                $insert_bukubesar1 = "INSERT INTO bukubesar (no_bukti, tanggal, kode_akun, debet, kredit, keterangan, tglsystem, username) 
                                     VALUES (?, ?, '1.100.10', ?, 0, ?, ?, ?)";
                                     
                $stmt_buku1 = $koneksi->prepare($insert_bukubesar1);
                $stmt_buku1->bind_param("ssdsss", 
                    $no_bukti, $tglmasehi, $bayar, $keteranganpesan, $tglnow, $username);
                
                if (!$stmt_buku1->execute()) {
                    throw new Exception("Gagal menyimpan buku besar (debit): " . $stmt_buku1->error);
                }
                $stmt_buku1->close();

                // Insert second entry into bukubesar - Credit entry
                $insert_bukubesar2 = "INSERT INTO bukubesar (no_bukti, tanggal, kode_akun, debet, kredit, keterangan, tglsystem, username) 
                                     VALUES (?, ?, ?, 0, ?, ?, ?, ?)";
                                     
                $stmt_buku2 = $koneksi->prepare($insert_bukubesar2);
                $stmt_buku2->bind_param("sssdsss", 
                    $no_bukti, $tglmasehi, $rekeningBayar, $bayar, $keteranganpesan, $tglnow, $username);
                
                if (!$stmt_buku2->execute()) {
                    throw new Exception("Gagal menyimpan buku besar (kredit): " . $stmt_buku2->error);
                }
                $stmt_buku2->close();

                $success_count++;
            }
        }
        
        // If we got here without exceptions, commit the transaction
        mysqli_commit($koneksi);
        
        if ($success_count > 0) {
            echo "<script>alert('Pembayaran Tagihan berhasil untuk $success_count data'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        } else {
            echo "<script>alert('Tidak ada data yang diproses.'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
        }
        
    } catch (Exception $e) {
        // Rollback transaction on error
        mysqli_rollback($koneksi);
        echo "<script>alert('Error: " . addslashes($e->getMessage()) . "'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
    }
    
} else {
    echo "<script>alert('Formulir belum disubmit.'); window.location='../home.php?home=46c4dc315e6c38dfc82768982a5791bb';</script>";
}
?>