<?php

require_once(dirname(__FILE__).'/../../DesignerTabSelf.php');

class AdminAjaxController extends ModuleAdminController
{
    public function initContent()
    {
        parent::initContent();
        if ($this->ajax)
            echo $this->ajaxProcessView();
        else
            $this->context->smarty->assign(array(
                'content' => $this->displayThemes(),
            ));
    }

    public function setMedia()
    {
        parent::setMedia();
        if (!$this->ajax)
            $this->addCSS(__PS_BASE_URI__ . 'modules/designer/css/style.css');
    }

    public function ajaxProcessView()
    {
        $themeName = Tools::getValue('theme_name', '');
        $project = getProject($themeName);
        $domain = Tools::getValue('domain', '');
        $baseUrl = Designer::getBaseUrlWithLastSlash();
        $moduleUrl = $baseUrl . 'modules/designer';		
        $adminDir = basename(_PS_ADMIN_DIR_);
        $isNew = isset($_GET["create_theme"]) ? $_GET["create_theme"] : 'false'; // for save and publish new theme
        $isActive = (_THEME_NAME_ === $themeName || $isNew === 'true') ? 'true' : 'false';
        $version = time();

        $data = json_encode(array(
            'domain' => $domain,
            'themeName' => $themeName,
            'templates' => getThemeTemplates($baseUrl, $themeName),
            'url' => getPSUrls($baseUrl, $themeName, $adminDir, $this->token, $domain),
            'ajax' => _PS_BASE_URL_.__PS_BASE_URI__ . $adminDir .'/index.php',
            'isActive' => $isActive,
            'isNew' => $isNew,
            'cmsVersion' => getThemeVersions(),
            'cssJsSources' => getThemeCache(getThemeDir($themeName)),
            'md5Hashes' => getThemeHashes(getThemeDir($themeName)),
            'project' => $project,
            'token' => $this->token
        ));
        $output = <<<EOT
<!DOCTYPE html>
<html>
<head>
    <title>Designer</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <script type="text/javascript">
        window.pluginData = $data;
    </script>
    <script type="text/javascript" src="$moduleUrl/DataProvider.js?version=$version"></script>
    <script type="text/javascript" src="$domain/loader/start.js?version=$version"></script>
</head>
<body>

</body>
</html>
EOT;
        return $output;
    }

    public function ajaxProcessUpdate()
    {
        $designer = $this->getDesignerObj();
        $response = $designer->update();
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessExport()
    {
        $data = isset($_POST['info']) ? $_POST['info'] : null;
        $designer = $this->getDesignerObj();
        $response = $designer->export($data);
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessSave()
    {
        $data = isset($_POST['info']) ? $_POST['info'] : null;
        $domain = isset($_POST['domain']) ? $_POST['domain'] : '';
        $isNew = isset($_POST['isNew']) && $_POST['isNew'] === 'true';
        $designer = $this->getDesignerObj();
        $response = $designer->save($data, $domain, $isNew);
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessPublish()
    {
        $designer = $this->getDesignerObj();
        $response = $designer->publish();
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessGetTheme()
    {
        $designer = $this->getDesignerObj();
        $userThemeName = isset($_POST['userThemeName']) ? $_POST['userThemeName'] : '';
        $response = $designer->getTheme($userThemeName);
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessRename()
    {
        $designer = $this->getDesignerObj();
        $newThemeName = isset($_POST['newThemeName']) ? $_POST['newThemeName'] : '';
        $response = $designer->rename($newThemeName);
        die(Tools::jsonEncode($response));
    }

    public function ajaxProcessClear()
    {
        $designer = $this->getDesignerObj();
        $response = $designer->chunkClear();
        die(Tools::jsonEncode($response));
    }

    private function getDesignerObj()
    {
        $themeName = Tools::getValue('themeName', '');
        if (empty($themeName))
            die('Empty theme name is invalid');
        
        return new DesignerTabSelf($themeName);
    }

    private function displayThemes()
    {
        $domain = Tools::getValue('domain');
        $baseUrl = Designer::getBaseUrlWithLastSlash();
        $themesUrl = $baseUrl . 'themes';

        $result = '';
        foreach (Theme::getAvailable(false) as $themeName)
        {
            if (strpos($themeName, _PREVIEW_SUFFIX_) !== FALSE) continue;

            $themeUrl = $themesUrl . '/' . $themeName;
            $result .= '<div class="theme-item">'
                    . '<div class="item-title"><h3>'.$themeName.'</h3></div>'
                    . '<div class="item-view"><img src="'.$themeUrl. '/preview.jpg" alt="'.$themeName.'"></div>';
            
            if (file_exists(getProjectPath($themeName))) // TODO: can be editted
            {
                $themeData = getProject($themeName);
                $dm = $domain;
                if (isset($themeData) && isset($themeData->domain))
                    $dm = $themeData->domain;
                
                $result .= '<div class="item-actions"><a id="'.$themeName.'" href="'.self::$currentIndex.'&ajax=1&token='.$this->token.'&theme_name='.$themeName.'&domain=' . urlencode($dm).'">Edit</a></div>';
            }
            $result .= '</div>';
        }
        
        $title = 'Themes List';
        $output = <<<EOF
<div class="theme-list">
<div class="theme-list-title">
    <h1>{$title}</h1>
<hr style="background-color: #812143;color: #812143;" />
</div>
<div id="theme-editor-list">{$result}</div>
EOF;
        return $output;
    }
}