<?php
/**
 * Copyright since 2022 Inferendo Srl
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License 3.0 (AFL-3.0)
 * that is bundled with this package in the file LICENSE.md.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/AFL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to hello@visidea.ai so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Visidea to newer
 * versions in the future. If you wish to customize Visidea for your
 * needs please refer to https://visidea.ai/ for more information.
 *
 * @author    Inferendo SRL <hello@visidea.ai>
 * @copyright Since 2022 Inferendo Srl
 * @license   https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
 */

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

class Visidea extends Module
{
    protected $config_form = false;

    public function __construct()
    {
        $this->name = 'visidea';
        $this->tab = 'administration';
        $this->version = '2.17.0';
        $this->author = 'Inferendo';
        $this->need_instance = 0;

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

        parent::__construct();

        $this->displayName = $this->l('Visidea');
        $this->description = $this->l('AI Search Bar, Visual Search and Product Recommendations');

        $this->confirmUninstall = $this->l('Are you shure you want to uninstall this module?');

        $this->ps_versions_compliancy = array('min' => '1.7.0.0', 'max' => _PS_VERSION_);
    }

    public function install()
    {
        return parent::install() &&
            $this->registerHook('actionFrontControllerSetMedia') &&
            $this->registerHook('displayBeforeBodyClosingTag') &&
            $this->registerHook('displayHome') &&
            $this->registerHook('displayFooterProduct') &&
            $this->registerHook('displayShoppingCartFooter') &&
            $this->registerHook('displayOrderConfirmation');
    }

    public function uninstall()
    {
        // Configuration::deleteByName('VISIDEA_WEBSITE');
        // Configuration::deleteByName('VISIDEA_PRIVATE_KEY');
        // Configuration::deleteByName('VISIDEA_PUBLIC_KEY');

        return parent::uninstall() &&
            $this->unregisterHook('actionFrontControllerSetMedia') &&
            $this->unregisterHook('displayBeforeBodyClosingTag') &&
            $this->unregisterHook('displayHome') &&
            $this->unregisterHook('displayFooterProduct') &&
            $this->unregisterHook('displayShoppingCartFooter') &&
            $this->unregisterHook('displayOrderConfirmation');
    }

    public function getContent()
    {
        $this->createConf();

        $output = '';
        if (((bool)Tools::isSubmit('submitVisideaModule')) == true) {
            $output = $this->postProcess();
        }

        $this->context->smarty->assign('module_dir', $this->_path);
        $this->context->smarty->assign('language', $this->getMainLanguage());

        $register = $this->context->smarty->fetch($this->local_path.'views/templates/admin/register.tpl');
        $configure = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');

        return $output.$register.$this->renderForm().$configure;
    }

    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 = 'submitVisideaModule';
        $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 structure of your form.
     */
    protected function getConfigForm()
    {
        return array(
            'form' => array(
                'legend' => array(
                'title' => $this->l('Settings'),
                'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'col' => 3,
                        'type' => 'text',
                        'prefix' => '<i class="icon icon-globe"></i>',
                        'name' => 'VISIDEA_WEBSITE',
                        'label' => $this->l('Website'),
                    ),
                    array(
                        'col' => 3,
                        'type' => 'text',
                        'prefix' => '<i class="icon icon-key"></i>',
                        'name' => 'VISIDEA_PUBLIC_KEY',
                        'label' => $this->l('Public Token'),
                    ),
                    array(
                        'col' => 3,
                        'type' => 'text',
                        'prefix' => '<i class="icon icon-key"></i>',
                        'name' => 'VISIDEA_PRIVATE_KEY',
                        'label' => $this->l('Private Token'),
                    ),

                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }

    protected function getConfigFormValues()
    {
        return array(
            'VISIDEA_WEBSITE' => Configuration::get('VISIDEA_WEBSITE', true),
            'VISIDEA_PRIVATE_KEY' => Configuration::get('VISIDEA_PRIVATE_KEY',null),
            'VISIDEA_PUBLIC_KEY' => Configuration::get('VISIDEA_PUBLIC_KEY',null),
        );
    }

    protected function createConf()
    {
        if (Configuration::get('VISIDEA_PRIVATE_KEY',null) === false) {
            $site_url = parse_url(Context::getContext()->shop->getBaseURL(true));
            $website = $site_url['host'];
            Configuration::updateValue('VISIDEA_PRIVATE_KEY', $this->generateRandomString());
            Configuration::updateValue('VISIDEA_PUBLIC_KEY', $this->generateRandomString());
            Configuration::updateValue('VISIDEA_WEBSITE', $website);
        }
    }

    protected function generateRandomString($length = 32)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    protected function getMainLanguage()
    {
        $id_lang = Configuration::get('PS_LANG_DEFAULT');
        $language = new Language($id_lang);
        return $language->iso_code;
    }

    
    protected function postProcess()
    {
        $form_values = $this->getConfigFormValues();

        foreach (array_keys($form_values) as $key) {
            Configuration::updateValue($key, Tools::getValue($key));
        }

        $path = __DIR__ . "/csv/";
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        // var_dump(Configuration::get('VISIDEA_PRIVATE_KEY',null));

        // file items
        $filename = 'items_' . Configuration::get('VISIDEA_PRIVATE_KEY',null) . '.csv';
        if (!file_exists($path.$filename)) {
            $items = array(
                'item_id',
                'name',
                'brand_id',
                'brand_name',
                'price',
                'market_price',
                'discount',
                'page_ids',
                'page_names',
                'url',
                'images',
                'stock'
            );
            $file = fopen($path.$filename, 'w');
            fputcsv($file, $items, ";");
            fclose($file);
        }
        // file users
        $filename = 'users_' . Configuration::get('VISIDEA_PRIVATE_KEY',null) . '.csv';
        if (!file_exists($path.$filename)) {
            $users = array(
                'user_id',
                'email',
                'name',
                'surname',
                'address',
                'city',
                'zip',
                'state',
                'country',
                'birthday'
            );
            $file = fopen($path.$filename, 'w');
            fputcsv($file, $users, ";");
            fclose($file);
        }
        // file interactions
        $filename = 'interactions_' . Configuration::get('VISIDEA_PRIVATE_KEY',null) . '.csv';
        if (!file_exists($path.$filename)) {
            $interactions = array(
                'user_id',
                'item_id',
                'action',
                'timestamp'
            );
            $file = fopen($path.$filename, 'w');
            fputcsv($file, $interactions, ";");
            fclose($file);
        }

        return $this->displayConfirmation($this->l('Parameters updated!'));

    }

    public function hookActionFrontControllerSetMedia()
    {
        $this->context->controller->registerJavascript(
            'visidea-library',
            'https://cdn.visidea.ai/js-visidea/js-visidea-3.16.0.min.js',
            array('server' => 'remote')
        );
    }

    public function hookDisplayBeforeBodyClosingTag($params)
    {
        return $this->display(__FILE__, 'init.tpl');
    }

    
    public function hookDisplayFooterProduct()
    {
        $this->smarty->assign('page', 'product');
        return $this->display(__FILE__, 'show_recommendation.tpl');
    }

    public function hookDisplayHome()
    {
        $this->smarty->assign('page', 'home');
        return $this->display(__FILE__, 'show_recommendation.tpl');
    }

    public function hookDisplayShoppingCartFooter()
    {
        $this->smarty->assign('page', 'cart');
        return $this->display(__FILE__, 'show_recommendation.tpl');
    }

    public function hookDisplayOrderConfirmation()
    {
        $this->smarty->assign('page', 'order');
        return $this->display(__FILE__, 'show_recommendation.tpl');
    }

}
