<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\ProductSerialModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\SerialNumberService;

class SerialNumberController extends BaseController
{
    protected ProductSerialModel $serials;
    protected SerialNumberService $service;

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

    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;

        $serials = $this->serials
            ->scopeForList($search ?: null, $status, null, $warehouseId)
            ->orderBy('product_serials.serial_number', 'ASC')
            ->paginate(25);

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

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

    public function store()
    {
        if (! $this->validate([
            'product_id'    => 'required|is_natural_no_zero',
            'serial_number' => 'required|max_length[100]',
            'status'        => 'required|in_list[in_stock,allocated,sold,scrapped]',
        ])) {
            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/serial-numbers')->with('success', 'Serial number created.');
    }

    public function editForm(int $id)
    {
        $serial = $this->serials->find($id);
        if (! $serial) {
            return redirect()->to('/inventory/serial-numbers')->with('error', 'Serial number not found.');
        }

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

    public function update(int $id)
    {
        if (! $this->validate([
            'product_id'    => 'required|is_natural_no_zero',
            'serial_number' => 'required|max_length[100]',
            'status'        => 'required|in_list[in_stock,allocated,sold,scrapped]',
        ])) {
            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/serial-numbers')->with('success', 'Serial number updated.');
    }

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

        return redirect()->to('/inventory/serial-numbers')->with('success', 'Serial number deleted.');
    }
}
