<?php
require_once '../includes/auth.php';
requirePermission('master_sales', 'edit', BASE_URL . '/dashboard.php');
require_once '../db.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header("Location: index.php"); exit; }

$master = $conn->query("SELECT id, status FROM master_invoices WHERE id = $id")->fetch_assoc();

if (!$master || $master['status'] !== 'draft') {
    header("Location: index.php");
    exit;
}

$conn->query("UPDATE master_invoices SET status = 'cancelled' WHERE id = $id AND status = 'draft'");
$conn->query("UPDATE sales_invoices SET status = 'cancelled' WHERE master_invoice_id = $id AND status = 'draft'");

header("Location: index.php?msg=cancelled");
exit;
