<?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.');

// Verify return belongs to a master invoice and is draft
$sr = $conn->query("
    SELECT sr.id, sr.status
    FROM sales_returns sr
    JOIN sales_invoices si ON si.id = sr.sales_invoice_id
    WHERE sr.id = $id
      AND si.master_invoice_id IS NOT NULL
      AND sr.status = 'draft'
")->fetch_assoc();

if (!$sr) die('Return not found or cannot be deleted. Only draft master returns can be removed.');

$conn->begin_transaction();
try {
    $conn->query("DELETE FROM sales_return_items WHERE sales_return_id = $id");
    $conn->query("DELETE FROM sales_returns WHERE id = $id");
    $conn->commit();
    header("Location: index.php");
    exit;
} catch (Exception $e) {
    $conn->rollback();
    die("Delete failed: " . $e->getMessage());
}
