<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\StockTransferLineModel;
use App\Models\StockTransferModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\StockTransferService;

class StockTransferController extends BaseController
{
    protected StockTransferModel $transfers;
    protected StockTransferLineModel $lines;
    protected StockTransferService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->transfers = new StockTransferModel();
        $this->lines     = new StockTransferLineModel();
        $this->service   = new StockTransferService();
    }

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

        $transfers = $this->transfers
            ->scopeForList($search ?: null, $status)
            ->orderBy('stock_transfers.transfer_date', 'DESC')
            ->orderBy('stock_transfers.id', 'DESC')
            ->paginate(20);

        return view('Modules\Inventory\Views\stock_transfers\index', array_merge($this->baseViewData(), [
            'title'     => 'Stock Transfers',
            'transfers' => $transfers,
            'pager'     => $this->transfers->pager,
            'filters'   => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Inventory\Views\stock_transfers\create', array_merge($this->baseViewData(), [
            'title'      => 'New Stock Transfer',
            'warehouses' => (new WarehouseModel())->getActive(),
            'products'   => (new ProductModel())->getActive(),
            'lines'      => [['product_id' => '', 'quantity' => '1', 'notes' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'transfer_date'     => 'required|valid_date',
            'from_warehouse_id' => 'required|is_natural_no_zero',
            'to_warehouse_id'   => 'required|is_natural_no_zero',
        ])) {
            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-transfers/' . $result['id'])->with('success', 'Stock transfer created.');
    }

    public function show(int $id)
    {
        $transfer = $this->transfers->findWithWarehouses($id);
        if (! $transfer) {
            return redirect()->to('/inventory/stock-transfers')->with('error', 'Stock transfer not found.');
        }

        return view('Modules\Inventory\Views\stock_transfers\show', array_merge($this->baseViewData(), [
            'title'    => $transfer['number'],
            'transfer' => $transfer,
            'lines'    => $this->lines->getForTransfer($id),
        ]));
    }

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

        if ($transfer['status'] !== 'draft') {
            return redirect()->to('/inventory/stock-transfers/' . $id)->with('error', 'Only draft transfers can be edited.');
        }

        $lines = $this->lines->getForTransfer($id);
        if (count($lines) === 0) {
            $lines = [['product_id' => '', 'quantity' => '1', 'notes' => '']];
        }

        return view('Modules\Inventory\Views\stock_transfers\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Stock Transfer',
            'transfer'   => $transfer,
            'lines'      => $lines,
            'warehouses' => (new WarehouseModel())->getActive(),
            'products'   => (new ProductModel())->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'transfer_date'     => 'required|valid_date',
            'from_warehouse_id' => 'required|is_natural_no_zero',
            'to_warehouse_id'   => 'required|is_natural_no_zero',
        ])) {
            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/stock-transfers/' . $id)->with('success', 'Stock transfer updated.');
    }

    public function complete(int $id)
    {
        $result = $this->service->complete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->to('/inventory/stock-transfers/' . $id)->with('success', 'Stock transfer completed.');
    }

    public function cancel(int $id)
    {
        $result = $this->service->cancel($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->to('/inventory/stock-transfers/' . $id)->with('success', 'Stock transfer cancelled.');
    }

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

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