<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierModel;
use Modules\Procurement\Services\SupplierService;

class SupplierController extends BaseController
{
    protected SupplierModel $suppliers;
    protected SupplierService $service;

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

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

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

        return view('Modules\Procurement\Views\suppliers\index', array_merge($this->baseViewData(), [
            'title'     => 'Suppliers',
            'suppliers' => $suppliers,
            'pager'     => $this->suppliers->pager,
            'filters'   => [
                'search' => $search,
                'status' => $status,
            ],
        ]));
    }

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

    public function store()
    {
        if (! $this->validate([
            'name'  => 'required|min_length[2]|max_length[150]',
            '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/suppliers/' . $result['id'])->with('success', 'Supplier created.');
    }

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

        return view('Modules\Procurement\Views\suppliers\show', array_merge($this->baseViewData(), [
            'title'    => $supplier['name'],
            'supplier' => $supplier,
        ]));
    }

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

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

    public function update(int $id)
    {
        if (! $this->validate([
            'name'  => 'required|min_length[2]|max_length[150]',
            '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/suppliers/' . $id)->with('success', 'Supplier updated.');
    }

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

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

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

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

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

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