<?php
require_once '../includes/auth.php';
require_once '../db.php';

requirePermission('master_sales', 'delete', BASE_URL . '/dashboard.php');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die('Invalid ID.');

$master = $conn->query("SELECT status FROM master_invoices WHERE id = $id")->fetch_assoc();
if (!$master) die('Master invoice not found.');
if ($master['status'] !== 'draft') die('Only draft master invoices can be deleted.');

$conn->begin_transaction();
try {
    $siRes = $conn->query("SELECT id FROM sales_invoices WHERE master_invoice_id = $id");
    while ($si = $siRes->fetch_assoc()) {
        $conn->query("DELETE FROM sales_items WHERE sales_invoice_id = {$si['id']}");
    }
    $conn->query("DELETE FROM sales_invoices WHERE master_invoice_id = $id");
    $conn->query("DELETE FROM master_invoices WHERE id = $id");
    $conn->commit();
    header('Location: index.php');
    exit;
} catch (Exception $e) {
    $conn->rollback();
    die('Delete failed: ' . $e->getMessage());
}
?>
