<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierContactModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\SupplierContactService;

class SupplierContactController extends BaseController
{
    protected SupplierContactModel $contacts;
    protected SupplierModel $suppliers;
    protected SupplierContactService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->contacts  = new SupplierContactModel();
        $this->suppliers = new SupplierModel();
        $this->service   = new SupplierContactService();
    }

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

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

        return view('Modules\Procurement\Views\supplier_contacts\index', array_merge($this->baseViewData(), [
            'title'       => 'Supplier Contacts',
            'contacts'    => $contacts,
            'pager'       => $this->contacts->pager,
            'suppliers'   => $this->suppliers->getActive(),
            'supplierMap' => $this->buildSupplierMap(),
            'filters'     => compact('search', 'status', 'supplierId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Procurement\Views\supplier_contacts\create', array_merge($this->baseViewData(), [
            'title'             => 'Add Supplier Contact',
            'suppliers'         => $this->suppliers->getActive(),
            'prefillSupplierId' => $this->request->getGet('supplier_id'),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'supplier_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('/procurement/supplier-contacts')->with('success', 'Supplier contact created.');
    }

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

        return view('Modules\Procurement\Views\supplier_contacts\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Supplier Contact',
            'contact'   => $contact,
            'suppliers' => $this->suppliers->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'supplier_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('/procurement/supplier-contacts')->with('success', 'Supplier contact updated.');
    }

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

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

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

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

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

        return redirect()->to('/procurement/supplier-contacts')->with('success', 'Supplier contact deleted.');
    }

    protected function buildSupplierMap(): array
    {
        $map = [];
        foreach ($this->suppliers->findAll() as $s) {
            $map[$s['id']] = $s['name'];
        }

        return $map;
    }
}
