<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\StockAdjustmentModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\StockAdjustmentService;

class StockAdjustmentController extends BaseController
{
    protected StockAdjustmentModel $adjustments;
    protected StockAdjustmentService $service;

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

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

        $adjustments = $this->adjustments
            ->scopeForList($search ?: null, $warehouseId)
            ->orderBy('stock_adjustments.adjustment_date', 'DESC')
            ->orderBy('stock_adjustments.id', 'DESC')
            ->paginate(20);

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

    public function createForm()
    {
        return view('Modules\Inventory\Views\stock_adjustments\create', array_merge($this->baseViewData(), [
            'title'      => 'New Stock Adjustment',
            'products'   => (new ProductModel())->getActive(),
            'warehouses' => (new WarehouseModel())->getActive(),
        ]));
    }

    public function store()
    {
        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->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/stock-adjustments')->with('success', 'Stock adjustment recorded.');
    }
}
