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

final class CategoryController
{
    private \PDO $pdo;
    private CategoryRepository $categories;
    private CategoryService $service;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->categories = new CategoryRepository($this->pdo);
        $this->service = new CategoryService($this->categories);
    }

    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->categories->findById($id) ?: null) : null;

            Response::view('pages/masters/categories', [
                'rows' => get_categories($this->pdo),
                'all' => $this->categories->all(),
                'edit' => $edit,
                'page_title' => 'فئات الأصناف',
                'breadcrumbs' => [$routeContext->dashboardCrumb(), ['label'=>'فئات الأصناف']],
            ]);
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect($routeContext->categoriesPath());
        }
    }

    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->categoriesPath());
            return;
        }

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