<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\LeadConversionModel;
use App\Models\LeadModel;
use App\Models\LeadSourceModel;
use Modules\Auth\Models\UserModel;
use Modules\Sale\Services\LeadConversionService;

class LeadConversionController extends BaseController
{
    protected LeadConversionModel $conversions;
    protected LeadModel $leads;
    protected LeadSourceModel $sources;
    protected UserModel $users;
    protected LeadConversionService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->conversions = new LeadConversionModel();
        $this->leads       = new LeadModel();
        $this->sources     = new LeadSourceModel();
        $this->users       = new UserModel();
        $this->service     = new LeadConversionService();
    }

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

        $conversions = $this->conversions
            ->scopeForList(null, $type)
            ->orderBy('converted_at', 'DESC')
            ->findAll();

        $leadMap = [];
        $userMap = [];
        foreach ((new LeadModel())->findAll() as $l) {
            $leadMap[$l['id']] = trim($l['first_name'] . ' ' . $l['last_name']);
        }
        foreach ($this->users->findAll() as $u) {
            $userMap[$u->id] = $u->getFullName();
        }

        if ($search) {
            $conversions = array_values(array_filter($conversions, static function (array $c) use ($search, $leadMap): bool {
                $name = $leadMap[$c['lead_id']] ?? '';

                return stripos($name, $search) !== false;
            }));
        }

        $convertibleLeads = (new LeadModel())
            ->scopeForList(null, null, null, null, null, true)
            ->whereIn('status', ['new', 'contacted', 'qualified'])
            ->orderBy('score', 'DESC')
            ->findAll();

        return view('Modules\Sale\Views\lead_conversion\index', array_merge($this->baseViewData(), [
            'title'            => 'Lead Conversion',
            'conversions'      => $conversions,
            'convertibleLeads' => $convertibleLeads,
            'leadMap'          => $leadMap,
            'userMap'          => $userMap,
            'filters'          => compact('search', 'type'),
        ]));
    }

    public function convert(int $leadId)
    {
        if (! $this->validate([
            'conversion_type' => 'required|in_list[customer,opportunity]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/sale/lead-conversion')->with('success', 'Lead converted successfully.');
    }
}
