<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\SalesRepresentativeModel;
use App\Models\SalesTerritoryModel;
use Modules\Sale\Services\SalesTeamService;

class SalesRepresentativeController extends BaseController
{
    protected SalesRepresentativeModel $reps;
    protected SalesTerritoryModel $territories;
    protected SalesTeamService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->reps        = new SalesRepresentativeModel();
        $this->territories = new SalesTerritoryModel();
        $this->service     = new SalesTeamService();
    }

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

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

        return view('Modules\Sale\Views\sales_representatives\index', array_merge($this->baseViewData(), [
            'title'   => 'Sales Representatives',
            'reps'    => $reps,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\sales_representatives\create', array_merge($this->baseViewData(), [
            'title'       => 'Add Sales Representative',
            'territories' => $this->territories->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/sale/sales-representatives')->with('success', 'Sales representative created.');
    }

    public function editForm(int $id)
    {
        $rep = $this->reps->find($id);
        if (! $rep) {
            return redirect()->to('/sale/sales-representatives')->with('error', 'Sales representative not found.');
        }

        return view('Modules\Sale\Views\sales_representatives\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Sales Representative',
            'rep'         => $rep,
            'territories' => $this->territories->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->updateRep($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/sales-representatives')->with('success', 'Sales representative updated.');
    }

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

        return redirect()->back()->with('success', 'Sales representative activated.');
    }

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

        return redirect()->back()->with('success', 'Sales representative deactivated.');
    }

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

        return redirect()->to('/sale/sales-representatives')->with('success', 'Sales representative deleted.');
    }
}
