<?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\ItemUnitRepository;
use App\Services\ItemUnitService;
use Throwable;

final class ItemUnitController
{
    private ItemUnitRepository $repo;
    private ItemUnitService $service;

    public function __construct(private ?\PDO $pdo = null)
    {
        $this->pdo ??= DB::pdo();
        $this->repo = new ItemUnitRepository($this->pdo);
        $this->service = new ItemUnitService($this->repo);
    }

    public function handle(): void
    {
        Auth::requireLogin();
        $itemId = Request::int('item_id');
        if ($itemId <= 0) {
            Response::flash('danger', 'اختر صنف أولاً');
            Response::redirect('/inventory/items');
        }
        $item = $this->repo->findItem($itemId);
        if (!$item) {
            Response::flash('danger', 'الصنف غير موجود');
            Response::redirect('/inventory/items');
        }

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $action = (string) Request::post('action', '');
                if ($action === 'set_base') {
                    $this->service->setBaseUnit($item, Request::int('base_unit_id'));
                    Response::flash('success', 'تم تحديد الوحدة الأساسية');
                    Response::redirect('/inventory/items/units?item_id=' . $itemId);
                    return;
                }
                if ($action === 'add_pack') {
                    $this->service->addPack($item, Request::int('pack_unit_id'), (float) Request::post('factor_to_base', 1), trim((string) Request::post('barcode', '')) ?: null);
                    Response::flash('success', 'تم حفظ وحدة التعبئة');
                    Response::redirect('/inventory/items/units?item_id=' . $itemId);
                    return;
                }
                if ($action === 'delete_pack') {
                    $this->service->deletePack($item, Request::int('unit_id'));
                    Response::flash('success', 'تم الحذف');
                    Response::redirect('/inventory/items/units?item_id=' . $itemId);
                    return;
                }
            }

            Response::view('pages/masters/item_units', [
                'item' => $item,
                'units' => $this->repo->allUnits(),
                'packs' => $this->repo->packsForItem($itemId),
                'page_title' => 'وحدات الصنف',
                'breadcrumbs' => [['label'=>'لوحة التحكم','url'=>'/admin/dashboard'],['label'=>'الأصناف','url'=>'/inventory/items'],['label'=>'وحدات الصنف']]
            ]);
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect('/inventory/items/units?item_id=' . $itemId);
        }
    }
}
