<?php
/**
 * Export Invoices as CSV (Excel-compatible)
 * GET /v1/invoices/export
 * Downloads a CSV file with invoice data + line items
 */

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

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$tenantId = $decoded['tenant_id'];
$role = $decoded['role'];
$companyId = $_GET['company_id'] ?? null;
$dateFrom = $_GET['date_from'] ?? null;
$dateTo = $_GET['date_to'] ?? null;
$status = $_GET['status'] ?? null;

// Build query with filters
$where = [];
$params = [];

if ($role !== 'super_admin') {
    $where[] = 'i.tenant_id = ?';
    $params[] = $tenantId;
}

if ($companyId) {
    $where[] = 'i.company_id = ?';
    $params[] = $companyId;
}

if ($dateFrom) {
    $where[] = 'i.invoice_date >= ?';
    $params[] = $dateFrom;
}

if ($dateTo) {
    $where[] = 'i.invoice_date <= ?';
    $params[] = $dateTo;
}

if ($status) {
    $where[] = 'i.status = ?';
    $params[] = $status;
}

$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $db->prepare("
    SELECT i.*, c.name as company_name_raw
    FROM invoices i
    JOIN companies c ON i.company_id = c.id
    $whereClause
    ORDER BY i.invoice_date DESC
    LIMIT 5000
");
$stmt->execute($params);
$invoices = $stmt->fetchAll();

// Decrypt helper
$dec = function($val) {
    if (empty($val)) return '';
    $result = Encryption::decrypt((string)$val);
    return ($result !== false && $result !== null) ? $result : (string)$val;
};

// UTF-8 BOM for Excel compatibility
$output = "\xEF\xBB\xBF";

// CSV headers
$output .= implode(',', [
    'رقم الفاتورة',
    'تاريخ الفاتورة',
    'الشركة',
    'اسم المورّد',
    'الرقم الضريبي للمورّد',
    'عنوان المورّد',
    'اسم العميل',
    'الرقم الضريبي للعميل',
    'نوع الفاتورة',
    'المبلغ قبل الضريبة',
    'قيمة الخصم',
    'قيمة الضريبة',
    'الإجمالي',
    'العملة',
    'الحالة',
    'JoFotara UUID',
    'تاريخ الإنشاء',
]) . "\n";

foreach ($invoices as $inv) {
    $statusAr = match($inv['status']) {
        'extracted' => 'مستخرجة',
        'approved' => 'معتمدة',
        'submitted' => 'مقدمة لجوفتورة',
        'rejected' => 'مرفوضة',
        default => $inv['status']
    };

    $row = [
        '"' . str_replace('"', '""', $inv['invoice_number'] ?? '') . '"',
        $inv['invoice_date'] ?? '',
        '"' . str_replace('"', '""', $dec($inv['company_name_raw'] ?? '')) . '"',
        '"' . str_replace('"', '""', $dec($inv['supplier_name'])) . '"',
        '"' . $dec($inv['supplier_tin']) . '"',
        '"' . str_replace('"', '""', $dec($inv['supplier_address'])) . '"',
        '"' . str_replace('"', '""', $dec($inv['buyer_name'])) . '"',
        '"' . $dec($inv['buyer_tin']) . '"',
        $inv['invoice_type'] ?? 'cash',
        $inv['subtotal'] ?? '0',
        $inv['discount_total'] ?? '0',
        $inv['tax_amount'] ?? '0',
        $inv['grand_total'] ?? '0',
        $inv['currency_code'] ?? 'JOD',
        $statusAr,
        $inv['jofotara_uuid'] ?? '',
        $inv['created_at'] ?? '',
    ];

    $output .= implode(',', $row) . "\n";
}

// Send as download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="musadaq_invoices_' . date('Y-m-d') . '.csv"');
header('Cache-Control: no-cache');

echo $output;
exit;
