<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductCategoryModel;
use Modules\Inventory\Services\CategoryService;

class CategoryController extends BaseController
{
    protected ProductCategoryModel $categories;
    protected CategoryService $service;

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

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

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

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

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

    public function store()
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[100]',
            'code' => 'required|max_length[30]',
        ])) {
            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('/inventory/categories')->with('success', 'Category created.');
    }

    public function editForm(int $id)
    {
        $category = $this->categories->find($id);
        if (! $category) {
            return redirect()->to('/inventory/categories')->with('error', 'Category not found.');
        }

        return view('Modules\Inventory\Views\categories\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Category',
            'category' => $category,
        ]));
    }

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

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

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

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

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

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

        return redirect()->to('/inventory/categories')->with('success', 'Category deleted.');
    }
}
