<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\ContactModel;
use Modules\Sale\Services\ContactService;

class ContactController extends BaseController
{
    protected ContactModel $contacts;
    protected CompanyModel $companies;
    protected ContactService $service;

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

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

        $contacts = $this->contacts
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null)
            ->orderBy('last_name', 'ASC')
            ->orderBy('first_name', 'ASC')
            ->paginate(20);

        return view('Modules\Sale\Views\contacts\index', array_merge($this->baseViewData(), [
            'title'      => 'Contacts',
            'contacts'   => $contacts,
            'pager'      => $this->contacts->pager,
            'companies'  => $this->companies->getActive(),
            'companyMap' => $this->buildCompanyMap(),
            'filters'    => compact('search', 'status', 'companyId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\contacts\create', array_merge($this->baseViewData(), [
            'title'     => 'Add Contact',
            'companies' => $this->companies->getActive(),
            'prefillCompanyId' => $this->request->getGet('company_id'),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id' => 'required|is_natural_no_zero',
            'first_name' => 'required|min_length[1]|max_length[100]',
            'last_name'  => 'required|min_length[1]|max_length[100]',
            'email'      => 'permit_empty|valid_email',
        ])) {
            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/contacts')->with('success', 'Contact created.');
    }

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

        return view('Modules\Sale\Views\contacts\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Contact',
            'contact'   => $contact,
            'companies' => $this->companies->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id' => 'required|is_natural_no_zero',
            'first_name' => 'required|min_length[1]|max_length[100]',
            'last_name'  => 'required|min_length[1]|max_length[100]',
            'email'      => 'permit_empty|valid_email',
        ])) {
            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/contacts')->with('success', 'Contact updated.');
    }

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

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

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

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

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

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

    protected function buildCompanyMap(): array
    {
        $map = [];
        foreach ($this->companies->findAll() as $c) {
            $map[$c['id']] = $c['name'];
        }

        return $map;
    }
}
