<?php

namespace Diamond\Controllers;

use Core\Application\Loader;
use Core\BaseController;
use Core\Exceptions\IsRedirectResponseException;
use Core\Menu\AdminMenu;
use Diamond\Application\Content\ContentService;
use Diamond\Application\Content\Exceptions\PageNotFoundException;
use Diamond\Application\System\SystemService;
use Diamond\Application\User\UserService;
use Diamond\Application\User\Exceptions\UserNotAuthException;
use Diamond\Factory\AdminPageFactory;
use Diamond\Factory\PublicPageFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Diamond\Infrastructure\Models\Page\Page;

/**
 * Description of Admin
 *
 * @author Dmitriy
 */
class AdminController extends BaseController
{

    use PageFactoryTrait;

    private PublicPageFactory $publicPageFactory;

    public function __construct(private Request              $request,
                                SystemService                $templateService,
                                private UserService          $userService,
                                private ContentService       $contentService,
                                SystemService $systemService,
                                private AdminMenu $adminMenu,
                                private \Diamond\Config\Main $sysConf
    )
    {
        $this->pageFactory = new AdminPageFactory($templateService);
        $this->publicPageFactory = new PublicPageFactory($systemService,$contentService,$request);
        $this->sysConf = $sysConf->setUrl_suffix('');
    }

    /**
     * @todo упростить, отрефакторить
     */
    public function index()
    {
        //@todo запрос к страницам определяет страницы авторизации
        try{
            $page = $this->contentService->getPage($this->request);
            return new Response( $this->publicPageFactory->renderPage($page));
        }
        catch (PageNotFoundException $ex){
            $pageAdmin = (new Page)
                ->setUrl($this->request->getPathInfo())
                ->setTitle(admin_name())
                ->setTemplate('admin')
                ->setScript('dashboard.twig');
        }



        try {

            if (input_get('logout') > 0) {
                $this->userService->logout();
                return new RedirectResponse(admin_path('/auth'));
            }

            try {
                $this->userService->getAuthUser();
            } catch (UserNotAuthException $ex) {
                throw new IsRedirectResponseException(RedirectResponse::create(admin_path('/auth')));
            }

            if (rtrim($this->request->getPathInfo(), '/') === admin_path()) {
                $response = RedirectResponse::create(admin_path('/diamond/system/dashboard'));
                throw new IsRedirectResponseException($response);
            }

            if (false === $this->userService->isUserAccessUrl(
                    $pageAdmin->getUrl(),
                    UserService::ACCESS_READ
                )) {
                throw new \Core\Exceptions\AuthMissing(self::class);
            }

            return new Response($this->pageFactory->renderPage($pageAdmin));
        } catch (Exception $exception) {
            return $this->getSystemPageFromException($exception);
        }
    }

    public function checked()
    {
        $data = $this->request->request->get('data');
        $checked = $this->request->request->get('checked') === 'true';

        if (!$data) {
            return JsonResponse::create(null, Response::HTTP_BAD_REQUEST);
        }
        $params = json_decode(base64_decode($data), true);

        if (!isset($params['class'], $params['id'], $params['fn'])) {
            return JsonResponse::create(null, Response::HTTP_BAD_REQUEST);
        }

        $controller = Loader::getInstance()->load('DI')->get($params['class']);

        $controller->{$params['fn']}($params['id'], $checked);
        return JsonResponse::create(null, Response::HTTP_NO_CONTENT);

    }
}