<?php

namespace Modules\Sale\Controllers;

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

class TerritoryController extends BaseController
{
    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->territories = new SalesTerritoryModel();
        $this->service     = new SalesTeamService();
    }

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

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

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

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

    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->createTerritory($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/territories')->with('success', 'Territory created.');
    }

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

        return view('Modules\Sale\Views\territories\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Territory',
            'territory' => $territory,
        ]));
    }

    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->updateTerritory($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/territories')->with('success', 'Territory updated.');
    }

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

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

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

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

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

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