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

$id = (int)$_GET['id'];

// Check status
$po = $conn->query("SELECT status FROM purchase_orders WHERE id = $id AND company_id = $cid")->fetch_assoc();
if (!$po) die("Not found.");

if ($po['status'] === 'final') {
    die("Cannot delete finalized purchase.");
}

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