<?php

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

include_once _PS_MODULE_DIR_.'chcreateur/config/define.inc.php';
include_once _PS_MODULE_DIR_.'chcreateur/classes/chcreaimagetype.php';
include_once _PS_MODULE_DIR_.'chcreateur/classes/chcreapost.php';

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;

class Chcreateur extends Module implements WidgetInterface
{
	public $dbfiles = '/db/dbfiles.php';

	public function __construct()
	{
		$this->name = 'chcreateur';
		$this->tab = 'front_office_features';
		$this->version = '1.0.0';
		$this->author = 'Cedric Hansen';
		$this->need_instance = 0;
		$this->ps_versions_compliancy = [
			'min' => '1.6.0',
			'max' => '1.7.9',
		];
		$this->bootstrap = true;
		parent::__construct();

		$this->displayName = $this->l('CH createur');
		$this->description = $this->l("Presentation d'une createur ");

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

	/**
	 * @return [type]
	 */
	public function install()
	{
		if (Shop::isFeatureActive()) {
			Shop::setContext(Shop::CONTEXT_ALL);
		}

		return (
			parent::install()
			//
			//&& $this->registerHook('displayBlockPosition2')
			&& $this->registerHook('displayHeader')
			&& $this->registerHook('ModuleRoutes')
			&& $this->Register_SQL()
			&& $this->_installTab()
			&& Configuration::updateValue('CHCREATEUR_TITLE', 'Nos createurs')
			&& Configuration::updateValue('CHCREATEUR_URL', 'nos-createurs')
			&& Configuration::updateValue('CHCREATEUR_DESCRIPTION', 'Une description', true)
		);
	}

	/**
	 * @return [type]
	 */
	public function Register_SQL()
	{
		$querys = array();
		if (file_exists(dirname(__FILE__).$this->dbfiles)) {
			require_once(dirname(__FILE__).$this->dbfiles);
			if (isset($querys) && !empty($querys)) {
				foreach ($querys as $query) {
					if (!Db::getInstance()->Execute($query)) {
						return false;
					}
				}
			}
		}
		return true;
	}

		/**
     * Installation du controller dans la backoffice
     * @return boolean
     */
    protected function _installTab()
    {
        $tab = new Tab();
        $tab->class_name = 'AdminChcreateur';
        $tab->module = $this->name;
        $tab->id_parent = (int)Tab::getIdFromClassName('IMPROVE');
        $tab->icon = 'chat';
        $languages = Language::getLanguages();
        foreach ($languages as $lang) {
            $tab->name[$lang['id_lang']] = $this->l('Notre createur');
        }
        try {
            $tab->save();
        } catch (Exception $e) {
            echo $e->getMessage();
            return false;
        }

        return true;
    }

	/**
	 * @return [type]
	 */
	public function uninstall()
	{
		return (
			parent::uninstall()
			//&& $this->UnRegister_SQL()
			//&& Configuration::deleteByName('CHCREATEUR_NAME')
		);
	}

	/**
	 * @return [type]
	 */
	public function UnRegister_SQL()
	{
		$querys_u = array();
		if (file_exists(dirname(__FILE__).$this->dbfiles)) {
			require_once(dirname(__FILE__).$this->dbfiles);
			if (isset($querys_u) && !empty($querys_u)) {
				foreach ($querys_u as $query_u) {
					if (!Db::getInstance()->Execute($query_u)) {
						return false;
					}
				}
			}
		}
		return true;
	}

	/**
	 * @param mixed $params
	 * 
	 * @return $array
	 */
	public function hookModuleRoutes($params)
    {
		$chcreateurroutes = array(
			'chcreateur-archive-module' => [
				'controller' => 'archive',
				'rule' => Configuration::get('CHCREATEUR_URL'),
				'keywords' => [],
				'params' => [
					'fc' => 'module',
					'module' => 'chcreateur',
				]
			],
			'chcreateur-single-module' => [
				'controller' => 'single',
				'rule' => Configuration::get('CHCREATEUR_URL').'/{id}_{rewrite}',
				'keywords' => [
					'id' =>   array('regexp' => '[0-9]+','param' => 'id'),
                    'rewrite' =>   array('regexp' => '[_a-zA-Z0-9-\pL]*','param' => 'rewrite'),
				],
				'params' => [
					'fc' => 'module',
					'module' => 'chcreateur',
				]
			]
		);
	
		return $chcreateurroutes;
	}



	public function postProcess()
	{
		$output = '';

		//print_r($_POST);
		//print_r($_GET);

		// this part is executed only when the form is submitted
		if (Tools::isSubmit('submit' . $this->name)) {
			// retrieve the value set by the user
			$config_TITLE = (string) Tools::getValue('CHCREATEUR_TITLE');
			$config_URL = (string) Tools::getValue('CHCREATEUR_URL');
			$config_DESCRIPTION = (string) Tools::getValue('CHCREATEUR_DESCRIPTION');


			// check that the value is valid
			if (empty($config_TITLE) || !Validate::isGenericName($config_TITLE)) {
				// invalid value, show an error
				$output = $this->displayError($this->l('Invalid Configuration value'));
			} else {
				// value is ok, update it and display a confirmation message
				Configuration::updateValue('CHCREATEUR_TITLE', $config_TITLE);
				Configuration::updateValue('CHCREATEUR_URL', $config_URL);
				Configuration::updateValue('CHCREATEUR_DESCRIPTION', $config_DESCRIPTION, true);

				$output = $this->displayConfirmation($this->l('Settings updated'));
			}
		}
		if (Tools::isSubmit('updatechcrea_image_type') || Tools::getValue('addnew')) {
			return $output . $this->renderImageForm();
		}
		if (Tools::isSubmit('SubmitImageForm')) {
			if (Tools::getValue('id_image_type')) {
				$obj = new chcreaimagetypeclass(Tools::getValue('id_image_type'));
			} else {
				$obj = new chcreaimagetypeclass();
			}

			foreach (chcreaimagetypeclass::$definition['fields'] as $key => $value) {
				$obj->$key = Tools::getValue($key);
			}

			if (Tools::getValue('id_image_type')) {
				if ($obj->update()) {
					return $this->displayConfirmation($this->l('Settings Updated'));
				} else {
					return $this->displayError($this->l('Unable to update settings'));
				}
			} else {
				if ($obj->add()) {
					return $this->displayConfirmation($this->l('Settings Created'));
				} else {
					return $this->displayError($this->l('Unable to create settings'));
				}
			}
		}
	}

	/**
	 * @return string
	 * @throws PrestaShopDatabaseException
	 * @throws PrestaShopException
	 */
	public function getContent()
	{
		//$lien = Context::getContext()->link->getModuleLink('chcreateur', 'archive', array('idPayment' => 1337));
		//print($lien);
		$html  = $this->postProcess();
		$html .= $this->displayForm();
		$html .= $this->displayList();

		return $html;
	}

	/**
	 * Get configuration form
	 * @return string
	 * @throws PrestaShopDatabaseException
	 * @throws PrestaShopException
	 */
	protected function renderImageForm()
	{
		$fields_form = [
			'form' => [
				'description' => $this->l('Format des images generées pour les templates'),
				'legend' => [
					'title' => $this->l('Configure Image'),
					'icon' => 'icon-cogs'
				],

				'input' => [
					[
						'type' => 'hidden',
						'label' => $this->l('Enable for id'),
						'name' => 'id_image_type',
						'required' => true,
					],
					[
						'type' => 'hidden',
						'label' => $this->l('Enable for shop'),
						'name' => 'id_shop',
						'required' => true,
					],
					[
						'type' => 'text',
						'label' => $this->l('Name'),
						'name' => 'name',
						'required' => false,
					],
					[
					  'type' => 'text',
					  'label' => $this->l('Width of picture'),
					  'name' => 'width',
					  'required' => true,
					],
					[
					  'type' => 'text',
					  'label' => $this->l('Height of picture'),
					  'name' => 'height',
					  'required' => true,
					],
					[
						'type' => 'switch',
						'label' => $this->l('Status'),
						'name' => 'active',
						'required' => false,
						'class' => 't',
						'is_bool' => true,
						'values' => array(
							array(
								'id' => 'active',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						)
					],
				],
				'submit' => [
					'title' => $this->l('Save'),
					'icon' => 'icon-save',
					'class' => 'button btn btn-default pull-right',
				]
			],
		];

		$helper = new HelperForm();
		//$helper->show_toolbar = true;
		$helper->show_cancel_button = true;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$helper->identifier = "image_type";
		$helper->submit_action = 'SubmitImageForm';
		$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->getAddFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

		return $helper->generateForm([$fields_form]);
	}

	public function getAddFieldsValues()
	{
		$fields = array();

		$id_image_type = (int) Tools::getValue('id_image_type');
		if ($id_image_type == 0) {
			$obj = new Chcreaimagetypeclass();
			print("id_image_type:".$obj->id);
			print("</br>");
		} else {
			$obj = new Chcreaimagetypeclass($id_image_type);
		}

		$fields = [
			'id_image_type' => Tools::getValue('id_image_type', $obj->id),
			'name' => Tools::getValue('name', $obj->name),
			'width' => Tools::getValue('width', $obj->width),
			'height' => Tools::getValue('height', $obj->height),
			'active' => Tools::getValue('active', $obj->active),
			'id_shop' => Tools::getValue('id_shop', $obj->id_shop),
		];

		return $fields;
	}

	public function displayForm()
	{
		// Init Fields form array
		$form = [
			'form' => [
				'legend' => [
					'title' => $this->l('Settings'),
				],
				'input' => [
					[
						'type' => 'text',
						'label' => $this->l('Title'),
						'name' => 'CHCREATEUR_TITLE',
						'size' => 128,
						'required' => true,
					],
					[
						'type' => 'textarea',
						'label' => $this->l('Description'),
						'name' => 'CHCREATEUR_DESCRIPTION',
						'size' => 800,
						'required' => true,
					],
					[
						'type' => 'text',
						'label' => $this->l('Base URL'),
						'name' => 'CHCREATEUR_URL',
						'size' => 128,
						'required' => true,
					],
				],
				'submit' => [
					'title' => $this->l('Save'),
					'class' => 'btn btn-default pull-right',
				],
			],

		];

		$helper = new HelperForm();

		// Module, token and currentIndex
		$helper->table = $this->table;
		$helper->name_controller = $this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->currentIndex = AdminController::$currentIndex . '&' . http_build_query(['configure' => $this->name]);
		$helper->submit_action = 'submit' . $this->name;

		// Default language
		$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');

		// Load current value into the form
		$helper->fields_value['CHCREATEUR_TITLE'] = Tools::getValue('CHCREATEUR_TITLE', Configuration::get('CHCREATEUR_TITLE'));
		$helper->fields_value['CHCREATEUR_DESCRIPTION'] = Tools::getValue('CHCREATEUR_DESCRIPTION', Configuration::get('CHCREATEUR_DESCRIPTION'));
		$helper->fields_value['CHCREATEUR_URL'] = Tools::getValue('CHCREATEUR_URL', Configuration::get('CHCREATEUR_URL'));

		return $helper->generateForm([$form]);
	}


	public function displayList()
	{
		$fields_list = [
			'id_image_type' => [
				'title' => $this->l('Id'),
				//'width' => 140,
				'type'  => 'text',
			],
			'name' => [
				'title' => $this->l('Name'),
				//'width' => '100%',
				'type'  => 'texte',
			],
			'width' => [
				'title' => $this->l('Width'),
				//'width' => 140,
				'type'  => 'texte',
			],
			'height' => [
				'title' => $this->l('height'),
				//'width' => 140,
				'type'  => 'texte',
			],
			'active' => [
				'title' => $this->l('active'),
				//'width' => 30,
				'type'  => 'bool',
				'active' => 'status',
				'icon' => [
					0 => 'disabled.gif',
					1 => 'enabled.gif',
				  'default' => 'disabled.gif'
				],
			],
		];

		$helper = new HelperList();

		$helper->shopLinkType = '';

		$helper->simple_header = false;
		// Actions to be displayed in the "Actions" column
		$helper->actions = array('edit', 'delete');
		$helper->show_toolbar = true;
		$helper->identifier = 'id_image_type';
		$helper->toolbar_btn['new'] =  [
		  'href' => Context::getContext()->link->getAdminLink('AdminModules').'&addnew=true&configure='.$this->name,
		  'desc' => $this->l('Add new')
		];
		$helper->title = 'List Image Type';
		$helper->table = Chcreaimagetypeclass::$definition['table'];
		$helper->className = Chcreaimagetypeclass::class; //Classe de l'objet
		$helper->token = Tools::getAdminTokenLite('AdminModules');


		//$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
		//AdminController::$currentIndex.'&configure='.$this->name;
		$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;



		return $helper->generateList(Chcreaimagetypeclass::GetAllImageTypes(), $fields_list);
	}

	public function initToolbar()
	{
		parent::initToolbar();

		$this->toolbar_btn['new'] = array(
			'href' => $this->context->link->getAdminLink('some link'),
			'desc' => $this->l('some description')
		);
	}


	/*
	public function renderList()
	{
		$this->addRowAction('edit');
		$this->addRowAction('delete');
		return parent::renderList();
	}
	*/

	/**
	 * @param null $hookName
	 * @param array $configuration
	 *
	 * @return [type]
	 */
	public function renderWidget($hookName = null, array $configuration = [])
	{
		if ($hookName  == 'displayxipblogleft') {
			$this->smarty->assign($this->getWidgetVariables($hookName, $configuration));
			return $this->fetch('module:'.$this->name.'/views/templates/front/left-list.tpl');

		} elseif ( $hookName == 'displayBlockPosition2' ) {
			$this->smarty->assign($this->getWidgetVariables($hookName, $configuration));
			//print_r($this->getWidgetVariables($hookName, $configuration));
			//print($this->name);
			//return "voila";
			return $this->fetch('module:'.$this->name.'/views/templates/front/vignette.tpl');
		} else {
			$this->smarty->assign($this->getWidgetVariables($hookName, $configuration));
			//print_r($this->getWidgetVariables($hookName, $configuration));
			//print($this->name);
			//return "voila";
			return $this->fetch('module:'.$this->name.'/views/templates/front/'.$this->name.'.tpl');
		}
	}

	public function getWidgetVariables($hookName = null, array $configuration = [])
	{
		$id_lang             = (int)$this->context->language->id;
		//$xipbdp_title        = Configuration::get(self::$xipblogshortname.'xipbdp_title', $id_lang);
		// $xipbdp_subtext      = Configuration::get(self::$xipblogshortname.'xipbdp_subtext', $id_lang);
		// $xipbdp_postcount    = Configuration::get(self::$xipblogshortname.'xipbdp_postcount');

		//Media::addJsDef(array('xipbdp_numcolumn'=>$xipbdp_numcolumn));
		$chcreaposts = array();
		$chcreaposts = Chcreapost::getAllSelections(6);
		
		// print('<Pre>'.print_r($chcreaposts,true).'</pre>');
		// exit();


		

		return array(
			'chcrea_title'      => Configuration::get('CHCREATEUR_TITLE'),
			'chcrea_desc'       => Configuration::get('CHCREATEUR_DESCRIPTION'),
			'hookName'         => $hookName,
			'chposts'       => $chcreaposts,
			'vignettes_nbr' => count($chcreaposts),
		);
	}

	public static function getBaseLink($id_shop = null, $ssl = null, $relative_protocol = false)
    {
        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;
        }

        if ($relative_protocol) {
            $base = '//'.($ssl ? $shop->domain_ssl : $shop->domain);
        } else {
            $base = (($ssl) ? 'https://'.$shop->domain_ssl : 'http://'.$shop->domain);
        }

        return $base.$shop->getBaseURI();
    }


    public static function XipBlogPostLink($params = array())
    {
        $url_format = Configuration::get(self::$xipblogshortname."url_format");
        if(isset($params['id']) && !isset($params['rewrite'])) {
            $params['rewrite'] = xippostsclass::get_the_rewrite($params['id']);
        }
        if(!isset($params['id']) && isset($params['rewrite'])) {
            $params['id'] = xippostsclass::get_the_id($params['rewrite']);
        }
        if(!isset($params['page_type'])) {
            $params['page_type'] = 'post';
        }
        if($url_format == 'preid_seo_url') {
            $rule = 'xipblog-single-module';
            return self::XipBlogLink($rule, $params);
        } elseif ($url_format == 'postid_seo_url') {
            $rule = 'xipblog-single-aftrid-module';
            return self::XipBlogLink($rule, $params);
        } elseif ($url_format == 'wthotid_seo_url') {
            $rule = 'xipblog-single-wid-module';
            return self::XipBlogLink($rule, $params);
        } elseif ($url_format == 'default_seo_url') {
            return self::GetLinkObject()->getModuleLink("xipblog", "single", $params);
        } else {
            $rule = 'xipblog-single-module';
        }
    }
}