beginTransaction(); $stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? FOR UPDATE"); $stmt->execute([$id]); $invoice = $stmt->fetch(); if (!$invoice) json_error('Invoice not found', 404); // Super admin can delete anything. Others might only delete non-approved, but let's allow admin to delete. if ($decoded['role'] !== 'super_admin' && $invoice['tenant_id'] !== $decoded['tenant_id']) { json_error('Access denied', 403); } $db->prepare("DELETE FROM invoice_lines WHERE invoice_id = ?")->execute([$id]); $db->prepare("DELETE FROM jofotara_submissions WHERE invoice_id = ?")->execute([$id]); $db->prepare("DELETE FROM invoices WHERE id = ?")->execute([$id]); $db->commit(); AuditLogger::log('invoice.deleted', 'invoice', $id, null, null, $decoded); json_success(null, 'تم حذف الفاتورة بنجاح'); } catch (\Exception $e) { if ($db->inTransaction()) $db->rollBack(); error_log("Invoice Delete Error: " . $e->getMessage()); json_error('فشل في حذف الفاتورة', 500); }