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

// Get the current session data
$username     = $_SESSION['username'];
$kode         = $_SESSION['kode'];

// Get form data
$no_bukti     = $_POST['no_bukti'];
$dataTable    = $_POST['dataTable'];
$register     = $_POST['register'];
$tgl          = date('Y-m-d', strtotime($_POST['tgl']));

// Use cleaned nominal if available, otherwise clean it here
if(isset($_POST['nominal_clean'])) {
    $nominal = $_POST['nominal_clean'];
} else {
    $nominal = str_replace(",", "", $_POST['nominal']);
}

$keterangan   = $_POST['keterangan'];

// First, get the original data to compare changes
$original = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM $dataTable WHERE no_bukti='$no_bukti'"));

// Check if record exists
if (!$original) {
    echo "<script type='text/javascript'>
        alert('Data tidak ditemukan!');
        window.location = '../home.php?home=".md5("edit_tagihansyahriah")."';
    </script>";
    exit;
}

// Get the transaction type (tagihan or pembayaran)
$is_payment = ($original['bayar'] > 0);

// Validate required fields
if (empty($register) || empty($tgl) || empty($nominal) || empty($keterangan)) {
    echo "<script type='text/javascript'>
        alert('Data Masih ada yang kosong...!');
        window.location = '../home.php?home=" . md5("edit_tagihansyahriah") . "';
    </script>";
    exit;
}

// Check account limits if necessary
$check_account = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT id, SUM(kewajiban-bayar) as sisa FROM $dataTable WHERE id = '$register' GROUP BY id"));

if ($check_account && $check_account['sisa'] <= 0 && !$is_payment) {
    echo "<script type='text/javascript'>
        alert('Tagihan Sudah Lunas...!');
        window.location = '../home.php?home=" . md5("edit_tagihansyahriah") . "';
    </script>";
    exit;
}

// Begin transaction for data consistency
mysqli_begin_transaction($koneksi);

try {
    // Update transaction in the specific table selected
    if ($is_payment) {
        // This is a payment record - update the bayar field
        $query = mysqli_query($koneksi, "UPDATE $dataTable SET 
            tglmasehi='$tgl',
            bayar='$nominal',
            keterangan='$keterangan',
            username='$username' 
            WHERE no_bukti='$no_bukti'");
        
        //WA 
        /* $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='$register' "));
    $nohp = $pesan['nohp'];
    $penErima = $pesan['nama'];
    $sisaKewajiban =($terbayar+$bayar)-$kewajibanWa;
    $kewajiban = $kewajibanWa;
    $judul = "*MMU A-39 REJOSARI*";
    $tglpsn = $tgl;                
    $metodebayar = 'SYAHRIAH';
    $kantor = "*MMU A-39*";
    $ket2 = $keterangan;
    $hasilket = preg_replace('/104.*$/', '', $ket2);
    $keteranganpesan = trim($hasilket);

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

$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='editBayar' ") or die(mysqli_error($koneksi));
 */

    } else {
        // This is a charge record - update the kewajiban field
        $query = mysqli_query($koneksi, "UPDATE $dataTable SET 
            tglmasehi='$tgl',
            kewajiban='$nominal',
            keterangan='$keterangan',
            username='$username' 
            WHERE no_bukti='$no_bukti'");
    }
            
    if (!$query) {
        throw new Exception(mysqli_error($koneksi));
    }
    
    // Update bukubesar entries - this depends on your accounting structure
    // First, delete existing entries for this transaction
    mysqli_query($koneksi, "DELETE FROM bukubesar WHERE no_bukti='$no_bukti'");
    
    // Determine the appropriate account codes based on the table/transaction type
    switch ($dataTable) {
        case 'bulanan':
            $debit_account = '1.100.10'; // Kas
            $credit_account = '4.100.10'; // Pendapatan Syahriah
            break;
        case 'seragam':
            $debit_account = '1.100.10'; // Kas
            $credit_account = '4.100.20'; // Pendapatan Seragam
            break;
        case 'kitab':
            $debit_account = '1.100.10'; // Kas
            $credit_account = '4.100.30'; // Pendapatan Kitab
            break;
        // Add cases for other table types
        default:
            $debit_account = '1.100.10'; // Default Kas
            $credit_account = '4.100.90'; // Default Pendapatan Lain
    }
    
    if ($is_payment) {
        // For payment records, create debit to cash and credit to revenue
        $query1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0', 
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='$debit_account',
            debet='$nominal',
            kredit='0',
            keterangan='$keterangan',
            kode='$kode',
            username='$username'");
            
        $query2 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0',
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='$credit_account',
            debet='0',
            kredit='$nominal',
            keterangan='$keterangan',
            kode='$kode',
            username='$username'");
    } else {
        // For charge records, create entries that match your accounting system
        // This is just an example - adjust based on your system
        $query1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0', 
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='1.200.10', /* Piutang */
            debet='$nominal',
            kredit='0',
            keterangan='$keterangan',
            kode='$kode',
            username='$username'");
            
        $query2 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0',
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='$credit_account',
            debet='0',
            kredit='$nominal',
            keterangan='$keterangan',
            kode='$kode',
            username='$username'");
    }
            
    if (!$query1 || !$query2) {
        throw new Exception(mysqli_error($koneksi));
    }

    // Commit transaction if everything is successful
    mysqli_commit($koneksi);
    
    // Success message and redirect
    echo "<script type='text/javascript'>
        alert('Data transaksi berhasil diupdate');
        window.location = '../home.php?home=" . md5("edit_tagihansyahriah") . "';
    </script>";
    
} catch (Exception $e) {
    // Rollback if there's an error
    mysqli_rollback($koneksi);
    
    echo "<script type='text/javascript'>
        alert('Error: " . $e->getMessage() . "');
        window.location = '../home.php?home=" . md5("edit_tagihansyahriah") . "';
    </script>";
}
?>