<?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\UnitRepository;
use App\Services\UnitService;
use Throwable;
use App\Modules\Inventory\Application\Services\InventoryRouteContext;

final class UnitController
{
    private UnitRepository $units;

    public function __construct(private ?\PDO $pdo = null)
    {
        $this->pdo ??= DB::pdo();
        $this->units = new UnitRepository($this->pdo);
        $this->service = new UnitService($this->units);
    }

    private UnitService $service;

    public function handle(): void
    {
        Auth::requireLogin();
        $routeContext = new InventoryRouteContext();
        $routeContext = new InventoryRouteContext();

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

            $action = (string) Request::get('action', '');
            $id = (int) Request::get('id', 0);
            $edit = ($action === 'edit' && $id > 0) ? ($this->units->findById($id) ?: null) : null;

            Response::view('pages/masters/units', [
                'rows' => $this->units->listWithBaseNames(),
                'all' => $this->units->all(),
                'base_units' => $this->units->baseUnits(),
                'edit' => $edit,
                'page_title' => 'تعريف الوحدات',
                'breadcrumbs' => [$routeContext->dashboardCrumb(), ['label'=>'تعريف الوحدات']],
            ]);
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect($routeContext->unitsPath());
        }
    }

    private function handlePost(): void
    {
        $routeContext = new InventoryRouteContext();
        Csrf::verify();
        $action = (string) Request::post('action', '');

        if ($action === 'delete') {
            $this->service->delete((int) Request::post('id', 0));
            Response::flash('success', 'تم الحذف');
            Response::redirect($routeContext->unitsPath());
            return;
        }

        if ($action === 'save') {
            $this->service->save(Request::all());
            Response::flash('success', 'تم الحفظ');
            Response::redirect($routeContext->unitsPath());
        }
    }
}
