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

// Get the current session data
$username     = $_SESSION['username'];
$kode         = $_SESSION['kode'];
//$tgl = $hijri[2]. '-' .$calendar->monthName($hijri[0]) . '-' . sprintf('%02d', $hijri[1]);  

// Get form data
$no_bukti     = $_POST['no_bukti'];
$rekening     = $_POST['rekening'];
$action       = isset($_POST['action']) ? $_POST['action'] : 'update';

// 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;
}

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

try {
    if ($action == 'delete') {
        // Delete the transaction from mutasitabungan
        $delete_query = mysqli_query($koneksi, "DELETE FROM mutasitabungan 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 = "Hapus 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='deleteTab' ") or die(mysqli_error($koneksi));
       
                
        
        if (!$delete_query) {
            throw new Exception(mysqli_error($koneksi));
        }
        
        // Delete related entries from bukubesar if they exist
        mysqli_query($koneksi, "DELETE FROM bukubesar WHERE no_bukti='$no_bukti'");
        
        // Commit transaction if everything is successful
        mysqli_commit($koneksi);
        
        // Success message and redirect
        echo "<script type='text/javascript'>
            alert('Data transaksi berhasil dihapus');
            window.location = '../home.php?home=" . md5("delete_mutasitabungan") . "';
        </script>";
    } else {
        // If not delete action, use the existing update logic
        $kodetab      = $_POST['jtabungan'];
        $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'];
        
        // 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("delete_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("delete_mutasitabungan") . "';
            </script>";
            exit;
        }
        
        // 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',
                username='$username' 
                WHERE no_bukti='$no_bukti'");
            
               
            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',
                username='$username' 
                WHERE no_bukti='$no_bukti'");

              
                
            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'");
           

        
        // Commit transaction if everything is successful
        mysqli_commit($koneksi);
        
        // Success message and redirect
        echo "<script type='text/javascript'>
            alert('Data transaksi berhasil dihapus');
            window.location = '../home.php?home=" . md5("delete_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("delete_mutasitabungan") . "';
    </script>";
}
?>