<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\LeadAssignmentRuleModel;
use App\Models\LeadModel;
use App\Models\LeadSourceModel;
use Modules\Auth\Models\UserModel;
use Modules\Sale\Services\LeadAssignmentService;

class LeadAssignmentController extends BaseController
{
    protected LeadAssignmentRuleModel $rules;
    protected LeadModel $leads;
    protected LeadSourceModel $sources;
    protected UserModel $users;
    protected LeadAssignmentService $service;

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

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

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

        $sourceMap = [];
        foreach ($this->sources->findAll() as $s) {
            $sourceMap[$s['id']] = $s['name'];
        }

        $userMap = [];
        foreach ($this->users->where('status', 'active')->findAll() as $u) {
            $userMap[$u->id] = $u->getFullName();
        }

        return view('Modules\Sale\Views\lead_assignment\index', array_merge($this->baseViewData(), [
            'title'         => 'Lead Assignment',
            'rules'         => $rules,
            'sources'       => $this->sources->getActive(),
            'users'         => $this->users->where('status', 'active')->orderBy('first_name', 'ASC')->findAll(),
            'sourceMap'     => $sourceMap,
            'userMap'       => $userMap,
            'unassignedCount' => count($this->leads->getUnassigned()),
            'filters'       => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\lead_assignment\create', array_merge($this->baseViewData(), [
            'title'   => 'Add Assignment Rule',
            'sources' => $this->sources->getActive(),
            'users'   => $this->users->where('status', 'active')->orderBy('first_name', 'ASC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'              => 'required|min_length[2]|max_length[100]',
            'assign_to_user_id' => '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-assignment')->with('success', 'Assignment rule created.');
    }

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

        return view('Modules\Sale\Views\lead_assignment\edit', array_merge($this->baseViewData(), [
            'title'   => 'Edit Assignment Rule',
            'rule'    => $rule,
            'sources' => $this->sources->getActive(),
            'users'   => $this->users->where('status', 'active')->orderBy('first_name', 'ASC')->findAll(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'              => 'required|min_length[2]|max_length[100]',
            'assign_to_user_id' => '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-assignment')->with('success', 'Assignment rule updated.');
    }

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

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

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

        return redirect()->back()->with('success', 'Assignment 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-assignment')->with('error', $result['error']);
        }

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

    public function assignUnassigned()
    {
        $count = $this->service->assignUnassigned((int) $this->session->get('user_id'));

        if ($count === 0) {
            return redirect()->back()->with('error', 'No unassigned leads matched any active rules.');
        }

        return redirect()->back()->with('success', "{$count} lead(s) assigned automatically.");
    }
}
