<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Repositories\ItemRepository;
use App\Services\ItemService;
use Throwable;
use App\Modules\Inventory\Application\Services\InventoryRouteContext;

final class ItemController
{
    private \PDO $pdo;
    private ItemRepository $items;
    private ItemService $service;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->items = new ItemRepository($this->pdo);
        $this->service = new ItemService($this->pdo, $this->items);
    }

    public function handle(string $mode = 'search'): void
    {
        Auth::requireLogin();
        $routeContext = new InventoryRouteContext();
        $mode = $mode === 'create' ? 'create' : 'search';
        $q = trim((string) Request::get('q', ''));
        $page = max(1, (int) Request::get('page', 1));
        $perPage = 25;
        $editId = $mode === 'search' ? (int) Request::get('edit', 0) : 0;

        try {
            if (Request::isPost()) {
                $this->handlePost($mode);
                return;
            }

            $editItem = null;
            $packInfo = null;
            if ($editId > 0) {
                $editItem = $this->items->findById($editId) ?: null;
                if ($editItem) {
                    $packInfo = $this->items->latestPackInfo($editId) ?: null;
                }
            }

            $totalItems = $mode === 'search' ? $this->items->countSearch($q) : 0;
            $totalPages = max(1, (int) ceil($totalItems / $perPage));
            if ($page > $totalPages) {
                $page = $totalPages;
            }

            Response::view('pages/items/index', [
                'mode' => $mode,
                'items' => $mode === 'search' ? $this->items->searchPage($q, $page, $perPage) : [],
                'q' => $q,
                'page' => $page,
                'per_page' => $perPage,
                'total_items' => $totalItems,
                'total_pages' => $totalPages,
                'edit_item' => $editItem,
                'pack_info' => $packInfo,
                'categories' => get_categories($this->pdo),
                'units' => get_units($this->pdo),
                'warehouses' => get_warehouses($this->pdo),
                'hasSupplierCol' => $this->items->hasSupplierColumn(),
                'page_title' => $mode === 'create' ? 'إضافة صنف' : 'بحث الأصناف',
                'breadcrumbs' => [$routeContext->dashboardCrumb(), ['label' => 'الأصناف']],
            ]);
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
            Response::redirect($mode === 'create' ? url('/inventory/items/create') : $routeContext->itemsPath());
        }
    }

    private function handlePost(string $mode): void
    {
        Csrf::verify();
        $action = (string) Request::post('action', '');
        if ($action === 'create') {
            $this->service->create(Request::all());
            Response::flash('success', 'تم إضافة الصنف');
            Response::redirect($mode === 'create' ? url('/inventory/items/create') : url('/inventory/items'));
            return;
        }
        if ($action === 'update') {
            $id = (int) Request::post('id', 0);
            $this->service->update($id, Request::all());
            Response::flash('success', 'تم تحديث الصنف');
            Response::redirect(url('/inventory/items'));
            return;
        }
        if ($action === 'delete') {
            $id = (int) Request::post('id', 0);
            $this->service->delete($id);
            Response::flash('success', 'تم حذف الصنف');
            Response::redirect(url('/inventory/items'));
            return;
        }
    }
}
