<?php
// delete_invoice.php
require 'header.php';
require 'db.php';

function h($s){ return htmlspecialchars((string)$s); }

$invoice_no = $_GET['invoice_no'] ?? '';
if (!$invoice_no) {
  // nothing to delete
  http_response_code(400);
  echo "<p>Invoice number required.</p>";
  echo '<p><a href="invoice_search.php">Back to search</a></p>';
  exit;
}

// Optional: fetch invoice to confirm it exists (and optionally log details)
$stmt = $conn->prepare("SELECT id, invoice_no, customer_name FROM invoices WHERE invoice_no = ? LIMIT 1");
if ($stmt === false) {
  echo "<p>DB error (prepare).</p>";
  exit;
}
$stmt->bind_param('s', $invoice_no);
$stmt->execute();
$res = $stmt->get_result();
$inv = $res->fetch_assoc();
$stmt->close();

if (!$inv) {
  // not found
  $_msg = "Invoice not found: " . urlencode($invoice_no);
  header("Location: invoice_search.php?msg=" . $_msg);
  exit;
}

// Perform delete
$del = $conn->prepare("DELETE FROM invoices WHERE invoice_no = ? LIMIT 1");
if ($del === false) {
  // DB prepare error
  $_msg = "DB error: could not prepare delete.";
  header("Location: invoice_search.php?msg=" . urlencode($_msg));
  exit;
}
$del->bind_param('s', $invoice_no);
$ok = $del->execute();
$err = $del->error;
$del->close();

if ($ok) {
  // success — redirect back with message
  $_msg = "Invoice " . urlencode($invoice_no) . " deleted successfully.";
  header("Location: invoice_search.php?msg=" . $_msg);
  exit;
} else {
  // failure
  $_msg = "Failed to delete invoice: " . urlencode($err ?: 'Unknown error');
  header("Location: invoice_search.php?msg=" . $_msg);
  exit;
}
