<?php
require_once("../../public/connection.php");

// Check if invoice_id is set and valid
if (isset($_GET['invoice_id'])) {
    $invoiceId = filter_var($_GET['invoice_id'], FILTER_SANITIZE_NUMBER_INT);

    if ($invoiceId) {
        // Begin transaction
        $connection->begin_transaction();

        try {
            // Delete invoice items first
            $stmtItems = $connection->prepare("DELETE FROM invoice_item_order WHERE invoice_id = ?");
            $stmtItems->bind_param("i", $invoiceId);
            $stmtItems->execute();

            // Delete main invoice
            $stmtInvoice = $connection->prepare("DELETE FROM invoice_order WHERE invoice_id = ?");
            $stmtInvoice->bind_param("i", $invoiceId);
            $stmtInvoice->execute();

            // Commit transaction
            $connection->commit();

            $_SESSION['msg'] = "Invoice and its items were deleted successfully.";
            $_SESSION['type'] = "success";
        } catch (Exception $e) {
            $connection->rollback();
            $_SESSION['msg'] = "Error deleting invoice: " . $e->getMessage();
            $_SESSION['type'] = "danger";
        }
    } else {
        $_SESSION['msg'] = "Invalid invoice ID provided.";
        $_SESSION['type'] = "warning";
    }
} else {
    $_SESSION['msg'] = "No invoice ID was specified.";
    $_SESSION['type'] = "warning";
}

// Redirect to the invoice list page
header("Location: view_invoice");
exit();
?>

