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

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

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

if (!$inv) { header("Location: index.php"); exit; }
if ($inv['status'] !== 'final') {
    header("Location: view.php?id=$id&error=not_final");
    exit;
}

$conn->begin_transaction();
try {
    // Restore stock: add back available_qty for each sold item
    $items = $conn->query("
        SELECT purchase_item_id, sold_qty FROM sales_items
        WHERE sales_invoice_id = $id
    ");
    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 movement OUT entries for this invoice
    $conn->query("DELETE FROM stock_movements WHERE reference_id = $id AND reference_type = 'sale'");

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

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

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