<?php

namespace Modules\Sale\Controllers;

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

class OpportunityController extends BaseController
{
    protected OpportunityModel $opportunities;
    protected CompanyModel $companies;
    protected SalesStageModel $stages;
    protected CompetitorModel $competitors;
    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->companies     = new CompanyModel();
        $this->stages        = new SalesStageModel();
        $this->competitors   = new CompetitorModel();
        $this->service       = new OpportunityService();
    }

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

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\opportunities\create', array_merge($this->baseViewData(), [
            'title'       => 'Add Opportunity',
            'companies'   => $this->companies->getActive(),
            'stages'      => $this->stages->getActive(),
            'competitors' => $this->competitors->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'         => 'required|min_length[2]|max_length[200]',
            'probability'  => 'permit_empty|integer|greater_than_equal_to[0]|less_than_equal_to[100]',
            'status'       => 'permit_empty|in_list[open,won,lost,abandoned]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/opportunities/' . $result['id'])->with('success', 'Opportunity created.');
    }

    public function show(int $id)
    {
        $opportunity = $this->opportunities->find($id);
        if (! $opportunity) {
            return redirect()->to('/sale/opportunities')->with('error', 'Opportunity not found.');
        }

        $company    = $opportunity['company_id'] ? $this->companies->find($opportunity['company_id']) : null;
        $stage      = $opportunity['sales_stage_id'] ? $this->stages->find($opportunity['sales_stage_id']) : null;
        $competitor = $opportunity['competitor_id'] ? $this->competitors->find($opportunity['competitor_id']) : null;

        return view('Modules\Sale\Views\opportunities\show', array_merge($this->baseViewData(), [
            'title'       => $opportunity['name'],
            'opportunity' => $opportunity,
            'company'     => $company,
            'stage'       => $stage,
            'competitor'  => $competitor,
        ]));
    }

    public function editForm(int $id)
    {
        $opportunity = $this->opportunities->find($id);
        if (! $opportunity) {
            return redirect()->to('/sale/opportunities')->with('error', 'Opportunity not found.');
        }

        return view('Modules\Sale\Views\opportunities\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Opportunity',
            'opportunity' => $opportunity,
            'companies'   => $this->companies->getActive(),
            'stages'      => $this->stages->getActive(),
            'competitors' => $this->competitors->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'         => 'required|min_length[2]|max_length[200]',
            'probability'  => 'permit_empty|integer|greater_than_equal_to[0]|less_than_equal_to[100]',
            'status'       => 'permit_empty|in_list[open,won,lost,abandoned]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/opportunities/' . $id)->with('success', 'Opportunity updated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/sale/opportunities')->with('error', $result['error']);
        }

        return redirect()->to('/sale/opportunities')->with('success', 'Opportunity deleted.');
    }
}
