<?php

namespace App\Filament\Resources\TransactionResource\Pages;

use App\Filament\Resources\TransactionResource;
use App\Filament\Support\Perm;
use App\Models\Sales\Transaction;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ListTransactions extends ListRecords
{
    protected static string $resource = TransactionResource::class;

    protected function getHeaderActions(): array
    {
        return [
            CreateAction::make(),
            Action::make('export')
                ->label('Export CSV')
                ->color('gray')
                ->icon('heroicon-m-arrow-down-tray')
                ->visible(fn (): bool => Perm::can('isms_transactions', 'export'))
                ->action(fn () => $this->exportCsv()),
        ];
    }

    /**
     * Ported from TransactionController::export() — the exact same scoped
     * query and column set, gated by `isms_transactions.export`.
     */
    public function exportCsv(): StreamedResponse
    {
        abort_unless(Perm::can('isms_transactions', 'export'), 403);

        $user = auth()->user();
        $canViewAll = $user?->hasPermissionTo('isms_transactions.view_all') ?? false;

        $transactions = Transaction::query()
            ->when(! $canViewAll, fn ($q) => $q->where('created_by', $user?->id))
            ->withTrashed()
            ->with(['customer:id,business_name', 'method:id,code,name', 'status:id,code,name', 'creator:id,name'])
            ->orderByDesc('taken_on')
            ->limit(1000)
            ->get();

        return response()->streamDownload(function () use ($transactions) {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['Transaction #', 'Date', 'Customer', 'Method', 'Amount', 'Status', 'Reference', 'Recorded By']);
            foreach ($transactions as $t) {
                fputcsv($out, [
                    $t->transaction_number,
                    ($t->taken_on ?? $t->created_at)?->toDateTimeString(),
                    $t->customer?->business_name,
                    $t->method?->name,
                    $t->amount,
                    $t->status?->name,
                    $t->reference,
                    $t->creator?->name,
                ]);
            }
            fclose($out);
        }, 'transactions.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
    }
}
