<?php

include_once('defines.inc.php');
include_once(dirname(__FILE__).'/Export/EditorHelper.php');
include_once(dirname(__FILE__).'/Export/FilesHelper.php');

class Designer extends Module
{
    public function __construct()
    {
        $this->name = 'designer';
        $this->tab = 'administration';
        $this->version = '1.0';
        
        parent::__construct();

        $this->displayName = $this->l('Billion Designer');
        $this->description = $this->l('Billion Designer tool');
        $this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');		
    }

    public function install()
    {
        return parent::install() && $this->installAdminTab();
    }
    
    private function installAdminTab()
    {
        $parentTab = new Tab();
        $parentTab->name = 'Designer';
        $parentTab->class_name = 'DesignerTab';
        $parentTab->module = $this->name;
        $parentTab->id_parent = 0;
        $parentTab->add();
        
        $tab = new Tab();
        $tab->name = 'Designer';
        $tab->class_name = 'AdminAjax';
        $tab->module = $this->name;
        $tab->id_parent = Tab::getIdFromClassName('DesignerTab');
        return $tab->add();
    }

    public function uninstall()
    {
        return parent::uninstall() && $this->uninstallAdminTab();
    }
    
    private function uninstallAdminTab()
    {
        $parentTab = new Tab(Tab::getIdFromClassName('DesignerTab'));
        $tab = new Tab(Tab::getIdFromClassName('AdminAjax'));
        return $tab->delete() && $parentTab->delete();
    }

    public function getContent()
    {
        $context = Context::getContext();
        $token = Tools::getAdminToken('AdminAjax'.(int)Tab::getIdFromClassName('AdminAjax').(int)$context->employee->id);
        header('Location: index.php?controller=AdminAjax&token=' . $token);
        exit;
    }		
    
    /**
      * Return employee instance from its id
      *
      * @@param string $id_employee employee id
      * @@return Employee instance
      */
    public static function getEmployeeById($id_employee)
    {
        if (!Validate::isUnsignedId($id_employee))
            die (Tools::displayError());

        $result = Db::getInstance()->getRow('
        SELECT *
        FROM `'._DB_PREFIX_.'employee`
        WHERE `active` = 1
        AND `id_employee` = '.(int)$id_employee);
        if (!$result)
            return false;
        
        $employee = new Employee();
        $employee->id = $result['id_employee'];
        $employee->id_profile = $result['id_profile'];
        foreach ($result as $key => $value)
            if (property_exists($employee, $key))
                $employee->{$key} = $value;
        return $employee;
    }
    
    /*
     * Retrieves first child category of default one
     */
    public static function getFirstChildCategory()
    {
        $result = 0;
        $context = Context::getContext();
        $default_category = $context->shop->getCategory();
        $sql = 'SELECT MIN(`id_category`) AS id_category
            FROM `'._DB_PREFIX_.'category`
            WHERE `id_parent` = '.(int)$default_category;
        if ($id_category = Db::getInstance()->getValue($sql))
            $result = (int)$id_category;
        return $result;
    }
    
    public static function getBaseUrlWithLastSlash($url = '')
    {
        $baseUrl = empty($url) ? _PS_BASE_URL_.__PS_BASE_URI__ : $url;
        return $baseUrl . (substr($baseUrl, -1) !== '/' ? '/' : '');
    }
    
    public static function getDownloadUrl()
    {
        return self::getBaseUrlWithLastSlash() . 'download';
    }
    
    /*
     * Method generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9
     */
    public static function generateThemeName()
    {
        $pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $length = 10; // themeName length
        for ($s = '', $i = 0, $z = strlen($pattern)-1; $i < $length; $x = rand(0,$z), $s .= $pattern{$x}, $i++);
        return $s;
    }
    
    public static function setActiveThemeForShop($themeName)
    {
        $id_theme = Designer::getThemeId($themeName);
        if (!$id_theme) 
            $id_theme = Designer::addTheme($themeName);
        $context = Context::getContext();
        $shop = $context->shop;
        if ($id_theme && $shop->id_theme != $id_theme)
        {
            $shop->id_theme = $id_theme;
            $shop->update();
        }
        
        return $id_theme;
    }
    
    /*
     * Retrieves theme ID by name from database
     */
    public static function getThemeId($themeDir)
    {
        $result = 0;
        $sql = 'SELECT id_theme FROM `'._DB_PREFIX_.'theme`
            WHERE `directory` = \''.(string)$themeDir .'\'';
        if ($id_theme = Db::getInstance()->getValue($sql))
            $result = (int)$id_theme;
        return $result;
    }
    
    /*
     * Retrieves theme ID by name from database
     */
    public static function addTheme($themeName)
    {
        $sql = 'INSERT INTO `'._DB_PREFIX_.'theme` (`name`, `directory`) VALUES (\''.$themeName.'\', \''.$themeName.'\')';
        Db::getInstance()->execute($sql);
        return Db::getInstance()->Insert_ID();
    }
    
    /*
     * Retrieves theme ID by name from database
     */
    public static function deleteTheme($themeName)
    {
        $sql = 'DELETE FROM `'._DB_PREFIX_.'theme` WHERE name = \''.$themeName.'\'';
        if (!Db::getInstance()->execute($sql))
            return false;
    }
    
    /*
     * Method similar to another one in modules/blockcategories/blockcategories.php
     */
    private static function getTree($resultParents, $resultIds, $maxDepth, $id_category = null, $currentDepth = 0)
    {
        $context = Context::getContext();
        if (is_null($id_category))
            $id_category = $context->shop->getCategory();

        $children = array();
        if (isset($resultParents[$id_category]) && count($resultParents[$id_category]) && ($maxDepth == 0 || $currentDepth < $maxDepth))
            foreach ($resultParents[$id_category] as $subcat)
                $children[] = Designer::getTree($resultParents, $resultIds, $maxDepth, $subcat['id_category'], $currentDepth + 1);
        if (!isset($resultIds[$id_category]))
            return false;
        $return = array('id' => $id_category, 'link' => $context->link->getCategoryLink($id_category, $resultIds[$id_category]['link_rewrite']),
                     'name' => $resultIds[$id_category]['name'], 'desc'=> $resultIds[$id_category]['description'],
                     'children' => $children);
        return $return;
    }

    /*
     * Method used to build horizontal menu similar to vertical menu for categories
     */
    public static function buildCategoryMenu()
    {
        global $cookie;
        $context = Context::getContext();
        $id_customer = (int)$cookie->id_customer;
        // Get all groups for this customer and concatenate them as a string: "1,2,3..."
        // It is necessary to keep the group query separate from the main select query because it is used for the cache
        $groups = $id_customer ? implode(', ', Customer::getGroupsStatic($id_customer)) : Configuration::get('PS_UNIDENTIFIED_GROUP');
        $id_product = (int)Tools::getValue('id_product', 0);
        $id_category = (int)Tools::getValue('id_category', 0);
        $id_lang = (int)$cookie->id_lang;
        $smartyCacheId = 'blockcategories|'.$context->shop->id.'_'.$groups.'_'.$id_lang.'_'.$id_product.'_'.$id_category;
        $context->smarty->cache_lifetime = 31536000; // 1 Year
        Tools::enableCache();
        
        $templatePath = _PS_THEME_DIR_.'modules/blockcategories/blockcategories-hmenu.tpl';
        $isCached = $context->smarty->isCached($templatePath, $smartyCacheId, null);
        if (!$isCached)
        {
            $maxdepth = Configuration::get('BLOCK_CATEG_MAX_DEPTH');
            if (!$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
                SELECT c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite
                FROM `'._DB_PREFIX_.'category` c
                INNER JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = '.$id_lang.Shop::addSqlRestrictionOnLang('cl').')
                INNER JOIN `'._DB_PREFIX_.'category_shop` cs ON (cs.`id_category` = c.`id_category` AND cs.`id_shop` = '.(int)$context->shop->id.')
                WHERE (c.`active` = 1 OR c.`id_category` = '.(int)Configuration::get('PS_HOME_CATEGORY').')
                AND c.`id_category` != '.(int)Configuration::get('PS_ROOT_CATEGORY').'
                '.((int)$maxdepth != 0 ? ' AND `level_depth` <= '.(int)$maxdepth : '').'
                AND c.id_category IN (SELECT id_category FROM `'._DB_PREFIX_.'category_group` WHERE `id_group` IN ('.pSQL($groups).'))
                ORDER BY `level_depth` ASC, '.(Configuration::get('BLOCK_CATEG_SORT') ? 'cl.`name`' : 'cs.`position`').' '.(Configuration::get('BLOCK_CATEG_SORT_WAY') ? 'DESC' : 'ASC')))
                return Tools::restoreCacheSettings();

            $resultParents = array();
            $resultIds = array();

            foreach ($result as &$row)
            {
                $resultParents[$row['id_parent']][] = &$row;
                $resultIds[$row['id_category']] = &$row;
            }

            $blockCategTree = Designer::getTree($resultParents, $resultIds, Configuration::get('BLOCK_CATEG_MAX_DEPTH'));
            unset($resultParents, $resultIds);

            $isDhtml = (Configuration::get('BLOCK_CATEG_DHTML') == 1 ? true : false);
            if (Tools::isSubmit('id_category'))
            {
                $context->cookie->last_visited_category = $id_category;
                $context->smarty->assign('currentCategoryId', $context->cookie->last_visited_category);
            }
            if (Tools::isSubmit('id_product'))
            {
                if (!isset($context->cookie->last_visited_category)
                    || !Product::idIsOnCategoryId($id_product, array('0' => array('id_category' => $context->cookie->last_visited_category)))
                    || !Category::inShopStatic($context->cookie->last_visited_category, $context->shop))
                {
                    $product = new Product($id_product);
                    if (isset($product) && Validate::isLoadedObject($product))
                        $context->cookie->last_visited_category = (int)$product->id_category_default;
                }
                $context->smarty->assign('currentCategoryId', (int)$context->cookie->last_visited_category);
            }
            $context->smarty->assign('blockCategTreeHMenu', $blockCategTree);
        }

        Tools::restoreCacheSettings();
        return;
    }
}
