<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\StockBalanceModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\StockService;

class StockController extends BaseController
{
    protected StockBalanceModel $balances;
    protected StockService $service;

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

    public function index()
    {
        $search      = trim((string) $this->request->getGet('q'));
        $warehouseId = $this->request->getGet('warehouse_id') ? (int) $this->request->getGet('warehouse_id') : null;
        $lowStock    = (bool) $this->request->getGet('low_stock');

        $balances = $this->balances
            ->scopeForList($search ?: null, $warehouseId, null, $lowStock)
            ->orderBy('products.name', 'ASC')
            ->paginate(25);

        return view('Modules\Inventory\Views\stock\index', array_merge($this->baseViewData(), [
            'title'      => 'Stock',
            'balances'   => $balances,
            'pager'      => $this->balances->pager,
            'warehouses' => (new WarehouseModel())->getActive(),
            'filters'    => [
                'search'       => $search,
                'warehouse_id' => $warehouseId,
                'low_stock'    => $lowStock,
            ],
        ]));
    }

    public function adjustForm()
    {
        return view('Modules\Inventory\Views\stock\adjust', array_merge($this->baseViewData(), [
            'title'      => 'Adjust Stock',
            'products'   => (new ProductModel())->getActive(),
            'warehouses' => (new WarehouseModel())->getActive(),
        ]));
    }

    public function adjust()
    {
        if (! $this->validate([
            'product_id'   => 'required|is_natural_no_zero',
            'warehouse_id' => 'required|is_natural_no_zero',
            'quantity'     => 'required|decimal',
            'mode'         => 'required|in_list[set,add]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->adjust($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/inventory/stock')->with('success', 'Stock adjusted.');
    }
}
