<?php

namespace App\Http\Controllers\Api;

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

class ExportController extends Controller
{
    public function expenses(Request $request): StreamedResponse
    {
        $userId = $request->user()->id;

        $expenses = Expense::with('category')
            ->where('user_id', $userId)
            ->orderBy('date', 'desc')
            ->get();

        $callback = function () use ($expenses) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['Date', 'Time', 'Category', 'Amount', 'Payment Method', 'Note']);

            foreach ($expenses as $expense) {
                fputcsv($file, [
                    $expense->date,
                    $expense->time ?? '',
                    $expense->category?->name ?? 'Unknown',
                    number_format($expense->amount, 2),
                    ucfirst($expense->payment_method),
                    $expense->note ?? '',
                ]);
            }

            fclose($file);
        };

        $filename = 'all-expenses-' . now()->format('Y-m-d') . '.csv';

        return response()->streamDownload($callback, $filename, [
            'Content-Type' => 'text/csv',
        ]);
    }
}
