<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;

class OutstandingPaymentController extends BaseController
{
    protected InvoiceModel $invoices;
    protected CompanyModel $companies;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->invoices  = new InvoiceModel();
        $this->companies = new CompanyModel();
    }

    public function index()
    {
        $search    = trim((string) $this->request->getGet('q'));
        $companyId = $this->request->getGet('company_id') ?: null;

        $invoices = $this->invoices
            ->scopeOutstanding($search ?: null, $companyId ? (int) $companyId : null)
            ->orderBy('invoices.due_date', 'ASC')
            ->orderBy('invoices.id', 'DESC')
            ->findAll();

        $totalOutstanding = 0.0;
        foreach ($invoices as $inv) {
            $totalOutstanding += max(0, (float) $inv['total'] - (float) $inv['amount_paid']);
        }

        return view('Modules\Sale\Views\outstanding_payments\index', array_merge($this->baseViewData(), [
            'title'            => 'Outstanding Payments',
            'invoices'         => $invoices,
            'companies'        => $this->companies->getActive(),
            'totalOutstanding' => $totalOutstanding,
            'filters'          => compact('search', 'companyId'),
        ]));
    }
}
