<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\LeadScoringRuleModel;
use Modules\Sale\Services\LeadScoringRuleService;
use Modules\Sale\Services\LeadScoringService;

class LeadScoringController extends BaseController
{
    protected LeadScoringRuleModel $rules;
    protected LeadScoringRuleService $service;
    protected LeadScoringService $scoring;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->rules    = new LeadScoringRuleModel();
        $this->service  = new LeadScoringRuleService();
        $this->scoring  = new LeadScoringService();
    }

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

        $rules = $this->rules
            ->scopeForList($search ?: null, $status)
            ->orderBy('points', 'DESC')
            ->orderBy('name', 'ASC')
            ->findAll();

        return view('Modules\Sale\Views\lead_scoring\index', array_merge($this->baseViewData(), [
            'title'   => 'Lead Scoring',
            'rules'   => $rules,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\lead_scoring\create', array_merge($this->baseViewData(), [
            'title' => 'Add Scoring Rule',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'      => 'required|min_length[2]|max_length[100]',
            'criterion' => 'required',
            'points'    => 'required|integer',
        ])) {
            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/lead-scoring')->with('success', 'Scoring rule created.');
    }

    public function editForm(int $id)
    {
        $rule = $this->rules->find($id);
        if (! $rule) {
            return redirect()->to('/sale/lead-scoring')->with('error', 'Scoring rule not found.');
        }

        return view('Modules\Sale\Views\lead_scoring\edit', array_merge($this->baseViewData(), [
            'title' => 'Edit Scoring Rule',
            'rule'  => $rule,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'      => 'required|min_length[2]|max_length[100]',
            'criterion' => 'required',
            'points'    => 'required|integer',
        ])) {
            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/lead-scoring')->with('success', 'Scoring rule updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Scoring rule activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Scoring rule deactivated.');
    }

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

        return redirect()->to('/sale/lead-scoring')->with('success', 'Scoring rule deleted.');
    }

    public function recalculate()
    {
        $updated = $this->scoring->recalculateAll();

        return redirect()->back()->with('success', "Recalculated scores for {$updated} lead(s).");
    }
}
