<?php
/**
* 2017-2019 PSBlog
*
* NOTICE OF LICENSE
*
* READ ATTACHED LICENSE.TXT
*
*  @author    PSBlog
*  @copyright 2017-2019 PSBlog
*  @license   LICENSE.TXT
*/

if (!defined('_PS_VERSION_')) {
    exit;
}

class Prestarcards extends Module
{
    protected $config_form = false;

    public function __construct()
    {
        $this->name = 'prestarcards';
        $this->tab = 'seo';
        $this->version = '1.8.2';
        $this->author = 'PSBlog';
        $this->need_instance = 0;
        $this->module_key = '354c477d98b5f3a1480bc812c3ed7d4b';
        $this->controllers = array(
            'ajxpetitions'
        );

        /**
         * Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
         */
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Google Rich Cards LD-JSON + Twitter Cards');
        $this->description = $this->l('Insert automatically LD-JSON rich cards for Google into your shop');
    }

    /**
     * Don't forget to create update methods if needed:
     * http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
     */
    public function install()
    {
        // General Options
        Configuration::updateValue('PSB_RICHCARDS_SECUREKEY', md5(uniqid(rand(), true)));
        Configuration::updateValue('PSB_RICHCARDS_PRODUCT', true);
        Configuration::updateValue('PSB_RICHCARDS_PRODUCT_CAT', true);
        Configuration::updateValue('PSB_RICHCARDS_BREAD', true);
        Configuration::updateValue('PSB_RICHCARDS_RATING', false);
        Configuration::updateValue('PSB_RICHCARDS_WEBSITE', true);
        Configuration::updateValue('PSB_RICHCARDS_STORE', true);
        Configuration::updateValue('PSB_RICHCARDS_RANGE', 3);
        Configuration::updateValue('PSB_RICHCARDS_TWITTER', false);
        Configuration::updateValue('PSB_RICHCARDS_TWITTER_CAT', false);
        Configuration::updateValue('PSB_RICHCARDS_TW_USER', '');
        Configuration::updateValue('PSB_RICHCARDS_HREF', true);
        Configuration::updateValue('PSB_RICHCARDS_STORETYPE', 1);
        Configuration::updateValue('PSB_RICHCARDS_IGNOREROOT', false);
        Configuration::updateValue('PSB_RICHCARDS_YOTPO_API', '');
        Configuration::updateValue('PSB_RICHCARDS_CANONICAL_INDEX', false);
        // Website Validation
        Configuration::updateValue('PSB_RICHCARDS_TAGWT', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGBING', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGYANDEX', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGALEXA', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGNORTON', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGWOT', '');
        Configuration::updateValue('PSB_RICHCARDS_TAGPINTEREST', '');
        // Social Media
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_FB', '');
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_PLUS', '');
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_IG', '');
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_YT', '');
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_MYS', '');
        Configuration::updateValue('PSB_RICHCARDS_SOCIAL_LINKED', '');
        
        return parent::install() &&
            $this->registerHook('backOfficeHeader') &&
            $this->registerHook('displayHeader') &&
            $this->registerHook('displayFooter');
    }

    public function uninstall()
    {
        // Options
        Configuration::deleteByName('PSB_RICHCARDS_SECUREKEY');
        Configuration::deleteByName('PSB_RICHCARDS_PRODUCT');
        Configuration::deleteByName('PSB_RICHCARDS_PRODUCT_CAT');
        Configuration::deleteByName('PSB_RICHCARDS_BREAD');
        Configuration::deleteByName('PSB_RICHCARDS_RATING');
        Configuration::deleteByName('PSB_RICHCARDS_WEBSITE');
        Configuration::deleteByName('PSB_RICHCARDS_STORE');
        Configuration::deleteByName('PSB_RICHCARDS_RANGE');
        Configuration::deleteByName('PSB_RICHCARDS_TWITTER');
        Configuration::deleteByName('PSB_RICHCARDS_TWITTER_CAT');
        Configuration::deleteByName('PSB_RICHCARDS_TW_USER');
        Configuration::deleteByName('PSB_RICHCARDS_HREF');
        Configuration::deleteByName('PSB_RICHCARDS_STORETYPE');
        Configuration::deleteByName('PSB_RICHCARDS_IGNOREROOT');
        Configuration::deleteByName('PSB_RICHCARDS_YOTPO_API');
        // Validation
        Configuration::deleteByName('PSB_RICHCARDS_TAGWT');
        Configuration::deleteByName('PSB_RICHCARDS_TAGBING');
        Configuration::deleteByName('PSB_RICHCARDS_TAGYANDEX');
        Configuration::deleteByName('PSB_RICHCARDS_TAGALEXA');
        Configuration::deleteByName('PSB_RICHCARDS_TAGNORTON');
        Configuration::deleteByName('PSB_RICHCARDS_TAGWOT');
        Configuration::deleteByName('PSB_RICHCARDS_TAGPINTEREST');
        // Social Media
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_FB');
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_PLUS');
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_IG');
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_YT');
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_MYS');
        Configuration::deleteByName('PSB_RICHCARDS_SOCIAL_LINKED');
        // Advanced
        Configuration::deleteByName('PSB_RICHCARDS_PREFETCH');
        Configuration::deleteByName('PSB_RICHCARDS_PRECONNECT');
        Configuration::deleteByName('PSB_RICHCARDS_CANONICAL_INDEX');
        
        return parent::uninstall();
    }

    /**
     * Load the configuration form
     */
    public function getContent()
    {
        $status = '';
        if (Tools::isSubmit('submitRichConfig') || Tools::isSubmit('submitRichConfigValidation') ||
        Tools::isSubmit('submitRichConfigSocial') || Tools::isSubmit('submitRichConfigPrefetch')) {
            $status = $this->postProcess();
        }
        
        $is17 = version_compare(_PS_VERSION_, '1.7', '>=') ? true : false;
        $link = new Link();
                
        $this->context->smarty->assign(array(
            'module_dir' => $this->_path,
            'module_version' => $this->version,
            'helper_form_1' => $this->renderForm(),
            'helper_form_2' => $this->renderFormValidation(),
            'helper_form_3' => $this->renderFormSocial(),
            'helper_form_4' => $this->renderFormSEO(),
            'theme_folder' => _PS_THEME_DIR_,
            'modules_folder' => _PS_MODULE_DIR_,
            'security' => Configuration::get('PSB_RICHCARDS_SECUREKEY'),
            'is17' => $is17,
            'index_url' => $link->getPageLink('index')
        ));

        // If 1.5
        $output = '';
        $is_old = version_compare(_PS_VERSION_, '1.6', '<') ? true : false;
        if ($is_old) {
            $output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure_15.tpl');
        } else {
            $output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
        }
        

        return $status.$output;
    }

    /**
     * Create the form that will be displayed in the configuration of your module.
     */
    protected function renderForm()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitRichConfig';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigForm()));
    }

    /**
     * Create the form that will be displayed in the configuration of your module.
     */
    protected function renderFormValidation()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitRichConfigValidation';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValuesValidation(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigFormValidation()));
    }

    /**
     * Create the form that will be displayed in the configuration of your module.
     */
    protected function renderFormSocial()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitRichConfigSocial';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValuesSocial(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigFormSocial()));
    }
    
    /**
     * Create the form that will be displayed in the configuration of your module.
     */
    protected function renderFormSEO()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitRichConfigPrefetch';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
            .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValuesPrefetch(), /* Add values for your inputs */
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigFormPrefetch()));
    }

    /**
     * Create the structure of your form.
     */
    protected function getConfigForm()
    {
        // Compatibility with 1.5
        $is_old = version_compare(_PS_VERSION_, '1.6', '<') ? true : false;
        $radio_switch = $is_old ? 'radio' : 'switch';

        $options_range = array(
            array(
                'id_option' => 1,
                'name' => $this->l('Inexpensive, usually $10 and under')
            ),
            array(
                'id_option' => 2,
                'name' => $this->l('Moderately expensive, usually between $10-$25')
            ),
            array(
                'id_option' => 3,
                'name' => $this->l('Expensive, usually between $25-$45')
            ),
            array(
                'id_option' => 4,
                'name' => $this->l('Very Expensive, usually $50 and up')
            ),
        );

        // Card Type
        // https://docs.google.com/spreadsheets/d/1Ed6RmI01rx4UdW40ciWgz2oS_Kx37_-sPi7sba_jC3w/edit#gid=0

        $array_business = $this->getArrayBusiness();
        array_unshift($array_business, 'LocalBusiness');
        
        $options_type_business = array();
        foreach ($array_business as $index => $business_type) {
            $options_type_business[] = array(
                'id_option' => $index+1,
                'name' => $business_type
            );
        }
        
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Settings'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Product Rich Cards'),
                        'id' => 'activateproduct',
                        'class' => 't',
                        'name' => 'activateproduct',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Rich Card generation.'),
                        'values' => array(
                            array(
                                'id' => 'activateproduct_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activateproduct_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Category Product Rich Cards'),
                        'id' => 'activateproductcat',
                        'class' => 't',
                        'name' => 'activateproductcat',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Rich Card generation into category page.'),
                        'values' => array(
                            array(
                                'id' => 'activateproductcat_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activateproductcat_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Ratings on Product'),
                        'id' => 'activateproductrating',
                        'class' => 't',
                        'name' => 'activateproductrating',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable "AggregateRating" for product Card.'),
                        'values' => array(
                            array(
                                'id' => 'activateproductrating_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activateproductrating_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Yotpo App Key'),
                        'id' => 'yotpoappkey',
                        'class' => 't',
                        'name' => 'yotpoappkey',
                        'desc' => $this->l('Your App identifier for Yotpo. Used for "AggregateRating".'),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Product Breadcrumb'),
                        'id' => 'activateproductbread',
                        'class' => 't',
                        'name' => 'activateproductbread',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable "BreadCrumbList" Rich Card generation.'),
                        'values' => array(
                            array(
                                'id' => 'activateproductbread_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activateproductbread_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Ignore root category/ies'),
                        'id' => 'activateignoreroot',
                        'class' => 't',
                        'name' => 'activateignoreroot',
                        'is_bool' => true,
                        'desc' => $this->l('Bypass root category on BreadCrumb.'),
                        'values' => array(
                            array(
                                'id' => 'activateignoreroot_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activateignoreroot_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Store/s Rich Cards'),
                        'id' => 'activatestore',
                        'class' => 't',
                        'name' => 'activatestore',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Rich Cards generation into stores page.'),
                        'values' => array(
                            array(
                                'id' => 'activatestore_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activatestore_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Store Type'),
                        'class' => 't',
                        'name' => 'storetype',
                        'desc' => $this->l('Type of Schema used to identify your shop type.'),
                        'options' => array(
                                'id' => 'id_option',
                                'query' => $options_type_business,
                                'name' => 'name',
                        )
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Website and Webpage Rich Card'),
                        'id' => 'activatewebsite',
                        'class' => 't',
                        'name' => 'activatewebsite',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Rich Card generation into index page.'),
                        'values' => array(
                            array(
                                'id' => 'activatewebsite_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activatewebsite_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'label' => $this->l('Price Range'),
                        'class' => 't',
                        'name' => 'pricerange',
                        'desc' => $this->l('Range of prices of your shop. Needed for Google.'),
                        'options' => array(
                                'id' => 'id_option',
                                'query' => $options_range,
                                'name' => 'name',
                            )
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Hreflang Tags'),
                        'id' => 'activatehref',
                        'class' => 't',
                        'name' => 'activatehref',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable international SEO with hreflang tags.'),
                        'values' => array(
                            array(
                                'id' => 'activatehref_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activatehref_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Twitter Card'),
                        'id' => 'activatetwitter',
                        'class' => 't',
                        'name' => 'activatetwitter',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Twitter Card generation.'),
                        'values' => array(
                            array(
                                'id' => 'activatetwitter_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activatetwitter_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Category Twitter Card'),
                        'id' => 'activatetwittercat',
                        'class' => 't',
                        'name' => 'activatetwittercat',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable Twitter Card generation for category page.'),
                        'values' => array(
                            array(
                                'id' => 'activatetwittercat_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'activatetwittercat_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Twitter username'),
                        'id' => 'twitterusername',
                        'prefix' => '@',
                        'name' => 'twitterusername',
                        'desc' => $this->l('Your Twitter username without @.'),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }

    /**
     * Create the structure of your form.
     */
    protected function getConfigFormValidation()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('WebSite Validation'),
                'icon' => 'icon-check',
                ),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->l('Google Site Verification'),
                        'id' => 'tagwebmaster',
                        'name' => 'tagwebmaster',
                        'desc' => $this->l('Adds your code to validate into Webmaster Tools.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Bing Site Verification'),
                        'id' => 'bing',
                        'name' => 'bing',
                        'desc' => $this->l('Adds your code to validate into Bing.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Yandex Site Verification'),
                        'id' => 'yandex',
                        'name' => 'yandex',
                        'desc' => $this->l('Adds your code to validate into Yandex.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Alexa Site Verification'),
                        'id' => 'alexa',
                        'name' => 'alexa',
                        'desc' => $this->l('Adds your code to validate into Alexa.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Norton Site Verification'),
                        'id' => 'norton',
                        'name' => 'norton',
                        'desc' => $this->l('Adds your code to validate into Norton.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('WOT Site Verification'),
                        'id' => 'wot',
                        'name' => 'wot',
                        'desc' => $this->l('Adds your code to validate into WOT.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Pinterest Site Verification'),
                        'id' => 'pinterest',
                        'name' => 'pinterest',
                        'desc' => $this->l('Adds your code to validate into Pinterest.'),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }
    
    /**
     * Create the structure of your form.
     */
    protected function getConfigFormSocial()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Social Media'),
                'icon' => 'icon-bullhorn',
                ),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->l('Facebook Profile'),
                        'id' => 'facebook',
                        'name' => 'facebook',
                        'desc' => $this->l('Link to your Facebook profile. Used into Organization tag.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Google Plus Profile'),
                        'id' => 'googleplus',
                        'name' => 'googleplus',
                        'desc' => $this->l('Link to your Google Plus profile. Used into Organization tag.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Instagram Profile'),
                        'id' => 'instagram',
                        'name' => 'instagram',
                        'desc' => $this->l('Link to your Instagram profile. Used into Organization tag.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Youtube Channel'),
                        'id' => 'youtube',
                        'name' => 'youtube',
                        'desc' => $this->l('Link to your Youtube channel. Used into Organization tag.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Myspace Profile'),
                        'id' => 'myspace',
                        'name' => 'myspace',
                        'desc' => $this->l('Link to your Myspace profile. Used into Organization tag.'),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('LinkedIn Profile'),
                        'id' => 'linkedin',
                        'name' => 'linkedin',
                        'desc' => $this->l('Link to your LinkedIn profile. Used into Organization tag.'),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }
    
    /**
     * Create the structure of your form.
     */
    protected function getConfigFormPrefetch()
    {
        // Compatibility with 1.5
        $is_old = version_compare(_PS_VERSION_, '1.6', '<') ? true : false;
        $radio_switch = $is_old ? 'radio' : 'switch';
    
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Advanced SEO'),
                'icon' => 'icon-rocket',
                ),
                'input' => array(
                    array(
                        'type' => $radio_switch,
                        'label' => $this->l('Canonical on Index'),
                        'id' => 'canonical_index',
                        'class' => 't',
                        'name' => 'canonical_index',
                        'is_bool' => true,
                        'desc' => $this->l('Enable or disable canonical tag on index page.'),
                        'values' => array(
                            array(
                                'id' => 'canonical_index_on',
                                'value' => true,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'canonical_index_off',
                                'value' => false,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'textarea',
                        'label' => $this->l('DNS Prefetch'),
                        'id' => 'dnsprefetch',
                        'name' => 'dnsprefetch',
                        'desc' => $this->l('List of hosts to prefetch. One per line.'),
                        'hint' => $this->l('Format: facebook.com (no http or https prefixes)'),
                    ),
                    array(
                        'type' => 'textarea',
                        'label' => $this->l('Preconnect Hosts'),
                        'id' => 'preconnect',
                        'name' => 'preconnect',
                        'desc' => $this->l('List of hosts to preconnect. One per line.'),
                        'hint' => $this->l('Format: facebook.com (no http or https prefixes)'),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }

    /**
     * Set values for the inputs.
     */
    protected function getConfigFormValues()
    {
        return array(
            'activateproduct' => Configuration::get('PSB_RICHCARDS_PRODUCT'),
            'activateproductcat' => Configuration::get('PSB_RICHCARDS_PRODUCT_CAT'),
            'activateproductbread' => Configuration::get('PSB_RICHCARDS_BREAD'),
            'activateignoreroot' => Configuration::get('PSB_RICHCARDS_IGNOREROOT'),
            'activateproductrating' => Configuration::get('PSB_RICHCARDS_RATING'),
            'yotpoappkey' => Configuration::get('PSB_RICHCARDS_YOTPO_API'),
            'activatewebsite' => Configuration::get('PSB_RICHCARDS_WEBSITE'),
            'activatestore' => Configuration::get('PSB_RICHCARDS_STORE'),
            'pricerange' => Configuration::get('PSB_RICHCARDS_RANGE'),
            'storetype' => Configuration::get('PSB_RICHCARDS_STORETYPE'),
            'activatetwitter' => Configuration::get('PSB_RICHCARDS_TWITTER'),
            'activatetwittercat' => Configuration::get('PSB_RICHCARDS_TWITTER_CAT'),
            'twitterusername' => Configuration::get('PSB_RICHCARDS_TW_USER'),
            'activatehref' => Configuration::get('PSB_RICHCARDS_HREF'),
        );
    }

    /**
     * Set values for the inputs.
     */
    protected function getConfigFormValuesValidation()
    {
        return array(
            'tagwebmaster' => Configuration::get('PSB_RICHCARDS_TAGWT'),
            'bing' => Configuration::get('PSB_RICHCARDS_TAGBING'),
            'yandex' => Configuration::get('PSB_RICHCARDS_TAGYANDEX'),
            'alexa' => Configuration::get('PSB_RICHCARDS_TAGALEXA'),
            'norton' => Configuration::get('PSB_RICHCARDS_TAGNORTON'),
            'wot' => Configuration::get('PSB_RICHCARDS_TAGWOT'),
            'pinterest' => Configuration::get('PSB_RICHCARDS_TAGPINTEREST'),
        );
    }

    /**
     * Set values for the inputs.
     */
    protected function getConfigFormValuesSocial()
    {
        return array(
            'facebook' => Configuration::get('PSB_RICHCARDS_SOCIAL_FB'),
            'googleplus' => Configuration::get('PSB_RICHCARDS_SOCIAL_PLUS'),
            'instagram' => Configuration::get('PSB_RICHCARDS_SOCIAL_IG'),
            'youtube' => Configuration::get('PSB_RICHCARDS_SOCIAL_YT'),
            'myspace' => Configuration::get('PSB_RICHCARDS_SOCIAL_MYS'),
            'linkedin' => Configuration::get('PSB_RICHCARDS_SOCIAL_LINKED'),
        );
    }

    /**
     * Set values for the inputs.
     */
    protected function getConfigFormValuesPrefetch()
    {
        // Prefetch
        $hosts_array = explode(';', Configuration::get('PSB_RICHCARDS_PREFETCH'));
        $hosts = implode("\n", $hosts_array);
        // Preconnect
        $hosts_array_preconnect = explode(';', Configuration::get('PSB_RICHCARDS_PRECONNECT'));
        $hosts_preconnect = implode("\n", $hosts_array_preconnect);
        // Canonical on index
        $canonical_index = Configuration::get('PSB_RICHCARDS_CANONICAL_INDEX');
        
        return array(
            'dnsprefetch' => $hosts,
            'preconnect' => $hosts_preconnect,
            'canonical_index' => $canonical_index,
        );
    }
    
    /**
     * Save form data.
     */
    protected function postProcess()
    {
        $message = '';
        
        if (Tools::isSubmit('submitRichConfig')) {
            // Bool values are forced, not validation needed
            $activateproduct = (bool)Tools::getValue('activateproduct');
            Configuration::updateValue('PSB_RICHCARDS_PRODUCT', $activateproduct);

            $activateproductcat = (bool)Tools::getValue('activateproductcat');
            Configuration::updateValue('PSB_RICHCARDS_PRODUCT_CAT', $activateproductcat);
            
            $activateproductbread = (bool)Tools::getValue('activateproductbread');
            Configuration::updateValue('PSB_RICHCARDS_BREAD', $activateproductbread);
            
            $activateignoreroot = (bool)Tools::getValue('activateignoreroot');
            Configuration::updateValue('PSB_RICHCARDS_IGNOREROOT', $activateignoreroot);
            
            // Yotpo API and Secret, can be letters and numbers
            $yotpoappkey = Tools::getValue('yotpoappkey');
            if (Validate::isLabel($yotpoappkey)) {
                Configuration::updateValue('PSB_RICHCARDS_YOTPO_API', $yotpoappkey);
            }

            $activateproductrating = (bool)Tools::getValue('activateproductrating');
            Configuration::updateValue('PSB_RICHCARDS_RATING', $activateproductrating);
            
            // Check for ratings
            if (!$activateproduct && $activateproductrating) {
                // Disable ratings if product is also disabled
                $message .= $this->displayError($this->l('Ratings needs Product Rich Cards to be enabled.'));
                Configuration::updateValue('PSB_RICHCARDS_RATING', false);
            }
            
            // Check for gsnippetsreviews
            if ($activateproductrating && (!Module::isEnabled('gsnippetsreviews') &&
            !Module::isEnabled('productcomments'))) {
                if (Tools::strlen($yotpoappkey) <= 0) {
                    $error_message = 'Ratings needs "productcomments" or "gsnippetsreviews" module to be installed.';
                    $error_message .= 'Yotpo API key also can be a valid option.';
                    $message .= $this->displayError($this->l($error_message));
                    Configuration::updateValue('PSB_RICHCARDS_RATING', false);
                }
            }
                        
            $activatewebsite = (bool)Tools::getValue('activatewebsite');
            Configuration::updateValue('PSB_RICHCARDS_WEBSITE', $activatewebsite);
            
            $activatestore = (bool)Tools::getValue('activatestore');
            Configuration::updateValue('PSB_RICHCARDS_STORE', $activatestore);
            
            $activatehref = (bool)Tools::getValue('activatehref');
            Configuration::updateValue('PSB_RICHCARDS_HREF', $activatehref);
            
            // Twitter Options
            $activatetwitter = (bool)Tools::getValue('activatetwitter');
            //$wasactive = (bool)Configuration::get('PSB_RICHCARDS_TWITTER');
            Configuration::updateValue('PSB_RICHCARDS_TWITTER', $activatetwitter);
            
            $activatetwittercat = (bool)Tools::getValue('activatetwittercat');
            Configuration::updateValue('PSB_RICHCARDS_TWITTER_CAT', $activatetwittercat);
            
            $twitterusername = Tools::getValue('twitterusername');
            
            if ($activatetwitter && Validate::isLabel($twitterusername) && Tools::strlen($twitterusername) > 0) {
                Configuration::updateValue('PSB_RICHCARDS_TW_USER', $twitterusername);
            } else {
                if (!Validate::isLabel($twitterusername) || Tools::strlen($twitterusername) == 0 && $activatetwitter) {
                    $message .= $this->displayError($this->l('Invalid Twitter username. Twitter Cards disabled.'));
                    Configuration::updateValue('PSB_RICHCARDS_TWITTER', false);
                    Configuration::updateValue('PSB_RICHCARDS_TWITTER_CAT', false);
                }
            }
            
            $pricerange = Tools::getValue('pricerange');
            if (!Validate::isInt($pricerange)) {
                $message .= $this->displayError($this->l('PriceRange must be a value from the list.'));
            } else {
                Configuration::updateValue('PSB_RICHCARDS_RANGE', (int)$pricerange);
            }

            $storetype = Tools::getValue('storetype');
            if (!Validate::isInt($storetype)) {
                $message .= $this->displayError($this->l('Type of store must be a value from the list.'));
            } else {
                Configuration::updateValue('PSB_RICHCARDS_STORETYPE', (int)$storetype);
            }
        } elseif (Tools::isSubmit('submitRichConfigValidation')) {
            // Google Webmaster Tool Verification code
            $tagwebmaster = Tools::getValue('tagwebmaster');
            if (Validate::isLabel($tagwebmaster)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGWT', $tagwebmaster);
            }

            // Bing Verification code
            $bing = Tools::getValue('bing');
            if (Validate::isLabel($bing)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGBING', trim($bing));
            }

            // Yandex Verification code
            $yandex = Tools::getValue('yandex');
            if (Validate::isLabel($yandex)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGYANDEX', trim($yandex));
            }
            
            // Alexa Verification code
            $alexa = Tools::getValue('alexa');
            if (Validate::isLabel($alexa)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGALEXA', trim($alexa));
            }

            // Norton Verification code
            $norton = Tools::getValue('norton');
            if (Validate::isLabel($norton)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGNORTON', trim($norton));
            }
            
            // WOT Verification code
            $wot = Tools::getValue('wot');
            if (Validate::isLabel($wot)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGWOT', trim($wot));
            }

            // Pinterest Verification code
            $pinterest = Tools::getValue('pinterest');
            if (Validate::isLabel($pinterest)) {
                Configuration::updateValue('PSB_RICHCARDS_TAGPINTEREST', $pinterest);
            }
        } elseif (Tools::isSubmit('submitRichConfigSocial')) {
            // Social Media
            // Facebook
            $facebook = Tools::getValue('facebook');
            if (Validate::isLabel($facebook) && Validate::isUrl($facebook)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_FB', $facebook);
            } elseif (Validate::isLabel($facebook) && Tools::strlen($facebook) > 0) {
                $message .= $this->displayError($this->l('Facebook profile must be a valid URL.'));
            }
            // Google+
            $googleplus = Tools::getValue('googleplus');
            if (Validate::isLabel($googleplus) && Validate::isUrl($googleplus)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_PLUS', $googleplus);
            } elseif (Validate::isLabel($googleplus) && Tools::strlen($googleplus) > 0) {
                $message .= $this->displayError($this->l('Google+ profile must be a valid URL.'));
            }
            // Instagram
            $instagram = Tools::getValue('instagram');
            if (Validate::isLabel($instagram) && Validate::isUrl($instagram)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_IG', $instagram);
            } elseif (Validate::isLabel($instagram) && Tools::strlen($instagram) > 0) {
                $message .= $this->displayError($this->l('Instagram profile must be a valid URL.'));
            }
            // Youtube
            $youtube = Tools::getValue('youtube');
            if (Validate::isLabel($youtube) && Validate::isUrl($youtube)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_YT', $youtube);
            } elseif (Validate::isLabel($youtube) && Tools::strlen($youtube) > 0) {
                $message .= $this->displayError($this->l('YouTube channel must be a valid URL.'));
            }
            // Myspace
            $myspace = Tools::getValue('myspace');
            if (Validate::isLabel($myspace) && Validate::isUrl($myspace)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_MYS', $myspace);
            } elseif (Validate::isLabel($myspace) && Tools::strlen($myspace) > 0) {
                $message .= $this->displayError($this->l('Myspace profile must be a valid URL.'));
            }
            // LinkedIn
            $linkedin = Tools::getValue('linkedin');
            if (Validate::isLabel($linkedin) && Validate::isUrl($linkedin)) {
                Configuration::updateValue('PSB_RICHCARDS_SOCIAL_LINKED', $linkedin);
            } elseif (Validate::isLabel($linkedin) && Tools::strlen($linkedin) > 0) {
                $message .= $this->displayError($this->l('LinkedIn profile must be a valid URL.'));
            }
        } elseif (Tools::isSubmit('submitRichConfigPrefetch')) {
            // Advanced SEO
            
            //Prefetch
            $dns_hosts = Tools::getValue('dnsprefetch');
            $valid_hosts = array();

            if (Tools::strlen(trim($dns_hosts)) > 0) {
                // For each new line (valid for \r\n and for \n for differents browsers)
                foreach (preg_split("/((\r?\n)|(\r\n?))/", $dns_hosts) as $host) {
                    // Validate each hostname
                    if (self::isHost($host)) {
                        $valid_hosts[] = $host;
                    }
                }
                $dns_hosts = implode(';', $valid_hosts);
                Configuration::updateValue('PSB_RICHCARDS_PREFETCH', $dns_hosts);
            }
            
            // Preconnect
            $preconnect_hosts = Tools::getValue('preconnect');
            $valid_hosts = array();

            if (Tools::strlen(trim($preconnect_hosts)) > 0) {
                // For each new line (valid for \r\n and for \n for differents browsers)
                foreach (preg_split("/((\r?\n)|(\r\n?))/", $preconnect_hosts) as $host) {
                    // Validate each hostname
                    if (self::isHost($host)) {
                        $valid_hosts[] = $host;
                    }
                }
                $preconnect_hosts = implode(';', $valid_hosts);
                Configuration::updateValue('PSB_RICHCARDS_PRECONNECT', $preconnect_hosts);
            }
            
            // Canonical index
            $canonical_index = (bool)Tools::getValue('canonical_index');
            Configuration::updateValue('PSB_RICHCARDS_CANONICAL_INDEX', $canonical_index);
        }
        
        $message .= $this->displayConfirmation($this->l('Options saved successfully.'));

        return $message;
    }

    
    // HOOKS
    public function hookBackOfficeHeader()
    {
        // Only for this module
        if ((Tools::getValue('configure') == $this->name) || (Tools::getValue('module_name') == $this->name)) {
            $this->context->controller->addCSS($this->_path.'views/css/tabs.css');
            // If 1.5
            $is_old = version_compare(_PS_VERSION_, '1.6', '<') ? true : false;
            if ($is_old) {
                $this->context->controller->addCSS($this->_path.'views/css/jquery-ui.min.css');
                $this->context->controller->addCSS($this->_path.'views/css/font-awesome.min.css');
                $this->context->controller->addJquery();
                $this->context->controller->addJS($this->_path.'views/js/jquery-ui.min.js');
            }
            //$this->context->controller->addJS($this->_path.'views/js/jquery-ui.min.js');
        }
    }
    
    public function hookDisplayHeader()
    {
        $controller = $this->context->controller;
        $controller_get = Tools::getValue('controller');
        $controller_used = Tools::strlen($controller->php_self) > 0 ? $controller : $controller_get;
        $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
        $id_shop = $this->context->shop->id;
        
        $templates = '';
                
        // Get Webmaster  Tools and others Verification codes
        $webmastertools = Configuration::get('PSB_RICHCARDS_TAGWT');
        $bing = Configuration::get('PSB_RICHCARDS_TAGBING');
        $yandex = Configuration::get('PSB_RICHCARDS_TAGYANDEX');
        $alexa = Configuration::get('PSB_RICHCARDS_TAGALEXA');
        $norton = Configuration::get('PSB_RICHCARDS_TAGNORTON');
        $wot = Configuration::get('PSB_RICHCARDS_TAGWOT');
        $pinterest = Configuration::get('PSB_RICHCARDS_TAGPINTEREST');
        
        $activatehref = (bool)Configuration::get('PSB_RICHCARDS_HREF');
        $languages_active = null;
        if ($activatehref) {
            $languages_active = Language::getLanguages(true, $this->context->shop->id);
        }
        
        // Canonical on index
        $canonical_index = (bool)Configuration::get('PSB_RICHCARDS_CANONICAL_INDEX');
        if ((($controller->php_self == 'index') || ($controller_get == 'index')) && ($canonical_index)) {
            // Set variables
            if (Tools::strlen($controller_used) > 0) {
                $canonical =  $this->context->link->getPageLink(
                    $controller_used,
                    null,
                    $id_lang,
                    null,
                    false,
                    $id_shop
                );

                $this->smarty->assign(array(
                    'shop_url_c' => $canonical,
                ));
                
                $templates .= $this->display(__FILE__, 'views/templates/hook/canonical_index.tpl');
            }
        }
        
        // Index HrefLang
        if ((($controller->php_self == 'index') || ($controller_get == 'index')) && ($activatehref)) {
            // Set variables
            $this->smarty->assign(array(
                'languages_active' => $languages_active,
                'default_id_lang' => $id_lang,
            ));
            $templates .= $this->display(__FILE__, 'views/templates/hook/hreflang_index.tpl');
        }
        
        // Product HrefLang
        $product = '';
        if (($controller->php_self == 'product') || ($controller_get == 'product')) {
            // Get Product
            
            $product = null;
            
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $id_product = (int)Tools::getValue('id_product');
                $product = new Product($id_product);
            } else {
                $product = $this->context->controller->getProduct();
            }
            // Only if products exists
            if ((int)$product->id > 0) {
                // Image for Twitter
                $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
                $images = Image::getImages((int)$id_lang, (int)$product->id);

                if (is_array($images) && count($images) > 0) {
                    $id_image = (int)$images[0]['id_image'];
                } else {
                    $id_image = 0;
                }
                
                $name_img = '';
                $image_link = '';
                if ($id_image > 0) {
                    if (version_compare(_PS_VERSION_, '1.7', '<')) {
                        // Hardcoded
                        $name_img = 'home_default';
                    } else {
                        // 1.7
                        $name_img = ImageType::getFormattedName('home');
                    }
                    if (is_array($product->link_rewrite)) {
                        $rewrite = $product->link_rewrite[$id_lang];
                        $image_link = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                    } else {
                        $image_link = $this->context->link->getImageLink($product->link_rewrite, $id_image, $name_img);
                    }
                }
                // Set variables
                $this->smarty->assign(array(
                    'activatehref' => $activatehref,
                    'product' => $product,
                    'languages_active' => $languages_active,
                    'default_id_lang' => $id_lang,
                ));
                
                if (count($languages_active) > 0) {
                    $templates .= $this->display(__FILE__, 'views/templates/hook/hreflang.tpl');
                }
                
                // Twitter
                $twitter_active = (bool)Configuration::get('PSB_RICHCARDS_TWITTER');
                if ($twitter_active && Validate::isLabel(Configuration::get('PSB_RICHCARDS_TW_USER'))) {
                    $this->smarty->assign(array(
                        'image' => $image_link,
                        'twitter_active' => true,
                        'twitterusername' => Configuration::get('PSB_RICHCARDS_TW_USER'),
                        'domain' => _PS_BASE_URL_,
                    ));
                } else {
                    $this->smarty->assign(array(
                        'twitter_active' => false,
                        'twitterusername' => '',
                    ));
                }
                $templates .= $this->display(__FILE__, 'views/templates/hook/twittercards.tpl');
            }
        }
        
        // HrefLang for Categories
        if (($controller->php_self == 'category') || ($controller_get == 'category')) {
            // HrefLang Category
            $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
            //$activatehref = (bool)Configuration::get('PSB_RICHCARDS_HREF');
            if ($activatehref) {
                $id_category = (int)Tools::getValue('id_category');
                $category = new Category($id_category, $this->context->language->id);
                $this->smarty->assign(array(
                    'category' => $category,
                    'languages_active' => $languages_active,
                    'default_id_lang' => $id_lang,
                ));
                $templates .= $this->display(__FILE__, 'views/templates/hook/hreflang_cat.tpl');
            }

            if ((bool)Configuration::get('PSB_RICHCARDS_TWITTER_CAT')) {
                $id_category = (int)Tools::getValue('id_category');
                // Instantiate category
                $category = new Category($id_category, $this->context->language->id);

                $this->smarty->assign(array(
                    'twitterusername' => Configuration::get('PSB_RICHCARDS_TW_USER'),
                    'domain' => _PS_BASE_URL_,
                    'category' => $category,
                    'id_lang' => $id_lang,
                ));
                $templates .= $this->display(__FILE__, 'views/templates/hook/twittercard_cat.tpl');
            }
        }
        
        // Hosts prefetch
        $dns_hosts = explode(';', trim(Configuration::get('PSB_RICHCARDS_PREFETCH')));
        if (count($dns_hosts) > 1) {
            $this->smarty->assign(array(
                'dns_hosts' => $dns_hosts,
            ));
            $templates .= $this->display(__FILE__, 'views/templates/hook/prefetch.tpl');
        }

        // Hosts preconnect
        $preconnect_hosts = explode(';', trim(Configuration::get('PSB_RICHCARDS_PRECONNECT')));
        if (count($preconnect_hosts) > 1) {
            $this->smarty->assign(array(
                'preconnect_hosts' => $preconnect_hosts,
            ));
            $templates .= $this->display(__FILE__, 'views/templates/hook/preconnect.tpl');
        }
        
        // Set variables
        $this->smarty->assign(array(
            'activatehref' => $activatehref,
            'product' => $product,
            'languages_active' => $languages_active,
            'webmastertools' => $webmastertools,
            'bing' => $bing,
            'yandex' => $yandex,
            'alexa' => $alexa,
            'norton' => $norton,
            'wot' => $wot,
            'pinterest' => $pinterest,
        ));
        $templates .= $this->display(__FILE__, 'views/templates/hook/webmaster.tpl');
        return $templates;
    }
    
  
    public function hookDisplayFooter()
    {
        $controller = $this->context->controller;
        $controller_get = Tools::getValue('controller');
        $templates = '';
               
        // Social media
        $facebook = Configuration::get('PSB_RICHCARDS_SOCIAL_FB');
        $twitter = Configuration::get('PSB_RICHCARDS_TW_USER');
        $googleplus = Configuration::get('PSB_RICHCARDS_SOCIAL_PLUS');
        $instagram = Configuration::get('PSB_RICHCARDS_SOCIAL_IG');
        $youtube = Configuration::get('PSB_RICHCARDS_SOCIAL_YT');
        $linkedin = Configuration::get('PSB_RICHCARDS_SOCIAL_LINKED');
        $myspace = Configuration::get('PSB_RICHCARDS_SOCIAL_MYS');
        
       
        // Check if we are in a product
        if (($controller->php_self == 'product') || ($controller_get == 'product')) {
            // Get Product
            $product = null;
            
            if (version_compare(_PS_VERSION_, '1.6', '<')) {
                $id_product = (int)Tools::getValue('id_product');
                $product = new Product($id_product);
            } else {
                $product = $this->context->controller->getProduct();
            }
            
            // Values
            $currency_code = $this->context->currency->iso_code;
            $decimals = 2;
            if (version_compare(_PS_VERSION_, '1.6', '>=')) {
                $decimals = (int)Configuration::get('PS_PRICE_DISPLAY_PRECISION');
            }
            
            // Main image
            $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
            $images = Image::getImages((int)$id_lang, (int)$product->id);

            /*if (is_array($images) && count($images) > 0) {
                $id_image = (int)$images[0]['id_image'];
            } else {
                $id_image = 0;
            }*/
            
            $name_img = '';
            $image_link = array();
            
            foreach ($images as $image) {
                $id_image = (int)$image['id_image'];
                if ($id_image > 0) {
                    if (version_compare(_PS_VERSION_, '1.7', '<')) {
                        // Hardcoded
                        $name_img = 'home_default';
                    } else {
                        // 1.7
                        $name_img = ImageType::getFormattedName('home');
                    }
                    if (is_array($product->link_rewrite)) {
                        $rewrite = $product->link_rewrite[$id_lang];
                        $image_link[] = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                    } else {
                        $rewrite = $product->link_rewrite[$id_lang];
                        $image_link[] = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                    }
                }
            }
            
            $product_link = $this->context->link->getProductLink($product);
            $shop_name = Configuration::get('PS_SHOP_NAME');
            
            // Average rating (if enabled)
            if (Module::isEnabled('gsnippetsreviews') && (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                if (file_exists(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php')) {
                    require_once(dirname(__FILE__).'/../gsnippetsreviews/conf/common.conf.php');
                    require_once(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php');

                    $oRatings = new BT_Rating();
                    $total_ratings = $oRatings->count((int)$this->context->shop->id, (int)$product->id);
                    $aParams = array('iProductId' => (int)$product->id);
                    $average_rating = $oRatings->average((int)$this->context->shop->id, $aParams);
                    
                    $this->smarty->assign(array(
                        'average_rating' => $average_rating,
                        'total_ratings' => $total_ratings,
                    ));
                }
            } elseif ((Tools::strlen(trim(Configuration::get('PSB_RICHCARDS_YOTPO_API'))) > 0) &&
            (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                // Yotpo
                $yotpo = $this->makeYotpoQuery(trim(Configuration::get('PSB_RICHCARDS_YOTPO_API')), (int)$product->id);
                if ($yotpo != null) {
                    $total_ratings = $yotpo->total_reviews;
                    $average_rating = $yotpo->average_score;
                    
                    $this->smarty->assign(array(
                        'average_rating' => $average_rating,
                        'total_ratings' => $total_ratings,
                    ));
                }
            } else {
                // PrestaShop
                //$is_16 = version_compare(_PS_VERSION_, '1.7', '<') ? true : false;
                $is_16 = true;
                if (Module::isEnabled('productcomments') && (bool)Configuration::get('PSB_RICHCARDS_RATING')
                && $is_16) {
                    $total_ratings = $this->getTotalRatings((int)$product->id);
                    $average_rating = $this->getAverageGrade((int)$product->id);
                    
                    $this->smarty->assign(array(
                        'average_rating' => $average_rating,
                        'total_ratings' => $total_ratings,
                    ));
                }
            }
            
            // Check Stock
            $stock = StockAvailable::getQuantityAvailableByProduct((int)$product->id);
            $instock = false;
            if ((int)$stock > 0) {
                $instock = true;
            }

            // Check Specific Price
            $valid_until = 0;
            if (!empty($product->specificPrice) && !empty($product->specificPrice['to'])) {
                $valid_until = $product->specificPrice['to'];
            }
            
            // BreadCrumb
            $breadcrumb_active = (bool)Configuration::get('PSB_RICHCARDS_BREAD');
            $all_product_subs = Product::getProductCategoriesFull((int)$product->id, $this->context->language->id);
            $category_root = Category::getRootCategory($this->context->language->id);
            $root_id = (int)$category_root->id;
            if (Configuration::get('PSB_RICHCARDS_IGNOREROOT') && $root_id > 0) {
                unset($all_product_subs[$root_id]);
            }
            
            // Google Rich Card
            $activaterich = (bool)Configuration::get('PSB_RICHCARDS_PRODUCT');
            
            $this->smarty->assign(array(
                'activaterich' => $activaterich,
                'product' => $product,
                'decimals' => $decimals,
                'valid_until' => $valid_until,
                'breadcrumb_list' => $all_product_subs,
                'breadcrumb_active' => $breadcrumb_active,
                'instock' => $instock,
                'id_lang' => $id_lang,
                'image' => $image_link,
                'currency' => $currency_code,
                'linkurl' => $product_link,
                'shop_name' => $shop_name,
                'module_dir' => $this->_path));
            
            return $templates.$this->display(__FILE__, 'views/templates/hook/product_rich.tpl');
        } elseif ((($controller->php_self == 'stores') || ($controller_get == 'stores')) &&
        ((bool)Configuration::get('PSB_RICHCARDS_STORE'))) {
            // Get Stores
            $imageRetriever = null;
            $stores = null;
            
            if (version_compare(_PS_VERSION_, '1.7', '<')) {
                // Older versions
                $stores = Db::getInstance()->executeS('
							SELECT s.*, cl.name country, st.iso_code state
							FROM '._DB_PREFIX_.'store s
							'.Shop::addSqlAssociation('store', 's').'
							LEFT JOIN '._DB_PREFIX_.'country_lang cl ON (cl.id_country = s.id_country)
							LEFT JOIN '._DB_PREFIX_.'state st ON (st.id_state = s.id_state)
							WHERE s.active = 1 AND cl.id_lang = '.(int)$this->context->language->id);
            } else {
                $stores = Store::getStores();
                $imageRetriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever($this->context->link);
            }

            $stores_clean = array();
            
            // Get price range
            $saved_range = (int)Configuration::get('PSB_RICHCARDS_RANGE');
            $pricerange = '';
            switch ($saved_range) {
                case 1:
                    $pricerange = '$';
                    break;
                case 2:
                    $pricerange = '$$';
                    break;
                case 3:
                    $pricerange = '$$$';
                    break;
                case 4:
                    $pricerange = '$$$$';
                    break;
                default:
                    $pricerange = '$$$';
            }
            
            $array_business = $this->getArrayBusiness();
            array_unshift($array_business, 'LocalBusiness');
            $position = (int)Configuration::get('PSB_RICHCARDS_STORETYPE') - 1;
            $store_type = $array_business[$position];
            
            // Display any "sameAs"?
            $sameas = false;
            $social_array = array();
            $social_string = '';
            
            if (Tools::strlen($facebook) > 0 || Tools::strlen($twitter) > 0 || Tools::strlen($googleplus) > 0 ||
            Tools::strlen($instagram) > 0 || Tools::strlen($youtube) > 0 || Tools::strlen($linkedin) > 0 ||
            Tools::strlen($myspace) > 0) {
                $sameas = true;
                if (Tools::strlen($facebook) > 0) {
                    $social_array[] = $facebook;
                }
                if (Tools::strlen($twitter) > 0) {
                    $social_array[] = 'https://twitter.com/'.$twitter.'/';
                }
                if (Tools::strlen($googleplus) > 0) {
                    $social_array[] = $googleplus;
                }
                if (Tools::strlen($instagram) > 0) {
                    $social_array[] = $instagram;
                }
                if (Tools::strlen($youtube) > 0) {
                    $social_array[] = $youtube;
                }
                if (Tools::strlen($linkedin) > 0) {
                    $social_array[] = $linkedin;
                }
                if (Tools::strlen($myspace) > 0) {
                    $social_array[] = $myspace;
                }
            }

            // Check if there are any social markup
            if (count($social_array) > 0) {
                foreach ($social_array as $index => $social) {
                    $social_string .= ($index+1) < count($social_array) ? '"'.$social.'", ' :
                    '"'.$social.'"';
                }
            }
            
            foreach ($stores as $store) {
                $name = $store['name'];
                $image = null;
                $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
                $link_url = self::getLink($this->context->shop->id, Configuration::get('PS_SSL_ENABLED'));
                $logo = $link_url.'img/'.Configuration::get('PS_LOGO', null, null, $this->context->shop->id);

                // Getting shop image
                if ($imageRetriever == null) {
                    // PS 1.6
                    if (file_exists(_PS_STORE_IMG_DIR_.(int)$store['id_store'].'.jpg')) {
                        $image = $link_url.'img/'.$store['id_store'].'.jpg';
                    } else {
                        $image = $logo;
                    }
                } else {
                    // PS 1.7
                    $image = $imageRetriever->getImage(new Store($store['id_store']), $store['id_store']);
                    $image = $image['medium']['url'];
                }
                
                // Adress related
                $street = $store['address1'];
                $locality = $store['city'];
                $id_state = $store['id_state'];
                $id_country = $store['id_country'];
                $region = State::getNameById($id_state);
                $country = Country::getNameById($id_lang, $id_country);
                $email = $store['email'];
                $postal = $store['postcode'];
                $lat = $store['latitude'];
                $lon = $store['longitude'];
                $map_url = 'http://maps.google.com/maps?q='.$lat.','.$lon;
                $phone = $store['phone'];
                $who = 'customer service';
                $opening = $this->renderStoreWorkingHours($store);

                // Store values as array
                $stores_clean[] = array(
                    'name' => $name,
                    'description' => '',
                    'logo' => $logo,
                    'image' => $image,
                    'pricerange' => $pricerange,
                    'linkurl' => $link_url,
                    'street' => $street,
                    'locality' => $locality,
                    'region' => $region,
                    'postal' => $postal,
                    'email' => $email,
                    'opening' => $opening,
                    'country' => $country,
                    'lat' => $lat,
                    'lon' => $lon,
                    'map_url' => $map_url,
                    'phone' => $phone,
                    'who' => $who);
            }
            
            $this->smarty->assign(array(
                'stores' => $stores_clean,
                'sameas' => $sameas,
                'store_type' => $store_type,
                'social_string' => $social_string,
            ));
            return $templates.$this->display(__FILE__, 'views/templates/hook/organization_rich.tpl');
        } elseif (($controller->php_self == 'manufacturer') || ($controller_get == 'manufacturer')) {
            // For manufacturer
            $id_lang = (int)Tools::getValue('id_lang') > 0 ? (int)Tools::getValue('id_lang') : 1;
            $id_manufacturer = (int)Tools::getValue('id_manufacturer');
            // Only if manufacturer and language are sent
            if ($id_lang > 0 && $id_manufacturer > 0) {
                $manufact = new Manufacturer($id_manufacturer);
                $manufacturer_name = $manufact->name;
                $products = Manufacturer::getProducts($id_lang, $id_manufacturer, 1, 500);
                if (count($products) > 1) {
                    foreach ($products as $product_smarty) {
                        // Values
                        $id_product = (int)$product_smarty['id_product'];
                        $product = new Product($id_product);
                        $currency_code = $this->context->currency->iso_code;
                        $decimals = 2;
                        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
                            $decimals = (int)Configuration::get('PS_PRICE_DISPLAY_PRECISION');
                        }
                        
                        // Main image
                        $images = Image::getImages((int)$id_lang, (int)$product->id);

                        /*if (is_array($images) && count($images) > 0) {
                            $id_image = (int)$images[0]['id_image'];
                        } else {
                            $id_image = 0;
                        }*/
                        
                        $name_img = '';
                        $image_link = array();
                        
                        foreach ($images as $image) {
                            $id_image = (int)$image['id_image'];
                            if ($id_image > 0) {
                                if (version_compare(_PS_VERSION_, '1.7', '<')) {
                                    // Hardcoded
                                    $name_img = 'home_default';
                                } else {
                                    // 1.7
                                    $name_img = ImageType::getFormattedName('home');
                                }
                                if (is_array($product->link_rewrite)) {
                                    $rewrite = $product->link_rewrite[$id_lang];
                                    $image_link[] = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                                } else {
                                    $image_link[] = $this->context->link->getImageLink(
                                        $product->link_rewrite,
                                        $id_image,
                                        $name_img
                                    );
                                }
                            }
                        }
                        
                        $product_link = $this->context->link->getProductLink($product);
                        $shop_name = Configuration::get('PS_SHOP_NAME');
                        
                        // Average rating (if enabled)
                        if (Module::isEnabled('gsnippetsreviews') &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            if (file_exists(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php')) {
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/conf/common.conf.php');
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php');
                                
                                $oRatings = new BT_Rating();
                                $total_ratings = $oRatings->count((int)$this->context->shop->id, (int)$product->id);
                                $aParams = array('iProductId' => (int)$product->id);
                                $average_rating = $oRatings->average((int)$this->context->shop->id, $aParams);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } elseif ((Tools::strlen(trim(Configuration::get('PSB_RICHCARDS_YOTPO_API'))) > 0) &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            // Yotpo
                            $yapi = Configuration::get('PSB_RICHCARDS_YOTPO_API');
                            $yotpo = $this->makeYotpoQuery(trim($yapi), (int)$product->id);
                            if ($yotpo != null) {
                                $total_ratings = $yotpo->total_reviews;
                                $average_rating = $yotpo->average_score;
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } else {
                            //$is_16 = version_compare(_PS_VERSION_, '1.7', '<') ? true : false;
                            $is_16 = true;
                            if (Module::isEnabled('productcomments') &&
                            (bool)Configuration::get('PSB_RICHCARDS_RATING') && $is_16) {
                                $total_ratings = $this->getTotalRatings((int)$product->id);
                                $average_rating = $this->getAverageGrade((int)$product->id);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        }
                        
                        // Check Stock
                        $stock = StockAvailable::getQuantityAvailableByProduct((int)$product->id);
                        $instock = false;
                        if ((int)$stock > 0) {
                            $instock = true;
                        }

                        // Check Specific Price
                        $valid_until = 0;
                        if (!empty($product->specificPrice) && !empty($product->specificPrice['to'])) {
                            $valid_until = $product->specificPrice['to'];
                        }
                    
                        // Google Rich Card
                        $activaterich = (bool)Configuration::get('PSB_RICHCARDS_PRODUCT');
                        if ($activaterich) {
                            $this->smarty->assign(array(
                                'activaterich' => $activaterich,
                                'product' => $product,
                                'decimals' => $decimals,
                                'valid_until' => $valid_until,
                                'instock' => $instock,
                                'id_lang' => $id_lang,
                                'image' => $image_link,
                                'currency' => $currency_code,
                                'manufacturer_name' => $manufacturer_name,
                                'linkurl' => $product_link,
                                'shop_name' => $shop_name,
                                'module_dir' => $this->_path));
                            $templates .= $this->display(__FILE__, 'views/templates/hook/product_rich_man.tpl');
                        }
                    }
                    return $templates;
                }
            }
        } elseif (($controller->php_self == 'index') && ((bool)Configuration::get('PSB_RICHCARDS_WEBSITE'))) {
            // For index
            $link_url = self::getLink($this->context->shop->id, Configuration::get('PS_SSL_ENABLED'));
            $logo = $link_url.'img/'.Configuration::get('PS_LOGO', null, null, $this->context->shop->id);
            $shop_name = Configuration::get('PS_SHOP_NAME');

            $this->smarty->assign(array('logo' => $logo, 'shop_name' => $shop_name, 'link_site' => $link_url));
            
            // Module featuredproducts
            $feat_products = null;
            if (Module::isEnabled('homefeatured') && Module::isEnabled('homefeatured')) {
                $hf = (int)Configuration::get('HOME_FEATURED_CAT');
                $category = new Category($hf, (int)Context::getContext()->language->id);
                $nb = (int)Configuration::get('HOME_FEATURED_NBR');
                if (!Configuration::get('HOME_FEATURED_RANDOMIZE')) {
                    $feat_products = $category->getProducts(
                        (int)Context::getContext()->language->id,
                        1,
                        ($nb ? $nb : 8),
                        'position'
                    );
                }

                if ($feat_products != null) {
                    $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
                    foreach ($feat_products as $featured) {
                        // Values
                        $id_product = (int)$featured['id_product'];
                        $product = new Product($id_product);
                        $currency_code = $this->context->currency->iso_code;
                        $decimals = 2;
                        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
                            $decimals = (int)Configuration::get('PS_PRICE_DISPLAY_PRECISION');
                        }
                        
                        // Main image
                        $images = Image::getImages((int)$id_lang, (int)$product->id);

                        /*if (is_array($images) && count($images) > 0) {
                            $id_image = (int)$images[0]['id_image'];
                        } else {
                            $id_image = 0;
                        }*/
                        
                        $name_img = '';
                        $image_link = array();
                        
                        foreach ($images as $image) {
                            $id_image = (int)$image['id_image'];
                            if ($id_image > 0) {
                                if (version_compare(_PS_VERSION_, '1.7', '<')) {
                                    // Hardcoded
                                    $name_img = 'home_default';
                                } else {
                                    // 1.7
                                    $name_img = ImageType::getFormattedName('home');
                                }
                                if (is_array($product->link_rewrite)) {
                                    $rewrite = $product->link_rewrite[$id_lang];
                                    $image_link[] = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                                } else {
                                    $image_link[] = $this->context->link->getImageLink(
                                        $product->link_rewrite,
                                        $id_image,
                                        $name_img
                                    );
                                }
                            }
                        }
                        
                        $product_link = $this->context->link->getProductLink($product);
                        $shop_name = Configuration::get('PS_SHOP_NAME');
                        
                        // Average rating (if enabled)
                        if (Module::isEnabled('gsnippetsreviews') &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            if (file_exists(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php')) {
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/conf/common.conf.php');
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php');
                                
                                $oRatings = new BT_Rating();
                                $total_ratings = $oRatings->count((int)$this->context->shop->id, (int)$product->id);
                                $aParams = array('iProductId' => (int)$product->id);
                                $average_rating = $oRatings->average((int)$this->context->shop->id, $aParams);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } elseif ((Tools::strlen(trim(Configuration::get('PSB_RICHCARDS_YOTPO_API'))) > 0) &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            // Yotpo
                            $yapi = Configuration::get('PSB_RICHCARDS_YOTPO_API');
                            $yotpo = $this->makeYotpoQuery(trim($yapi), (int)$product->id);
                            if ($yotpo != null) {
                                $total_ratings = $yotpo->total_reviews;
                                $average_rating = $yotpo->average_score;
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } else {
                            //$is_16 = version_compare(_PS_VERSION_, '1.7', '<') ? true : false;
                            $is_16 = true;
                            if (Module::isEnabled('productcomments') &&
                            (bool)Configuration::get('PSB_RICHCARDS_RATING') && $is_16) {
                                $total_ratings = $this->getTotalRatings((int)$product->id);
                                $average_rating = $this->getAverageGrade((int)$product->id);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        }
                        
                        // Check Stock
                        $stock = StockAvailable::getQuantityAvailableByProduct((int)$product->id);
                        $instock = false;
                        if ((int)$stock > 0) {
                            $instock = true;
                        }

                        // Check Specific Price
                        $valid_until = 0;
                        if (!empty($product->specificPrice) && !empty($product->specificPrice['to'])) {
                            $valid_until = $product->specificPrice['to'];
                        }
                    
                        // Google Rich Card
                        $activaterich = (bool)Configuration::get('PSB_RICHCARDS_PRODUCT');
                        if ($activaterich) {
                            $this->smarty->assign(array(
                                'activaterich' => $activaterich,
                                'product' => $product,
                                'decimals' => $decimals,
                                'valid_until' => $valid_until,
                                'instock' => $instock,
                                'id_lang' => $id_lang,
                                'image' => $image_link,
                                'currency' => $currency_code,
                                'linkurl' => $product_link,
                                'shop_name' => $shop_name,
                                'module_dir' => $this->_path));
                            $templates .= $this->display(__FILE__, 'views/templates/hook/featured.tpl');
                        }
                    }
                }
            }
            
            return $templates.$this->display(__FILE__, 'views/templates/hook/website.tpl');
        } elseif (($controller->php_self == 'category') || ($controller_get == 'category')) {
            // For category (product-list)
            $id_lang = $this->context->cookie->id_lang > 0 ? $this->context->cookie->id_lang : 1;
            $products = null;
            
            // Only if Rich cards for categories is enabled
            if ((bool)Configuration::get('PSB_RICHCARDS_PRODUCT_CAT')) {
                if (version_compare(_PS_VERSION_, '1.7', '<')) {
                    $products = $this->context->smarty->getTemplateVars('products');
                } else {
                    $product_list = $this->context->smarty->getTemplateVars('listing');
                    $products = $product_list['products'];
                }
                
                if (count($products) > 1) {
                    foreach ($products as $product_smarty) {
                        // Values
                        $id_product = (int)$product_smarty['id_product'];
                        $product = new Product($id_product);
                        $currency_code = $this->context->currency->iso_code;
                        $decimals = 2;
                        if (version_compare(_PS_VERSION_, '1.6', '>=')) {
                            $decimals = (int)Configuration::get('PS_PRICE_DISPLAY_PRECISION');
                        }
                        
                        // Main image
                        $images = Image::getImages((int)$id_lang, (int)$product->id);

                        /*if (is_array($images) && count($images) > 0) {
                            $id_image = (int)$images[0]['id_image'];
                        } else {
                            $id_image = 0;
                        }*/
                        
                        $name_img = '';
                        $image_link = array();
                        
                        foreach ($images as $image) {
                            $id_image = (int)$image['id_image'];
                            if ($id_image > 0) {
                                if (version_compare(_PS_VERSION_, '1.7', '<')) {
                                    // Hardcoded
                                    $name_img = 'home_default';
                                } else {
                                    // 1.7
                                    $name_img = ImageType::getFormattedName('home');
                                }
                                if (is_array($product->link_rewrite)) {
                                    $rewrite = $product->link_rewrite[$id_lang];
                                    $image_link[] = $this->context->link->getImageLink($rewrite, $id_image, $name_img);
                                } else {
                                    $image_link[] = $this->context->link->getImageLink(
                                        $product->link_rewrite,
                                        $id_image,
                                        $name_img
                                    );
                                }
                            }
                        }
                        
                        $product_link = $this->context->link->getProductLink($product);
                        $shop_name = Configuration::get('PS_SHOP_NAME');
                        
                        // Average rating (if enabled)
                        if (Module::isEnabled('gsnippetsreviews') &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            if (file_exists(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php')) {
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/conf/common.conf.php');
                                require_once(dirname(__FILE__).'/../gsnippetsreviews/lib/reviews/rating_class.php');
                                
                                $oRatings = new BT_Rating();
                                $total_ratings = $oRatings->count((int)$this->context->shop->id, (int)$product->id);
                                $aParams = array('iProductId' => (int)$product->id);
                                $average_rating = $oRatings->average((int)$this->context->shop->id, $aParams);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } elseif ((Tools::strlen(trim(Configuration::get('PSB_RICHCARDS_YOTPO_API'))) > 0) &&
                        (bool)Configuration::get('PSB_RICHCARDS_RATING')) {
                            // Yotpo
                            $yapi = Configuration::get('PSB_RICHCARDS_YOTPO_API');
                            $yotpo = $this->makeYotpoQuery(trim($yapi), (int)$product->id);
                            if ($yotpo != null) {
                                $total_ratings = $yotpo->total_reviews;
                                $average_rating = $yotpo->average_score;
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        } else {
                            //$is_16 = version_compare(_PS_VERSION_, '1.7', '<') ? true : false;
                            $is_16 = true;
                            if (Module::isEnabled('productcomments') &&
                            (bool)Configuration::get('PSB_RICHCARDS_RATING') && $is_16) {
                                $total_ratings = $this->getTotalRatings((int)$product->id);
                                $average_rating = $this->getAverageGrade((int)$product->id);
                                
                                $this->smarty->assign(array(
                                    'average_rating' => $average_rating,
                                    'total_ratings' => $total_ratings,
                                ));
                            }
                        }
                        
                        // Check Stock
                        $stock = StockAvailable::getQuantityAvailableByProduct((int)$product->id);
                        $instock = false;
                        if ((int)$stock > 0) {
                            $instock = true;
                        }

                        // Check Specific Price
                        $valid_until = 0;
                        if (!empty($product->specificPrice) && !empty($product->specificPrice['to'])) {
                            $valid_until = $product->specificPrice['to'];
                        }
                    
                        // Google Rich Card
                        $activaterich = (bool)Configuration::get('PSB_RICHCARDS_PRODUCT');
                        if ($activaterich) {
                            $this->smarty->assign(array(
                                'activaterich' => $activaterich,
                                'product' => $product,
                                'decimals' => $decimals,
                                'valid_until' => $valid_until,
                                'instock' => $instock,
                                'id_lang' => $id_lang,
                                'image' => $image_link,
                                'currency' => $currency_code,
                                'linkurl' => $product_link,
                                'shop_name' => $shop_name,
                                'module_dir' => $this->_path));
                            $templates .= $this->display(__FILE__, 'views/templates/hook/product_rich_cat.tpl');
                        }
                    }
                }
            } // End for product card generation on categories

            $id_category = (int)Tools::getValue('id_category');
            // BreadCrumb
            if ((bool)Configuration::get('PSB_RICHCARDS_BREAD')) {
                // Instantiate category
                $category = new Category($id_category, $this->context->language->id);
                $tree = array_reverse($category->getParentsCategories($this->context->language->id));
                if (count($tree) > 0) {
                    if (Configuration::get('PSB_RICHCARDS_IGNOREROOT')) {
                        unset($tree[0]);
                    }
                    $this->smarty->assign(array(
                        'breadcrumb_list' => $tree,
                    ));
                    $templates .= $this->display(__FILE__, 'views/templates/hook/breadcrumb.tpl');
                }
            }
            
            return $templates;
        }
    }
    
    public function getLink($id_shop = null, $ssl = null)
    {
        static $force_ssl = null;

        if ($ssl === null) {
            if ($force_ssl === null) {
                $force_ssl = (Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE'));
            }
            $ssl = $force_ssl;
        }

        if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && $id_shop !== null) {
            $shop = new Shop($id_shop);
        } else {
            $shop = Context::getContext()->shop;
        }

        $base = $ssl ? 'https://'.$shop->domain_ssl : 'http://'.$shop->domain;
        return $base.$shop->getBaseURI();
    }

    /**
     * Get number Ratings by Product
     *
     * @return float Average
     */
    public static function getTotalRatings($id_product)
    {
        $validate = Configuration::get('PRODUCT_COMMENTS_MODERATE');
        $sql = 'SELECT COUNT(`grade`) AS total FROM `'._DB_PREFIX_.'product_comment`  WHERE `id_product` = '.
        (int)$id_product.' AND `deleted` = 0'.($validate == '1' ? ' AND `validate` = 1' : '');

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
    }
    
    /**
     * Get avg Rating by Product
     *
     * @return int Average
     */
    public static function getAverageGrade($id_product)
    {
        $validate = Configuration::get('PRODUCT_COMMENTS_MODERATE');
        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT (SUM(pc.`grade`) / COUNT(pc.`grade`)) AS grade	
		FROM `'._DB_PREFIX_.'product_comment` pc WHERE pc.`id_product` = '.(int)$id_product.' AND pc.`deleted` = 0'.
        ($validate == '1' ? ' AND pc.`validate` = 1' : ''));
    }

    /**
     * Get Business Type array
     *
     * @return array
     */
    private function getArrayBusiness()
    {
        return array(
        'AccountingService', 'Attorney', 'AutoBodyShop', 'AutoDealer', 'AutoPartsStore', 'AutoRental', 'AutoRepair',
        'AutoWash', 'Bakery', 'BarOrPub', 'BeautySalon', 'BedAndBreakfast', 'BikeStore', 'BookStore',
        'CafeOrCoffeeShop', 'ChildCare', 'ClothingStore', 'ComputerStore', 'DaySpa', 'Dentist',
        'DryCleaningOrLaundry', 'Electrician', 'ElectronicsStore', 'EmergencyService', 'EntertainmentBusiness',
        'EventVenue', 'ExerciseGym', 'FinancialService', 'Florist', 'FoodEstablishment', 'FurnitureStore',
        'GardenStore', 'GeneralContractor', 'GolfCourse', 'HairSalon', 'HardwareStore', 'HealthAndBeautyBusiness',
        'HobbyShop', 'HomeAndConstructionBusiness', 'HomeGoodsStore', 'Hospital', 'Hotel', 'HousePainter',
        'HVACBusiness', 'InsuranceAgency', 'JewelryStore', 'LiquorStore', 'Locksmith', 'LodgingBusiness',
        'MedicalClinic', 'MensClothingStore', 'MobilePhoneStore', 'Motel', 'MotorcycleDealer', 'MotorcycleRepair',
        'MovingCompany', 'MusicStore', 'NailSalon', 'NightClub', 'Notary', 'OfficeEquipmentStore', 'Optician',
        'PetStore', 'Physician', 'Plumber', 'ProfessionalService', 'RealEstateAgent', 'Residence', 'Restaurant',
        'RoofingContractor', 'RVPark', 'School', 'SelfStorage', 'ShoeStore', 'SkiResort', 'SportingGoodsStore',
        'SportsClub', 'Store', 'TattooParlor', 'Taxi', 'TennisComplex', 'TireShop', 'ToyStore', 'TravelAgency',
        'VeterinaryCare', 'WholesaleStore', 'Winery');
    }

    /**
    * Checks if its a valid hostname (from TOR and IP Blocker)
    */
    public static function isHost($hostname)
    {
        $valid = false;
        // RegEx host validation (FDI)
        $rgx_host = "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*";
        $rgx_host .= "([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/";

        // Check if its a valid host and if its the same
        $host = preg_grep($rgx_host, array($hostname));
        if ((count($host) > 0) && ($hostname == $host[0])) {
            $valid = true;
        }
        
        return $valid;
    }
    
    /**
    * Get Yotpo reviews
    */
    private function makeYotpoQuery($app_key, $id_product)
    {
        // Test Cache
        include_once dirname(__FILE__).'/lib/cache.class.php';
        $cached = new CachePHP_Yotpo(array(
            'name'      => 'yotpo_'.(int)$id_product,
            'path'      => dirname(__FILE__).'/cache/',
            'extension' => '.cache.php'
        ));
        // Delete old caches
        $cached->eraseExpired();
        
        // Check if cached
        if ($cached->isCached($id_product)) {
            return json_decode($cached->retrieve($id_product));
        } else {
            $endpoint = 'https://api.yotpo.com/products/'.$app_key.'/'.(int)$id_product.'/bottomline/';
            $ch = @curl_init();
            @curl_setopt($ch, CURLOPT_URL, $endpoint);
            @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            @curl_setopt($ch, CURLOPT_HEADER, false);
            @curl_setopt($ch, CURLOPT_TIMEOUT, 2);
            @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            @curl_setopt($ch, CURLOPT_VERBOSE, false);
            $response = @curl_exec($ch);
            @curl_close($ch);
            
            if ($response == null) {
                return null;
            }
            
            $pre = json_decode($response);
            if (property_exists($pre, 'response')) {
                // Product with Yotpo
                $result = $pre->response->bottomline;
                $yotpo_res = array(
                    'average_score' => $result->average_score,
                    'total_reviews' => $result->total_reviews,
                );
                $cached->store($id_product, json_encode($yotpo_res), 604800);
                return $result;
            } else {
                // Product without Yotpo
                $yotpo_res = array(
                    'average_score' => 0,
                    'total_reviews' => 0,
                );
                
                $result = json_encode($yotpo_res);
                $cached->store($id_product, $result, 604800);
                return json_decode($result);
            }
        }
    }

    /**
    * Renders Working Hours
    */
    private function renderStoreWorkingHours($store)
    {
        $days = null;
        $days[1] = 'Mo';
        $days[2] = 'Tu';
        $days[3] = 'We';
        $days[4] = 'Th';
        $days[5] = 'Fr';
        $days[6] = 'Sa';
        $days[7] = 'Su';

        $days_datas = array();
        $hours = array();

        if ($store['hours']) {
            $hours = Tools::unSerialize($store['hours']);
            if (is_array($hours)) {
                $hours = array_filter($hours);
            }
        }

        if (!empty($hours)) {
            for ($i = 1; $i < 8; $i++) {
                if (isset($hours[(int)$i - 1]) && Tools::strlen($hours[(int)$i - 1])>2) {
                    $hours_datas = array();
                    $hours_datas['hours'] = $hours[(int)$i - 1];
                    $hours_datas['day'] = $days[$i];
                    $days_datas[] = $hours_datas;
                }
            }
            // Check if there are any opening markup
            $opening_string = '';
            if (count($days_datas) > 0) {
                foreach ($days_datas as $index => $opening) {
                    $opening_string .= ($index+1) < count($days_datas) ? '"'.$opening['day'].' '.
                    $opening['hours'].'", ' : '"'.$opening['day'].' '.$opening['hours'].'"';
                }
            }
            return $opening_string;
        }
        return '';
    }
}
