<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\StockCountLineModel;
use App\Models\StockCountModel;
use App\Models\WarehouseModel;
use Modules\Inventory\Services\StockCountService;

class StockCountController extends BaseController
{
    protected StockCountModel $counts;
    protected StockCountLineModel $lines;
    protected StockCountService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->counts  = new StockCountModel();
        $this->lines   = new StockCountLineModel();
        $this->service = new StockCountService();
    }

    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;

        $counts = $this->counts
            ->scopeForList($search ?: null, $status, $warehouseId)
            ->orderBy('stock_counts.count_date', 'DESC')
            ->orderBy('stock_counts.id', 'DESC')
            ->paginate(20);

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

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

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

    public function show(int $id)
    {
        $count = $this->counts->scopeForList()->where('stock_counts.id', $id)->first();
        if (! $count) {
            return redirect()->to('/inventory/stock-counts')->with('error', 'Stock count not found.');
        }

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

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

        if (! in_array($count['status'], ['draft', 'in_progress'], true)) {
            return redirect()->to('/inventory/stock-counts/' . $id)->with('error', 'Only draft or in-progress counts can be edited.');
        }

        $lines = $this->lines->getForCount($id);
        if (count($lines) === 0) {
            $lines = [['product_id' => '', 'system_qty' => '', 'counted_qty' => '', 'notes' => '']];
        }

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

    public function update(int $id)
    {
        if (! $this->validate([
            'warehouse_id' => 'required|is_natural_no_zero',
            'count_date'   => 'required|valid_date',
        ])) {
            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-counts/' . $id)->with('success', 'Stock count 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-counts/' . $id)->with('success', 'Stock count completed and adjustments applied.');
    }

    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-counts/' . $id)->with('success', 'Stock count 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-counts')->with('error', $result['error']);
        }

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