<?php

namespace App\Http\Controllers;

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

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

        // Fetch invoices with related data (outstanding only)
        $invoices = ClientInvoice::with(['client', 'receiptLines', 'currency'])
            ->where('status', '!=', 'draft')
            ->where(function ($query) {
                $query->whereDoesntHave('receiptLines')
                      ->orWhereHas('receiptLines', function ($subQuery) {
                          $subQuery->selectRaw('SUM(amount) as total_paid, invoice_id')
                                    ->groupBy('invoice_id')
                                    ->havingRaw('SUM(amount) < client_invoices.total');
                      });
            })
            ->orderBy('invoice_date', 'desc')
            ->get();

        // Calculate metrics
        $totalOutstanding = $invoices->sum(function ($invoice) {
            $collected = $invoice->receiptLines->sum('amount');
            return $invoice->total - $collected;
        });

        $overdueAmount = $invoices->filter(function ($invoice) {
            return $invoice->due_date < now();
        })->sum(function ($invoice) {
            $collected = $invoice->receiptLines->sum('amount');
            return $invoice->total - $collected;
        });

        $totalInvoices = $invoices->count();

        $avgDaysOverdue = $invoices->filter(function ($invoice) {
            return $invoice->due_date < now();
        })->avg(function ($invoice) {
            return now()->diffInDays($invoice->due_date);
        }) ?? 0;

        $metrics = [
            'totalOutstanding' => $totalOutstanding,
            'overdueAmount' => $overdueAmount,
            'totalInvoices' => $totalInvoices,
            'avgDaysOverdue' => round($avgDaysOverdue),
        ];

        // Apply filters if provided
        $clientId = $request->get('client_id');
        $dateFrom = $request->get('date_from');
        $dateTo = $request->get('date_to');

        if ($clientId) {
            $invoices = $invoices->where('client_id', $clientId);
        }

        if ($dateFrom) {
            $invoices = $invoices->where('invoice_date', '>=', $dateFrom);
        }

        if ($dateTo) {
            $invoices = $invoices->where('invoice_date', '<=', $dateTo);
        }

        return view('modules.reports.outstanding-fees', compact('invoices', 'metrics', 'clients'));
    }
}
