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

if (isset($_REQUEST['del'])) {
  // Get the invoice number from the request
  $invoice = $_GET['del'];
  
  // Start a transaction to ensure atomicity (all queries succeed or none)
  $conn->beginTransaction();

  try {
    // 1. Delete all records with the same invoice from manual_stock_sale table
    $sql = "DELETE FROM manual_stock_sale WHERE invoice=:invoice";
    $query = $conn->prepare($sql);
    $query->bindParam(':invoice', $invoice, PDO::PARAM_INT);
    $query->execute();

    // 2. Delete all records with the same invoice from cash_deposit table
    $sql_cash = "DELETE FROM cash_deposit_manually WHERE invoice=:invoice";
    $query_cash = $conn->prepare($sql_cash);
    $query_cash->bindParam(':invoice', $invoice, PDO::PARAM_INT);
    $query_cash->execute();

    // Check if any records were deleted from manual_stock_sale
    $count_manual_stock_sale = $query->rowCount();

    // Check if any records were deleted from cash_deposit
    $count_cash_deposit = $query_cash->rowCount();

    // If any records were deleted, commit the transaction
    if ($count_manual_stock_sale > 0 || $count_cash_deposit > 0) {
      // Commit the transaction
      $conn->commit();
      echo "<script>alert('Records deleted successfully.');</script>";
    } else {
      // Rollback if no records were found in either table
      $conn->rollBack();
      echo "<script>alert('No records found to delete.');</script>";
    }

    // Redirect to the list-sale page
    echo "<script>window.location.href='../list_pos_manually.php'</script>";
  } catch (Exception $e) {
    // Rollback the transaction in case of error
    $conn->rollBack();
    echo "<script>alert('Error: " . $e->getMessage() . "');</script>";
    echo "<script>window.location.href='../list_pos_manually.php'</script>";
  }
}
?>
