<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\CustomerGroupModel;

class CompanyController extends BaseController
{
    protected CompanyModel $companies;
    protected CustomerGroupModel $groups;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->companies = new CompanyModel();
        $this->groups    = new CustomerGroupModel();
    }

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

        $companies = $this->companies
            ->scopeForList($search ?: null, $status, $groupId ? (int) $groupId : null)
            ->orderBy('name', 'ASC')
            ->paginate(20);

        return view('Modules\Sale\Views\companies\index', array_merge($this->baseViewData(), [
            'title'     => 'Companies',
            'companies' => $companies,
            'pager'     => $this->companies->pager,
            'groups'    => $this->groups->getActive(),
            'groupMap'  => $this->buildGroupMap(),
            'filters'   => compact('search', 'status', 'groupId'),
        ]));
    }

    public function show(int $id)
    {
        $company = $this->companies->find($id);
        if (! $company) {
            return redirect()->to('/sale/companies')->with('error', 'Company not found.');
        }

        $group = $company['customer_group_id'] ? $this->groups->find($company['customer_group_id']) : null;

        return view('Modules\Sale\Views\companies\show', array_merge($this->baseViewData(), [
            'title'   => $company['name'],
            'company' => $company,
            'group'   => $group,
        ]));
    }

    public function createForm()
    {
        return redirect()->to('/contracts/customers/create');
    }

    public function store()
    {
        return redirect()->to('/contracts/customers/create');
    }

    public function editForm(int $id)
    {
        return redirect()->to('/contracts/customers/' . $id . '/edit');
    }

    public function update(int $id)
    {
        return redirect()->to('/contracts/customers/' . $id . '/edit');
    }

    public function activate(int $id)
    {
        return redirect()->to('/contracts/customers/' . $id);
    }

    public function deactivate(int $id)
    {
        return redirect()->to('/contracts/customers/' . $id);
    }

    public function destroy(int $id)
    {
        return redirect()->to('/contracts/customers');
    }

    protected function buildGroupMap(): array
    {
        $map = [];
        foreach ($this->groups->findAll() as $g) {
            $map[$g['id']] = $g['name'];
        }

        return $map;
    }
}
