<?php

namespace KupShop\KupShopBundle\Views;

use KupShop\KupShopBundle\Views\Traits\MessagesTrait;
use KupShop\KupShopBundle\Views\Traits\SecurityTrait;
use KupShop\KupShopBundle\Views\Traits\TemplateTrait;
use Symfony\Component\HttpFoundation\Request;

class BaseView extends \TemplateAccess
{
    use MessagesTrait;
    use SecurityTrait;
    use TemplateTrait;

    protected $title;

    private array $bodyVariables = [];

    public function getTemplateVariables()
    {
        $body = $this->getBodyVariables();
        if (!empty($this->bodyVariables) && is_array($body)) {
            $body = [...$this->bodyVariables, ...$body];
        }

        return [
            'view' => $this,
            'body' => $body,
            'header' => $this->getHeaderVariables(),
        ];
    }

    public function getBodyVariables()
    {
        return [
            'returnNav' => $this->getBreadcrumbs(),
        ];
    }

    public function addBodyVariables(array $data)
    {
        $this->bodyVariables = array_merge($this->bodyVariables, $data);

        return $this;
    }

    public function getHeaderVariables()
    {
        $dbcfg = \Settings::getDefault();
        $header = [
            'pageTitle' => $this->getMetaTitle().' - '.$dbcfg['shop_title'],
            'meta_keywords' => $this->getMetaKeywords(),
            'meta_description' => $this->getMetaDescription(),
            'robots' => (!$this->getShowInSearch() || !isLive()) ? 'noindex, nofollow' : 'index, follow',
            'canonical_url' => $this->useCanonicalUrl(),
        ];

        // Wpj Toolbar
        if (getAdminUser() || isLocalDevelopment()) {
            $header['wpjToolbar'] = $this->getWpjToolbar();
        }

        return $header;
    }

    public function getBreadcrumbs()
    {
        $title = $this->getTitle();
        if ($title) {
            return getReturnNavigation(-1, 'NO_TYPE', [$title]);
        } else {
            return null;
        }
    }

    public function getBreadcrumbsNew(): array
    {
        $breadcrumbs = $this->getBreadcrumbs() ?? [];
        if ($breadcrumbs && findModule(\Modules::COMPONENTS)) {
            return reset($breadcrumbs);
        }

        return $breadcrumbs;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getMetaTitle()
    {
        return $this->getTitle();
    }

    public function getShowInSearch(): bool
    {
        return true;
    }

    public function getMetaKeywords()
    {
        return null;
    }

    public function getMetaDescription()
    {
        return null;
    }

    public function getWpjToolbar()
    {
        $user = getAdminUser();

        if (isDevelopment()) {
            $user = \KupShop\KupShopBundle\Config::get()['Admin']['settings'];
        }

        if ($user) {
            global $cfg;
            $admin_url = getVal('admin_url', $cfg['Menu']['wpj_toolbar'], '/admin/');

            $toolBar = [
                'show' => true,
                'admin_url' => $admin_url,
                'user' => $user,
                'template' => null,
                'view' => null,
                'url' => null,
                'title' => null,
                'translateTitle' => null,
            ];

            $path = explode('\\', static::class);
            if (!empty($path)) {
                $toolBar['view'] = end($path);
            }
            try {
                $toolBar['template'] = $this->getTemplate();
            } catch (\Exception $e) {
            }

            // Blocek version
            $blocekVersion = getCache('blocek-version', $found);
            if (!$found) {
                $blocekVersion = glob('./web/blocek/bundle*.js');
                if ($blocekVersion) {
                    $blocekVersion = str_replace(['./web/blocek/bundle', '.js'], '', $blocekVersion[0]);
                } else {
                    $blocekVersion = '';
                }
                setCache('blocek-version', $blocekVersion);
            }
            $toolBar['blocek_version'] = $blocekVersion;

            $toolBar['tpl_theme'] = $cfg['Path']['smarty_tpl']['theme'] ?? '';

            return $toolBar;
        }

        return [];
    }

    /** @deprecated Not used in components, use getCanonicalUrl instead */
    protected function useCanonicalUrl()
    {
        return null;
    }

    public function getCanonicalUrl(Request $request)
    {
        $path = $request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo();

        // Hack? Maybe no ...
        if ($page = $request->query->get('page')) {
            $page = intval($page);
            if ($page > 1) {
                $path .= '?page='.$page;
            }
        }

        return $path;
    }
}
