<?php
/**
 * Official JoFotara XML Download
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

// 1. Auth Check
$decoded = AuthMiddleware::check();
$db = Database::getInstance();

// 2. Validate Request
$id = $_GET['id'] ?? null;
if (!$id) json_error('Invoice ID is required', 422);

$tenantId = $decoded['tenant_id'];

try {
    // 3. Fetch accepted submission for this invoice
    $stmt = $db->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);
}
