<?php
/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Gebtu;

class PageAssets
{
    /** array js variables */
    private $javascriptVariables = [];

    /** array required javascript files */
    private $requiredJavascript = [];

    /** array required css files */
    private $requiredCss = [];

    public function addCss($file, $attributes = [], $stage = 50, $cacheFix = true)
    {
        $this->requiredCss[(int)$stage][$file] = array(
            'value' => $file,
            'attributes' => $attributes,
            'cacheFix' => $cacheFix
        );
    }

    public function removeCss($file)
    {
        foreach ($this->requiredCss as $levelKey => &$level) {
            if (isset($this->requiredCss[$levelKey][$file])) {
                unset($this->requiredCss[$levelKey][$file]);
            }
        }
    }

    public function getCss()
    {
        ksort($this->requiredCss);
        $cssFiles = [];
        foreach ($this->requiredCss as $level) {
            $cssFiles = array_merge($cssFiles, $level);
        }
        return $cssFiles;
    }

    public function addJavascriptContent($key, $javascript, $stage = 50)
    {
        $this->requiredJavascript[(int)$stage][$key] = array(
            'type' => 'content',
            'value' => $javascript
        );
    }


    public function addJavascript($file, $attributes = [], $stage = 50, $cacheFix = true)
    {
        $this->requiredJavascript[(int)$stage][$file] = array(
            'type' => 'file',
            'value' => $file,
            'attributes' => $attributes,
            'cacheFix' => $cacheFix
        );
    }

    public function removeJavascript($file)
    {
        foreach ($this->requiredJavascript as $levelKey => &$level) {
            if (isset($this->requiredJavascript[$levelKey][$file]) && $this->requiredJavascript[$levelKey][$file]['type'] == 'file') {
                unset($this->requiredJavascript[$levelKey][$file]);
            }
        }
    }

    public function removeJavascriptContent($key)
    {
        foreach ($this->requiredJavascript as $levelKey => &$level) {
            if (isset($this->requiredJavascript[$levelKey][$key]) && $this->requiredJavascript[$levelKey][$key]['type'] == 'content') {
                unset($this->requiredJavascript[$levelKey][$key]);
            }
        }
    }

    public function getJavascript()
    {
        ksort($this->requiredJavascript);
        return $this->requiredJavascript;
    }

    public function addJavascriptVariable($name, $value)
    {
        $this->javascriptVariables[$name] = $value;
    }

    public function removeJavascriptVariable($name)
    {
        if (isset($this->javascriptVariables[$name])) {
            unset($this->javascriptVariables[$name]);
        }
    }

    public function getJavascriptVariables()
    {
        return $this->javascriptVariables;
    }

    public function generateHead()
    {
        $cacheVersion = $this->getCacheVersion();
        $cssFiles = $this->getCss();

        $inDesignPreview = false;

        $data = ipRequest()->getRequest();

        if (!empty($data['ipDesign']['pCfg']) || !empty($data['restoreDefault'])) {
            $inDesignPreview = \Demotic\Gebtu\Design\ConfigModel::instance()->isInPreviewState();
        }

        if ($inDesignPreview) {
            $themeAssetsUrl = ipThemeUrl(\Demotic\Application::ASSETS_DIR . '/');
            $designService = \Demotic\Gebtu\Design\Service::instance();
            $theme = ipConfig()->theme();

            foreach ($cssFiles as &$file) {
                if (strpos($file['value'], $themeAssetsUrl) === 0) {
                    $pathinfo = pathinfo($file['value']);

                    if ($pathinfo['extension'] == 'css'
                        && $themeAssetsUrl . $pathinfo['basename'] == $file['value']
                    ) {
                        $themeFile = \Demotic\Application::ASSETS_DIR . '/' . $pathinfo['filename'] . '.less';
                        if (file_exists(ipThemeFile($themeFile))) {
                            $file['value'] = $designService->getRealTimeUrl($theme, $themeFile);
                            $file['cacheFix'] = false;
                        }
                    }
                }

                if ($file['cacheFix']) {
                    $file['value'] .= (strpos($file['value'], '?') !== false ? '&' : '?') . $cacheVersion;
                }
            }
        } else {
            foreach ($cssFiles as &$file) {
                if ($file['cacheFix']) {
                    $file['value'] .= (strpos($file['value'], '?') !== false ? '&' : '?') . $cacheVersion;
                }
            }
        }

        $cssFiles = ipFilter('ipCss', $cssFiles);

        $response = ipResponse();
        $responseTitle = $response->getTitle();

        //If the $responseTitle is empty then probably we are in the admin backend or a route from a plugin's 'routes' file
        //Check for current module we are in Admin backend routes if we detect the request data is present. If not default we split the URL path and get the last part as our page title
        if(empty($responseTitle)){
            $requestData = \Demotic\ServiceLocator::request()->getRequest();
            $curModTitle = '';

            if(!empty($requestData)){
                if (!empty($requestData['aa'])) {
                    $parts = explode('.', $requestData['aa']);
                    $curModule = $parts[0];
                } else {
                    $curModule = "Content";
                }

                $responseTitle = 'Admin: '. $curModule;
            }else{
                $url = ipRequest()->getUrl();
                $parts = explode('/', $url);
                $last = array_pop($parts);
                $last = \Demotic\Gebtu\Text\Specialchars::url($last);
                $last = str_replace(array('-'), ' ', $last);
                $responseTitle = ucwords($last);
            }
        }

        $data = array(
            'title' => $responseTitle,
            'keywords' => $response->getKeywords(),
            'description' => $response->getDescription(),
            'favicon' => $response->getFavicon(),
            'charset' => $response->getCharset(),
            'css' => $cssFiles
        );

        $head = ipView('Demotic/Gebtu/Config/view/head.php', $data)->render();
        $head = ipFilter('ipHead', $head);
        return $head;
    }

    public function generateJavascript()
    {
        $cacheVersion = $this->getCacheVersion();
        $javascriptFiles = $this->getJavascript();
        $javascriptFilesSorted = [];
        foreach ($javascriptFiles as $level) {
            foreach ($level as &$file) {
                if ($file['type'] == 'file' && $file['cacheFix']) {
                    $file['value'] .= (strpos($file['value'], '?') !== false ? '&' : '?') . $cacheVersion;
                }
            }
            $javascriptFilesSorted = array_merge($javascriptFilesSorted, $level);
        }
        
        $revision = array('revisionId' => 0);
        if(!is_null($this->getCurrentRevision())){
            $revision = $this->getCurrentRevision();
        }

        $page = ipContent()->getCurrentPage();


        $javascriptFilesSorted = ipFilter('ipJs', $javascriptFilesSorted);


        $language = ipContent()->getCurrentLanguage();
        $data = array(
            'ip' => array(
                'baseUrl' => ipConfig()->baseUrl(),
                'safeMode' => \Demotic\Gebtu\Admin\Service::isSafeMode(),
                'languageId' => $language->getId(),
                'languageUrl' => $language->getLink(),
                'languageCode' => $language->getCode(),
                'languageTextDirection' => $language->getTextDirection(),
                'theme' => ipConfig()->theme(),
                'pageId' => $page ? $page->getId() : null,
                'revisionId' => $revision['revisionId'],
                'securityToken' => \Demotic\ServiceLocator::application()->getSecurityToken(),
                'developmentEnvironment' => ipConfig()->isDevelopmentEnvironment(),
                'debugMode' => ipconfig()->isDebugMode(),
                'isManagementState' => ipIsManagementState(),
                'isAdminState' => ipAdminId() ? 1 : 0,
                'isAdminNavbarDisabled' => ipRequest()->getQuery('disableAdminNavbar') ? 1 : 0,
                'gmapsApiKey' => ipGetOption('Config.gmapsApiKey')
            ),
            'javascriptVariables' => $this->getJavascriptVariables(),
            'javascript' => $javascriptFilesSorted,
        );
        $javascript = ipView('Demotic/Gebtu/Config/view/javascript.php', $data)->render();
        $javascript = ipFilter('ipJavaScript', $javascript);
        return $javascript;
    }

    protected function getCacheVersion()
    {
        return \Demotic\ServiceLocator::storage()->get('Demotic', 'cacheVersion', 1);
    }

    protected function getCurrentRevision()
    {
        return \Demotic\ServiceLocator::content()->getCurrentRevision();
    }

    public function removeAllCss()
    {
        $this->requiredCss = [];
    }

    public function removeAllJs()
    {
        $this->requiredJavascript = [];
    }

    public function removeAllJsVariables()
    {
        $this->javascriptVariables = [];
    }
}