
<?php
require_once '../includes/auth.php';
requirePermission('sales', 'delete');
require_once '../db.php';

$id = (int)$_GET['id'];

$inv = $conn->query("SELECT status FROM sales_invoices WHERE id = $id AND company_id = $cid")->fetch_assoc();

if (!$inv) {
    die("Invoice not found");
}

if ($inv['status'] !== 'draft') {
    die("Final invoice cannot be deleted.");
}

// Safe to delete
$conn->begin_transaction();

try {
    $conn->query("DELETE FROM sales_items WHERE sales_invoice_id = $id");
    $conn->query("DELETE FROM sales_invoices WHERE id = $id");
    $conn->commit();
    header("Location: index.php?msg=deleted");
    exit;
} catch(Exception $e) {
    $conn->rollback();
    die("Delete failed: " . $e->getMessage());
}
?>