prepare(" SELECT js.xml_payload, js.jofotara_uuid FROM jofotara_submissions js JOIN invoices i ON js.invoice_id = i.id WHERE i.id = ? AND i.tenant_id = ? AND js.status = 'accepted' ORDER BY js.created_at DESC LIMIT 1 "); $stmt->execute([$id, $tenantId]); $row = $stmt->fetch(); if (!$row || empty($row['xml_payload'])) { json_error('لا يوجد XML رسمي متاح لهذه الفاتورة', 404); } // 4. Send headers for download header('Content-Type: application/xml; charset=utf-8'); header('Content-Disposition: attachment; filename="invoice_' . ($row['jofotara_uuid'] ?: $id) . '.xml"'); echo $row['xml_payload']; exit; } catch (\Exception $e) { error_log("XML Download Error: " . $e->getMessage()); json_error('خطأ في تحميل الملف', 500); }