<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

class OrderExportController extends Controller
{
    public function csv(Request $request): StreamedResponse|Response
    {
        $user = $request->user();
        if (! $user || ! $user->isAdmin()) {
            abort(403);
        }

        $query = Order::query()->with(['user', 'address']);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $query->orderByDesc('created_at');

        $filename = 'commandes_' . now()->format('Y-m-d_His') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        return response()->streamDownload(function () use ($query) {
            $stream = fopen('php://output', 'w');

            fprintf($stream, chr(0xEF) . chr(0xBB) . chr(0xBF)); // BOM UTF-8

            fputcsv($stream, [
                'ID',
                'Numéro',
                'Client',
                'Email',
                'Total (FCFA)',
                'Statut',
                'Paiement',
                'Livraison',
                'Date création',
            ], ';');

            $query->chunk(100, function ($orders) use ($stream) {
                foreach ($orders as $order) {
                    fputcsv($stream, [
                        $order->id,
                        $order->number,
                        $order->user?->name ?? '',
                        $order->user?->email ?? '',
                        $order->total,
                        $order->status,
                        $order->payment_status,
                        $order->delivery_status,
                        $order->created_at?->format('Y-m-d H:i'),
                    ], ';');
                }
            });

            fclose($stream);
        }, $filename, $headers);
    }
}
