<?php
require_once '../includes/auth.php';
requirePermission('master_sales', 'revert', 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) { header("Location: index.php"); exit; }
if ($master['status'] !== 'final') {
    header("Location: view.php?id=$id&error=not_final");
    exit;
}

$conn->begin_transaction();
try {
    // Get all sub-invoices for this master
    $subInvoices = $conn->query("SELECT id FROM sales_invoices WHERE master_invoice_id = $id AND status = 'final'");

    while ($sub = $subInvoices->fetch_assoc()) {
        $sid = (int)$sub['id'];

        // Restore stock for each sub-invoice
        $items = $conn->query("SELECT purchase_item_id, sold_qty FROM sales_items WHERE sales_invoice_id = $sid");
        while ($item = $items->fetch_assoc()) {
            $pid = (int)$item['purchase_item_id'];
            $qty = (float)$item['sold_qty'];
            $conn->query("UPDATE purchase_items SET available_qty = available_qty + $qty WHERE id = $pid");
        }

        // Remove stock movements for this sub-invoice
        $conn->query("DELETE FROM stock_movements WHERE reference_id = $sid AND reference_type = 'sale'");

        // Revert sub-invoice to draft
        $conn->query("UPDATE sales_invoices SET status = 'draft' WHERE id = $sid");
    }

    // Revert master invoice to draft
    $conn->query("UPDATE master_invoices SET status = 'draft' WHERE id = $id");

    $conn->commit();
    header("Location: view.php?id=$id&reverted=1");
    exit;

} catch (Exception $e) {
    $conn->rollback();
    die("Revert failed: " . $e->getMessage());
}
