<?php 
include '../koneksi.php';
$id         = $_GET['id'];
$oleh       = $_GET['oleh'];
$notrans    = $_GET['notrans'];
$kode       = $_GET['kode'];


function cek_kd_trans($kode, $kd_trans, $tanggal) {
  $query = "SELECT * FROM cmob_trans WHERE kode = '$kode' AND tanggal > '$tanggal' ORDER BY tanggal ASC";
  $result = mysqli_query($koneksi, $query);
  while ($row = mysqli_fetch_assoc($result)) {
    if ($row['kt'] == 'PH' && $kt == 'BL') {
      return false;
    } elseif ($row['kt'] == 'JL' && ($kt == 'BL' || $kt == 'PH')) {
      return false;
    }
  }
  return true;
}

if (isset($_POST['hapus'])) {
  $id       = $_POST['id'];
  $notrans  = $_POST['notrans'];
  $oleh     = $_POST['oleh'];
  $kode     = $_POST['kode'];
  
  $query = "SELECT * FROM cmob_trans WHERE id = '$id'";
  $result = mysqli_query($koneksi, $query);
  $row = mysqli_fetch_assoc($result);
  $kode = $row['kode'];
  $kd_trans = $row['kt'];
  $tanggal = $row['tanggal'];

  if (cek_kd_trans($kode, $kt, $tanggal)) {
    $query_hapus = "DELETE FROM cmob_trans WHERE id = '$id'";
    mysqli_query($koneksi, $query_hapus);
    
    $query_hapus_jor = "DELETE FROM jor WHERE notrans = '$notrans'";
    mysqli_query($koneksi, $query_hapus_jor);
    
    $query_hapus_kas = "DELETE FROM kas WHERE notrans = '$notrans'";
    mysqli_query($koneksi, $query_hapus_kas);

    echo "Data berhasil dihapus";
  } else {
    echo "Data tidak bisa dihapus karena ada transaksi berikutnya";
  }
}

    header("location:at_rekap_daftar.php ");
