<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\TaxRefund;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class TaxRefundDownloadController extends Controller
{
    /**
     * Download a tax refund receipt (PDF or CSV) securely.
     *
     * @param Request $request
     * @param TaxRefund $refund
     * @return StreamedResponse|\Illuminate\Http\RedirectResponse
     */
    public function download(Request $request, TaxRefund $refund)
    {
        // Signed middleware already validates the URL
        if (!$request->hasValidSignature()) {
            abort(403, 'Invalid or expired link.');
        }

        // Determine format (default PDF)
        $format = strtolower($request->query('format', 'pdf'));

        return match ($format) {
            'pdf' => $this->downloadPdf($refund),
            'csv' => $this->downloadCsv($refund),
            default => redirect()->back()->withErrors(['error' => 'Invalid format selected.']),
        };
    }

    /**
     * Stream PDF download
     */
    protected function downloadPdf(TaxRefund $refund): StreamedResponse
    {
        $pdf = Pdf::loadView('tax-refunds.receipt-pdf', [
            'refund' => $refund,
            'statusHistories' => $refund->statusHistories()->orderBy('created_at')->get(),
        ]);

        return response()->streamDownload(
            fn() => print $pdf->output(),
            "refund_{$refund->filing_number}.pdf"
        );
    }

    /**
     * Stream CSV download
     */
    protected function downloadCsv(TaxRefund $refund): StreamedResponse
    {
        $headers = [
            'Filing Number',
            'Full Name',
            'Email',
            'Country',
            'State',
            'Status',
            'Amount',
            'Filing Status',
            'Income',
            'Taxes Withheld',
            'Deductions',
            'Credits',
            'Review Due Date',
            'Status History Notes',
            'Status Changed At'
        ];

        $statusHistories = $refund->statusHistories()->orderBy('created_at')->get();

        $rows = $statusHistories->map(function ($history) use ($refund) {
            return [
                $refund->filing_number,
                $refund->full_name,
                $refund->email,
                $refund->country_code,
                $refund->state,
                $history->status,
                $refund->amount,
                $refund->meta['filing_status'] ?? '',
                $refund->meta['income'] ?? '',
                $refund->meta['taxes_withheld'] ?? '',
                $refund->meta['deductions'] ?? '',
                $refund->meta['credits'] ?? '',
                $refund->review_due_date?->format('Y-m-d') ?? '',
                $history->notes,
                $history->changed_at?->format('Y-m-d H:i:s') ?? $history->created_at->format('Y-m-d H:i:s'),
            ];
        });

        return response()->streamDownload(function () use ($headers, $rows) {
            echo implode(',', $headers) . "\n";
            foreach ($rows as $row) {
                echo implode(',', array_map(fn($val) => '"' . str_replace('"', '""', $val) . '"', $row)) . "\n";
            }
        }, "refund_{$refund->filing_number}.csv", ['Content-Type' => 'text/csv']);
    }
}
