<?php
require_once '../includes/auth.php';
requirePermission('sales_returns', 'delete');
require_once '../db.php';

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

$sr = $conn->query("
    SELECT sr.*, inv.invoice_no
    FROM sales_returns sr
    JOIN sales_invoices inv ON inv.id = sr.sales_invoice_id
    WHERE sr.id = $id AND sr.company_id = $cid
")->fetch_assoc();

if (!$sr) die("Sales return not found.");

if ($sr['status'] !== 'draft') {
    die("Finalized returns cannot be deleted. Only draft returns can be removed.");
}

$conn->begin_transaction();

try {
    // Draft returns do not affect available_qty (only final returns do),
    // so no stock restoration needed — just remove the records.
    $conn->query("DELETE FROM sales_return_items WHERE sales_return_id = $id");
    $conn->query("DELETE FROM sales_returns WHERE id = $id AND company_id = $cid");
    $conn->commit();
    header("Location: index.php?deleted=1");
    exit;
} catch (Exception $e) {
    $conn->rollback();
    die("Delete failed: " . $e->getMessage());
}
