<?php 
session_start();
include '../koneksi.php';
$id  = (int)($_GET['id'] ?? 0);
// Role input_pengeluaran: hanya boleh hapus transaksi Pengeluaran
if (isset($_SESSION['status']) && $_SESSION['status'] === 'input_pengeluaran_logedin') {
  $cek = mysqli_query($koneksi, "SELECT transaksi_jenis FROM transaksi WHERE transaksi_id = $id");
  $row = mysqli_fetch_assoc($cek);
  if (!$row || $row['transaksi_jenis'] !== 'Pengeluaran') {
    $_SESSION['alert'] = 'error';
    $_SESSION['message'] = 'Anda hanya dapat menghapus transaksi pengeluaran.';
    header('Location: transaksi.php');
    exit;
  }
}

$transaksi = mysqli_query($koneksi,"select * from transaksi where transaksi_id='$id'");
$t = mysqli_fetch_assoc($transaksi);
if (!$t) {
  $_SESSION['alert'] = 'error';
  $_SESSION['message'] = 'Data transaksi tidak ditemukan.';
  header('Location: transaksi.php');
  exit;
}
$bank_lama = $t['transaksi_bank'];

$rekening = mysqli_query($koneksi,"select * from bank where bank_id='$bank_lama'");
$r = mysqli_fetch_assoc($rekening);

$jenis = $t['transaksi_jenis'];
$nominal = $t['transaksi_nominal'];

if($jenis == "Pemasukan"){

	$saldo_sekarang = $r['bank_saldo'];
	$total = $saldo_sekarang-$nominal;
	mysqli_query($koneksi,"update bank set bank_saldo='$total' where bank_id='$bank_lama'");

}elseif($jenis == "Pengeluaran"){

	$saldo_sekarang = $r['bank_saldo'];
	$total = $saldo_sekarang+$nominal;
	mysqli_query($koneksi,"update bank set bank_saldo='$total' where bank_id='$bank_lama'");

}	


mysqli_query($koneksi, "delete from transaksi where transaksi_id='$id'");
$_SESSION['alert'] = 'success';
$_SESSION['message'] = 'Data transaksi berhasil dihapus!';
header("location:transaksi.php");