<?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'];
$kodetab      = $_POST['jtabungan'];
$rekening     = $_POST['rekening'];
$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 mutasitabungan 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=c1b1f59dbfe51b882c8b0dd09c86c1ca';
    </script>";
    exit;
}

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

// Check if the account is blocked or closed
$block = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT rekening, blokir, tutup FROM bukutabungan WHERE rekening = '$rekening'"));

if ($block && $block['tutup'] == '1') {
    echo "<script type='text/javascript'>
        alert('Buku Tabungan Telah ditutup...!');
        window.location = '../home.php?home=" . md5("edit_mutasitabungan") . "';
    </script>";
    exit;
} elseif ($block && $block['blokir'] == '1') {
    echo "<script type='text/javascript'>
        alert('Buku Tabungan Telah blokir...!');
        window.location = '../home.php?home=" . md5("edit_mutasitabungan") . "';
    </script>";
    exit;
}

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

try {
    // Update mutasitabungan table based on transaction type
    if ($kodetab == "S") {
        // For deposit (Setor)
        $query = mysqli_query($koneksi, "UPDATE mutasitabungan SET 
            rekening='$rekening',
            debet='0',
            kredit='$nominal',
            keterangan='$keterangan',
            kodetab='$kodetab',
            tgl='$tgl',
            userKoreksi='$username' 
            WHERE no_bukti='$no_bukti'");

         //untuk WA
        $pesan = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT a.nim AS nim,a.nama AS nama,a.ibu as ibu, a.wali as wali, a.nohp AS nohp,sum(b.kredit-b.debet) AS saldoTab,b.keterangan as keterangan FROM registrasi a LEFT JOIN mutasitabungan b ON a.id=b.id WHERE b.rekening='$rekening' AND NOT no_bukti='$no_bukti' "));
  $saldoTab =$pesan['saldoTab']+$nominal;
    $nohp = $pesan['nohp'];
    $nama = $pesan['nama'];
    $nim = $pesan['nim'];
    $barang = 'a';
    $saldoTarik  =$pesan['saldoTab']-$nominal;
$judul = "*MMU A-39 REJOSARI*";
$tglpsn = $tgl;                
    // Set payment method
    $metodebayar = "Koreksi Setor";
    $jmlangsuran = number_format(0, 0);
    $kantor = "*MMU A-39*";
    $rekeningpesan = $nim;
    $ket2 = $keterangan;
    $hasilket = preg_replace('/104.*$/', '', $ket2);
    $keteranganpesan = trim($hasilket);

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

        $waSetor = mysqli_query($koneksi, "INSERT INTO message SET number='$nohp',tgl='$tglpsn',judul='$judul', penErima='$nama', PenGirim='$kantor', rekening='$nim',kewajiban='$barang',sisaKewajiban='$saldoTab', nominal='$nominal', keterangan='$keteranganpesan', metodeBayar='$metodebayar',kodeFilTer='editTab' ") or die(mysqli_error($koneksi));
            
        if (!$query) {
            throw new Exception(mysqli_error($koneksi));
        }
    } else {
        // For withdrawal (Tarik)
        $query = mysqli_query($koneksi, "UPDATE mutasitabungan SET 
            rekening='$rekening',
            debet='$nominal',
            kredit='0',
            keterangan='$keterangan',
            kodetab='$kodetab',
            tgl='$tgl',
            userKoreksi='$username' 
            WHERE no_bukti='$no_bukti'");
        
        //untuk WA
        $pesan = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT a.nim AS nim,a.nama AS nama,a.ibu as ibu, a.wali as wali, a.nohp AS nohp,sum(b.kredit-b.debet) AS saldoTab,b.keterangan as keterangan FROM registrasi a LEFT JOIN mutasitabungan b ON a.id=b.id WHERE b.rekening='$rekening' AND NOT no_bukti='$no_bukti'"));
  $saldoTab =$pesan['saldoTab']+$nominal;
    $nohp = $pesan['nohp'];
    $nama = $pesan['nama'];
    $nim = $pesan['nim'];
    $barang = 'a';
    $saldoTarik  =$pesan['saldoTab']-$nominal;
$judul = "*MMU A-39 REJOSARI*";
$tglpsn = $tgl;                
    // Set payment method
    $metodebayar = "Koreksi Tarik";
    $jmlangsuran = number_format(0, 0);
    $kantor = "*MMU A-39*";
    $rekeningpesan = $nim;
    $ket2 = $keterangan;
    $hasilket = preg_replace('/104.*$/', '', $ket2);
    $keteranganpesan = trim($hasilket);

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

        $waSetor = mysqli_query($koneksi, "INSERT INTO message SET number='$nohp',tgl='$tglpsn',judul='$judul', penErima='$nama', PenGirim='$kantor', rekening='$nim',kewajiban='$barang',sisaKewajiban='$saldoTarik', nominal='$nominal', keterangan='$keteranganpesan', metodeBayar='$metodebayar',kodeFilTer='editTab' ") or die(mysqli_error($koneksi));
            
        if (!$query) {
            throw new Exception(mysqli_error($koneksi));
        }
    }

    // Check if the account has sufficient balance for withdrawal
    if ($kodetab == "T") {
        $balance_check = mysqli_fetch_assoc(mysqli_query($koneksi, 
            "SELECT SUM(kredit-debet) as balance FROM mutasitabungan 
            WHERE rekening='$rekening'"));
            
        $original_amount = ($original['kodetab'] == 'T') ? $original['debet'] : 0;
        
        // Calculate if there's enough balance for this withdrawal
        if ($balance_check['balance'] < $nominal) {
            throw new Exception("Saldo tidak mencukupi untuk melakukan penarikan!");
        }
    }

    // Update bukubesar entries
    // First, delete existing entries for this transaction
    mysqli_query($koneksi, "DELETE FROM bukubesar WHERE no_bukti='$no_bukti'");
    
    // Then create new entries based on the current transaction type
    if ($kodetab == "S") {
        // For deposit (Setor)
        $query1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0', 
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='1.100.10',
            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='2.220.10',
            debet='0',
            kredit='$nominal',
            keterangan='$keterangan',
            kode='$kode',
            username='$username'");
            
        if (!$query1 || !$query2) {
            throw new Exception(mysqli_error($koneksi));
        }
    } else {
        // For withdrawal (Tarik)
        $query1 = mysqli_query($koneksi, "INSERT INTO bukubesar SET 
            id_jurnal='0', 
            no_bukti='$no_bukti',
            tanggal='$tgl',
            kode_akun='1.100.10',
            debet='0',
            kredit='$nominal',
            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='2.220.10',
            debet='$nominal',
            kredit='0',
            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_mutasitabungan") . "';
    </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_mutasitabungan") . "';
    </script>";
}
?>