<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Client;
use App\Models\ClientInvoice;
use App\Models\ClientReceipt;

class ClientStatementController extends Controller
{
    public function index(Request $request)
    {
        // Fetch all clients
        $clients = Client::all();

        // Select client by id or default to first
        $selectedClientId = $request->input('client_id', $clients->first()->id ?? null);

        $selectedClient = $selectedClientId ? Client::find($selectedClientId) : null;

        // Fetch invoices and receipts for the selected client
        $invoices = $selectedClient ? ClientInvoice::where('client_id', $selectedClient->id)->get() : collect();
        $receipts = $selectedClient ? ClientReceipt::where('client_id', $selectedClient->id)->get() : collect();

        // Calculate metrics
        $totalInvoices = $invoices->sum('total_amount');
        $totalReceipts = $receipts->sum('total_amount');
        $balance = $totalInvoices - $totalReceipts;
        $outstandingInvoices = $invoices->where('status', 'unpaid')->count();
        $paidInvoices = $invoices->where('status', 'paid')->count();
        $activeCases = 0; // Placeholder, if client has cases
        $lastPaymentDate = $receipts->sortByDesc('receipt_date')->first()->receipt_date ?? null;

        // Pass data to view
        return view('modules.reports.client-statement', [
            'clients' => $clients,
            'selectedClient' => $selectedClient,
            'invoices' => $invoices,
            'receipts' => $receipts,
            'metrics' => [
                'totalInvoices' => $totalInvoices,
                'totalReceipts' => $totalReceipts,
                'balance' => $balance,
                'outstandingInvoices' => $outstandingInvoices,
                'paidInvoices' => $paidInvoices,
                'activeCases' => $activeCases,
                'lastPaymentDate' => $lastPaymentDate,
            ],
        ]);
    }
}
