<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $invoice_id = intval($_GET['id']);

    try {
        $conn->beginTransaction();

        // حذف الأصناف المرتبطة بالفاتورة
        $stmt = $conn->prepare("DELETE FROM purchase_invoice_items WHERE invoice_id = :invoice_id");
        $stmt->execute([':invoice_id' => $invoice_id]);

        // حذف الفاتورة
        $stmt = $conn->prepare("DELETE FROM purchase_invoices WHERE id = :invoice_id");
        $stmt->execute([':invoice_id' => $invoice_id]);

        $conn->commit();
        header("Location: purchase_invoices.php?success=deleted");
        exit();
    } catch (PDOException $e) {
        $conn->rollBack();
        error_log("Error deleting invoice: " . $e->getMessage());
        header("Location: purchase_invoices.php?error=delete_failed");
        exit();
    }
} else {
    header("Location: purchase_invoices.php?error=invalid_id");
    exit();
}
?>