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

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

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

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

    $count_stock_sale = $query->rowCount();

    $count_cash_deposit = $query_cash->rowCount();

    if ($count_stock_sale > 0 || $count_cash_deposit > 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_return_pos.php'</script>";
  } catch (Exception $e) {
    $conn->rollBack();
    echo "<script>alert('Error: " . $e->getMessage() . "');</script>";
    echo "<script>window.location.href='../list_return_pos.php'</script>";
  }
}
?>
