<?php
include '../koneksi.php';

$id         = $_POST['id'];
$tanggal    = $_POST['tanggal'];
$jenis      = $_POST['jenis'];
$kategori   = $_POST['kategori'];
$project    = $_POST['project'] != "" ? $_POST['project'] : NULL;
$nominal    = $_POST['nominal'];
$keterangan = $_POST['keterangan'];
$bank       = $_POST['bank'];

/* ================= DATA TRANSAKSI LAMA ================= */
$lama = mysqli_fetch_assoc(mysqli_query(
    $koneksi,
    "SELECT * FROM transaksi WHERE transaksi_id='$id'"
));

/* ================= KEMBALIKAN SALDO LAMA ================= */
if($lama['transaksi_jenis'] == "Pemasukan"){
    mysqli_query(
        $koneksi,
        "UPDATE bank 
         SET bank_saldo = bank_saldo - {$lama['transaksi_nominal']} 
         WHERE bank_id='{$lama['transaksi_bank']}'"
    );
}else{
    mysqli_query(
        $koneksi,
        "UPDATE bank 
         SET bank_saldo = bank_saldo + {$lama['transaksi_nominal']} 
         WHERE bank_id='{$lama['transaksi_bank']}'"
    );
}

/* ================= UPLOAD BUKTI (OPSIONAL) ================= */
$nama_file = $lama['transaksi_foto'];

if(isset($_FILES['trnfoto']) && $_FILES['trnfoto']['name'] != ""){
    $rand = rand();
    $filename = $_FILES['trnfoto']['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $allowed = ['pdf','jpg','jpeg','png'];

    if(in_array($ext, $allowed)){
        $nama_file = $rand.'_'.$filename;
        move_uploaded_file(
            $_FILES['trnfoto']['tmp_name'],
            "../gambar/bukti/".$nama_file
        );
    }
}

/* ================= UPDATE TRANSAKSI ================= */
$query = mysqli_query($koneksi,"
UPDATE transaksi SET
    transaksi_tanggal='$tanggal',
    transaksi_jenis='$jenis',
    transaksi_kategori='$kategori',
    transaksi_project=".($project ? "'$project'" : "NULL").",
    transaksi_nominal='$nominal',
    transaksi_keterangan='$keterangan',
    transaksi_foto='$nama_file',
    transaksi_bank='$bank'
WHERE transaksi_id='$id'
");

if(!$query){
    die(mysqli_error($koneksi));
}

/* ================= TAMBAH SALDO BARU ================= */
if($jenis == "Pemasukan"){
    mysqli_query(
        $koneksi,
        "UPDATE bank 
         SET bank_saldo = bank_saldo + $nominal 
         WHERE bank_id='$bank'"
    );
}else{
    mysqli_query(
        $koneksi,
        "UPDATE bank 
         SET bank_saldo = bank_saldo - $nominal 
         WHERE bank_id='$bank'"
    );
}

header("location:transaksi.php?alert=update");
