<?php 
include '../includes/config.php';

if (isset($_REQUEST['del'])) {
  $invoice = $_GET['del'];
  
  $conn->beginTransaction();

  try {
    $sql = "DELETE FROM stock_sale WHERE invoice=:invoice";
    $query = $conn->prepare($sql);
    $query->bindParam(':invoice', $invoice, PDO::PARAM_INT);
    $query->execute();

    $sql_cash = "DELETE FROM cash_deposit WHERE invoice=:invoice";
    $query_cash = $conn->prepare($sql_cash);
    $query_cash->bindParam(':invoice', $invoice, PDO::PARAM_INT);
    $query_cash->execute();

    $sql_reprint = "DELETE FROM reprint_previous_balance WHERE invoice=:invoice";
    $query_reprint = $conn->prepare($sql_reprint);
    $query_reprint->bindParam(':invoice', $invoice, PDO::PARAM_INT);
    $query_reprint->execute();

    $count_stock_sale = $query->rowCount();

    $count_cash_deposit = $query_cash->rowCount();

    $count_reprint = $query_reprint->rowCount();

    if ($count_stock_sale > 0 || $count_cash_deposit > 0 || $count_reprint > 0) {
      $conn->commit();
      echo "<script>alert('Records deleted successfully.');</script>";
    } else {
      $conn->rollBack();
      echo "<script>alert('No records found to delete.');</script>";
    }

    echo "<script>window.location.href='../list_pos.php'</script>";
  } catch (Exception $e) {
    $conn->rollBack();
    echo "<script>alert('Error: " . $e->getMessage() . "');</script>";
    echo "<script>window.location.href='../list_pos.php'</script>";
  }
}
?>
