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

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

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

    $count_deleted = $query->rowCount();

    if ($count_deleted > 0) {
      $conn->commit();
      echo "<script>alert('Record(s) deleted successfully.');</script>";
    } else {
      $conn->rollBack();
      echo "<script>alert('No records found to delete.');</script>";
    }

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