<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductBatchModel;
use App\Models\ProductModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\BatchService;

class BatchController extends BaseController
{
    protected ProductBatchModel $batches;
    protected BatchService $service;

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

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

        $batches = $this->batches
            ->scopeForList($search ?: null, $status, null, $warehouseId)
            ->orderBy('product_batches.expiry_date', 'ASC')
            ->orderBy('product_batches.batch_number', 'ASC')
            ->paginate(25);

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

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

    public function store()
    {
        if (! $this->validate([
            'product_id'   => 'required|is_natural_no_zero',
            'batch_number' => 'required|max_length[80]',
            'quantity'     => 'required|decimal',
            'status'       => 'required|in_list[active,expired,depleted]',
        ])) {
            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/batches')->with('success', 'Batch created.');
    }

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

        return view('Modules\Inventory\Views\batches\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Batch',
            'batch'      => $batch,
            'products'   => (new ProductModel())->getActive(),
            'warehouses' => (new WarehouseModel())->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'product_id'   => 'required|is_natural_no_zero',
            'batch_number' => 'required|max_length[80]',
            'quantity'     => 'required|decimal',
            'status'       => 'required|in_list[active,expired,depleted]',
        ])) {
            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/batches')->with('success', 'Batch updated.');
    }

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

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