<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\OpportunityModel;
use App\Models\SalesStageModel;

class ExpectedRevenueController extends BaseController
{
    protected OpportunityModel $opportunities;
    protected CompanyModel $companies;
    protected SalesStageModel $stages;

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

    public function index()
    {
        $stageId   = $this->request->getGet('stage_id') ?: null;
        $companyId = $this->request->getGet('company_id') ?: null;

        $rows = $this->opportunities
            ->scopeForWeightedRevenue(
                $stageId ? (int) $stageId : null,
                $companyId ? (int) $companyId : null
            )
            ->orderBy('opportunities.expected_close_date', 'ASC')
            ->orderBy('opportunities.name', 'ASC')
            ->findAll();

        $totalExpected = 0.0;
        $totalWeighted = 0.0;
        foreach ($rows as $row) {
            $totalExpected += (float) $row['expected_revenue'];
            $totalWeighted += (float) $row['weighted_revenue'];
        }

        return view('Modules\Sale\Views\expected_revenue\index', array_merge($this->baseViewData(), [
            'title'          => 'Expected Revenue',
            'rows'           => $rows,
            'stages'         => $this->stages->getActive(),
            'companies'      => $this->companies->getActive(),
            'totalExpected'  => $totalExpected,
            'totalWeighted'  => $totalWeighted,
            'filters'        => compact('stageId', 'companyId'),
        ]));
    }
}
