<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use Config\Database;
use Modules\Inventory\Services\ReorderLevelService;

class ReorderLevelController extends BaseController
{
    protected ProductModel $products;
    protected ReorderLevelService $service;

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

    public function index()
    {
        $search   = trim((string) $this->request->getGet('q'));
        $lowStock = (bool) $this->request->getGet('low_stock');

        $db = Database::connect();
        $builder = $db->table('products')
            ->select('products.*, COALESCE(SUM(stock_balances.quantity), 0) AS total_stock', false)
            ->join('stock_balances', 'stock_balances.product_id = products.id', 'left')
            ->where('products.status', 'active')
            ->groupBy('products.id');

        if ($search) {
            $builder->groupStart()
                ->like('products.name', $search)
                ->orLike('products.sku', $search)
                ->orLike('products.barcode', $search)
                ->groupEnd();
        }

        if ($lowStock) {
            $builder->having('products.reorder_level >', 0, false)
                ->having('total_stock <= products.reorder_level', null, false);
        }

        $products = $builder->orderBy('products.name', 'ASC')->get()->getResultArray();

        return view('Modules\Inventory\Views\reorder_levels\index', array_merge($this->baseViewData(), [
            'title'    => 'Reorder Levels',
            'products' => $products,
            'filters'  => [
                'search'    => $search,
                'low_stock' => $lowStock,
            ],
        ]));
    }

    public function update()
    {
        $productIds    = $this->request->getPost('product_id') ?? [];
        $reorderLevels = $this->request->getPost('reorder_level') ?? [];

        $levels = [];
        foreach ((array) $productIds as $i => $productId) {
            $levels[] = [
                'product_id'    => $productId,
                'reorder_level' => $reorderLevels[$i] ?? 0,
            ];
        }

        $result = $this->service->updateLevels($levels, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/inventory/reorder-levels')->with('success', 'Reorder levels saved.');
    }
}
