<?php

namespace Core\App\Services;

use Core\App\Models\OrderModel;

/**
 * OrderExportService
 *
 * Handles all order export logic: CSV download and Google Sheets queuing.
 */
class OrderExportService
{
    public function __construct(private OrderModel $orders) {}

    /**
     * Stream a UTF-8 CSV file of all orders to the browser and exit.
     */
    public function exportCsv(): void
    {
        $orders = $this->orders->getAll();

        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename=orders.csv');

        $output = fopen('php://output', 'w');

        // UTF-8 BOM so Excel renders Arabic/French correctly
        fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));

        fputcsv($output, ['ID', 'Name', 'Phone', 'Status', 'Total', 'Date']);

        foreach ($orders as $order) {
            fputcsv($output, [
                $order['id'],
                $order['full_name'],
                $order['phone'],
                $order['order_status'],
                $order['total_amount'],
                $order['created_at'],
            ]);
        }

        fclose($output);
        exit;
    }

    /**
     * Queue a confirmed order for export to Google Sheets (non-blocking).
     */
    public function queueGoogleSheets(int $id): void
    {
        try {
            $exporter = new GoogleSheetsExporter();
            $exporter->queueConfirmedOrder($id);
        } catch (\Throwable $e) {
            // Non-blocking: export failures must never affect order flow
        }
    }
}
