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

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

/* ================= UPLOAD BUKTI (OPSIONAL) ================= */
$nama_file = "";

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)){
        header("location:transaksi.php?alert=gagal");
        exit;
    }

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

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

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

/* ================= UPDATE SALDO BANK ================= */
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=berhasil");
