<?php

namespace App\Components\Report\Tranche;

use App\Models\Client\Client;
use App\Models\Tranche;
use Livewire\Component;
use Livewire\WithPagination;
use Symfony\Component\HttpFoundation\StreamedResponse;

class View extends Component {
    use WithPagination;

    public Tranche $tranche;
    public $search = '';


    public function exportToCsv() {
        $cases = Client::where('tranche_id', $this->tranche->id)
            ->with(['claim.status'])
            ->get();

        $filename = "funded_cases_" . now()->format('Y-m-d_H-i-s') . ".csv";

        return new StreamedResponse(function () use ($cases)
        {
            $handle = fopen('php://output', 'w');

            // Header
            fputcsv($handle, [
                'Funder', 'Tranche', 'Amount Funded', 'Date Funded', 'Redemption Date',
                'Client ID', 'APP Number', 'Priority Level', 'Status',
                'Est Compensation', 'Actual Compensation'
            ]);

            $totals = ['funded' => 0, 'est' => 0, 'actual' => 0];

            foreach ($cases as $client) {
                $row = [
                    $this->tranche->funder_name,
                    $this->tranche->tranche_name,
                    $this->tranche->amount_per_case,
                    now()->format('d/m/Y'),
                    now()->addMonths(12)->format('d/m/Y'),
                    $client->id,
                    $client->claim?->case_number ?? 'N/A',
                    $client->claim?->priority?->priority ?? 'N/A',
                    $client->claim?->status?->status ?? 'N/A',
                    0, // Placeholders from original
                    0
                ];
                fputcsv($handle, $row);
                $totals['funded'] += $this->tranche->amount_per_case;
            }

            fputcsv($handle, []);
            fputcsv($handle, ['Funded Total (£)', $totals['funded']]);
            fputcsv($handle, ['Est Compensation Total (£)', 0]);
            fputcsv($handle, ['Actual Compensation Total (£)', 0]);

            fclose($handle);
        }, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ]);
    }

    public function render() {
        $clients = Client::where('tranche_id', $this->tranche->id)
            ->where(function ($q)
            {
                $q->where('id', 'like', "%{$this->search}%");
            })
            ->with(['claim.status'])
            ->paginate(15);

        return view('components.report.tranche.view', [
            'clients' => $clients
        ]);
    }
}
