<?php declare(strict_types=1);

namespace Shop\Presentation\Controllers;

use Core\Application\Loader;
use Core\BaseController;
use Core\Concrete\AuthFactory;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Http\Discovery\Exception\NotFoundException;
use Shop\Application\Auth\AdminAuthService;
use Symfony\Component\HttpFoundation\JsonResponse;

class CategoryController extends BaseController implements RequestAwareInterface
{
    use RequestAwareTrait;

    public function __construct(protected AdminAuthService $adminAuthService)
    {
    }

    public function show(array $args): JsonResponse
    {
        if(!$user = $this->adminAuthService->getCurrentUser()){
            return new JsonResponse([], JsonResponse::HTTP_FORBIDDEN);
        }


        if (empty($args['id'])) {
            throw new NotFoundException('id not set');
        }

        if(input_get('lite')){
            $html = Loader::getModule('Shop.AdminCategoriesLite', [
                'parentId' => $args['id']
            ]);
        }
        else{
            $html = Loader::getModule('Shop.AdminCategories', [
                'parentId' => $args['id']
            ]);
        }
        


        if (preg_match('~<tbody>(.*?)<\/tbody>~is', $html, $match)) {
            $html = $match[1];
        }

        if (preg_match('~<tr.*?class="table-filter">.*?<\/tr>(.*?)$~is', $html, $match)) {
            $html = $match[1];
        }

        return JsonResponse::create([
            'html' => $html
        ]);

    }

}