<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductBrandModel;
use App\Models\ProductCategoryModel;
use App\Models\ProductModel;
use App\Models\UnitOfMeasureModel;
use Modules\Inventory\Services\ProductService;

class ProductController extends BaseController
{
    protected ProductModel $products;
    protected ProductService $service;

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

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

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

        return view('Modules\Inventory\Views\products\index', array_merge($this->baseViewData(), [
            'title'      => 'Products',
            'products'   => $products,
            'pager'      => $this->products->pager,
            'categories' => (new ProductCategoryModel())->getActive(),
            'brands'     => (new ProductBrandModel())->getActive(),
            'filters'    => [
                'search'      => $search,
                'status'      => $status,
                'category_id' => $categoryId,
                'brand_id'    => $brandId,
            ],
        ]));
    }

    public function createForm()
    {
        return view('Modules\Inventory\Views\products\create', array_merge($this->baseViewData(), [
            'title'      => 'Add Product',
            'categories' => (new ProductCategoryModel())->getActive(),
            'brands'     => (new ProductBrandModel())->getActive(),
            'units'      => (new UnitOfMeasureModel())->getActive(),
        ]));
    }

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

    public function show(int $id)
    {
        $product = $this->products->findWithRelations($id);
        if (! $product) {
            return redirect()->to('/inventory/products')->with('error', 'Product not found.');
        }

        return view('Modules\Inventory\Views\products\show', array_merge($this->baseViewData(), [
            'title'   => $product['name'],
            'product' => $product,
        ]));
    }

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

        return view('Modules\Inventory\Views\products\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Product',
            'product'    => $product,
            'categories' => (new ProductCategoryModel())->getActive(),
            'brands'     => (new ProductBrandModel())->getActive(),
            'units'      => (new UnitOfMeasureModel())->getActive(),
        ]));
    }

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

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

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

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

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

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

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