<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\OpportunityModel;
use App\Models\SalesStageModel;
use Modules\Sale\Services\OpportunityService;

class ProbabilityController extends BaseController
{
    protected OpportunityModel $opportunities;
    protected SalesStageModel $stages;
    protected OpportunityService $service;

    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->stages        = new SalesStageModel();
        $this->service       = new OpportunityService();
    }

    public function index()
    {
        $search  = trim((string) $this->request->getGet('q'));
        $status  = $this->request->getGet('status') ?: 'open';
        $stageId = $this->request->getGet('stage_id') ?: null;

        $opportunities = $this->opportunities
            ->scopeForList($search ?: null, $status ?: null, $stageId ? (int) $stageId : null)
            ->orderBy('opportunities.name', 'ASC')
            ->findAll();

        return view('Modules\Sale\Views\probability\index', array_merge($this->baseViewData(), [
            'title'         => 'Probability',
            'opportunities' => $opportunities,
            'stages'        => $this->stages->getActive(),
            'filters'       => compact('search', 'status', 'stageId'),
        ]));
    }

    public function updateProbability(int $id)
    {
        if (! $this->validate([
            'probability' => 'required|integer|greater_than_equal_to[0]|less_than_equal_to[100]',
        ])) {
            return redirect()->back()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->updateProbability(
            $id,
            (int) $this->request->getPost('probability'),
            (int) $this->session->get('user_id')
        );

        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Probability updated.');
    }
}
