<?php

include_once _PS_MODULE_DIR_.'chcreateur/classes/chcreapost.php';
include_once _PS_MODULE_DIR_.'chcreateur/classes/chcreaimages.php';



class AdminChcreateurController extends ModuleAdminController
{
	public function __construct()
	{
		$this->table = 'chcreaposts';
		$this->className = 'Chcreapost';
		$this->name = 'AdminChcreateur';
		$this->lang = true;
		$this->deleted = false;
		$this->module = 'chcreateur';
		$this->position_identifier = 'id_chcreaposts';
		$this->allow_export = false;
		$this->bootstrap = true;
		if (Shop::isFeatureActive()) {
			Shop::addTableAssociation($this->table, ['type' => 'shop']);
		}
		parent::__construct();

		$this->fields_list = [
			'id_chcreaposts' => [
				'title' => $this->l('Id'),
				'width' => 100,
				'type' => 'text',
			],
			'id_temp' => [
				'title' => 'Image',
				'align' => 'center',
				'callback' => 'getImage',

			],
			'post_title' => [
				'title' => $this->l('Post Title'),
				'width' => 60,
				'type' => 'text',
			],
			'post_excerpt' => [
				'title' => $this->l('Excerpt'),
				'width' => 220,
				'type' => 'text',
			],
			'link_rewrite' => [
				'title' => $this->l('URL Rewrite'),
				'width' => 220,
				'type' => 'text',
			],
			'post_format' => [
				'title' => $this->l('Format'),
				'width' => 20,
				'type' => 'text',
			],
			'position' => [
				'title' => $this->l('Position'),
				'align' => 'left',
				'filter_key' => 'a!position',
				'position' => 'position',
				// 'orderby' => false
			],
			/*
			'post_date' => [
				'title' => $this->l('Date'),
				'align' => 'text-right',
				'type' => 'datetime',
				'filter_key' => 'post_date',
			],
			*/
			'active' => [
				'title' => $this->l('Status'),
				'width' => 60,
				'align' => 'center',
				'active' => 'status',
				'type' => 'bool',
				'orderby' => false,
			],
		];
		$this->bulk_actions = [
			'delete' => [
				'text' => $this->l('Delete selected'),
				'icon' => 'icon-trash',
				'confirm' => $this->l('Delete selected items?'),
			],
		];
		parent::__construct();
	}

	public function getImage($id, $col)
	{
		$Chcreaimages = new Chcreaimages();
		$imgs = $Chcreaimages->getUrls($id);
		if ( count($imgs) < 1  ) {
			$html = '';
		} else {
			$html = '<a href="#"><img src="'.$imgs[0].'" height="50px" ></a>';
		}
		return $html;
	}

	public function __initToolbar()
	{
		parent::initToolbar();
		/*
		$this->toolbar_btn['custom'] = array(
				'href' => '',
				'desc' => 'Un nouveau'
		);
		*/
		// print_r($this->toolbar_btn);exit();
	}

	public function init()
	{
		parent::init();
		$this->_join = 'LEFT JOIN '._DB_PREFIX_.'chcreaposts_shop sbp ON a.id_chcreaposts=sbp.id_chcreaposts && sbp.id_shop IN('.implode(',', Shop::getContextListShopID()).')';
		$this->_select = 'a.`id_chcreaposts` as `id_temp`'; 
		$this->_orderBy = 'a.position';
	}

	public function setMedia($isNewTheme = false)
	{
		parent::setMedia();
		$this->addJqueryUi('ui.widget');
		$this->addJqueryPlugin('tagify');
		$this->addJqueryPlugin('select2');

		//$this->context->controller->addJS(chcrea_js_dir.'validator.min.js');
	}

	public function renderForm()
	{
		$id_chcreaposts = Tools::getValue('id_chcreaposts');
		$audio_temp = '';
		$video_temp = '';
		$gallery_temp = [];
		$gallery_temp_str = '';
		$post_img_temp = '';
		$prod_temp = '';
		$gallery_url = chcrea_img_uri;

		if (isset($id_chcreaposts) && !empty($id_chcreaposts)) {
			$Chcreapost = new Chcreapost($id_chcreaposts);
			if (isset($Chcreapost->audio) && !empty($Chcreapost->audio)) {
				$audio_temp = @explode(',', $Chcreapost->audio);
			}
			if (isset($Chcreapost->related_products) && !empty($Chcreapost->related_products)) {
				$prod_temp = @explode(',', $Chcreapost->related_products);
			}
			if (isset($Chcreapost->video) && !empty($Chcreapost->video)) {
				//$video_temp = @explode(',', $Chcreapost->video);
				$video_temp = $Chcreapost->video;
			}
			// if (isset($Chcreapost->gallery) && !empty($Chcreapost->gallery)) {
			// 	$gallery_temp = @explode(',', $Chcreapost->gallery);
			// 	$gallery_temp_str = $Chcreapost->gallery;
			// }
			// if (isset($Chcreapost->post_img) && !empty($Chcreapost->post_img)) {
			// 	$post_img_temp = '<img src="'.chcrea_img_uri.$Chcreapost->post_img.'" height="110" width="auto"><br>';
			// }
			$Chcreaimages = new Chcreaimages();
			$imgs = $Chcreaimages->getUrls($id_chcreaposts);
			if ( is_array($imgs) ){
				foreach($imgs as $img) {
					$post_img_temp .= '<img src="'.$img.'" height="110" width="auto"><br>';
				}
			}
			$gallery_url = chcrea_img_uri.'/'. $id_chcreaposts .'/';
			$Chcreaimages = new Chcreaimages();
			$imgs = $Chcreaimages->getGallery($id_chcreaposts);
			foreach($imgs as $value) {

				$gallery_temp[$value['id_images']] = $value['name'];
			}

			// print("<pre>".print_r($gallery_temp,true)."</pre>");
			// exit();


		}
		$this->fields_form = [
			'description' => "Le format des images : 1200 x 678",
			'legend' => [
				'title' => $this->l('Add New Post'),
			],
			'input' => [
				/*
				[
					'type' => 'radio',
					'label' => $this->l('Post Format'),
					'name' => 'post_format',
					'required' => false,
					'class' => 't',
					'is_bool' => true,
					'values' => [
						[
							'id' => 'standrad',
							'value' => 'standrad',
							'label' => $this->l('Standard'),
						],
						[
							'id' => 'gallery',
							'value' => 'gallery',
							'label' => $this->l('Gallery'),
						],
						[
							'id' => 'video',
							'value' => 'video',
							'label' => $this->l('Video'),
						],
						[
							'id' => 'audio',
							'value' => 'audio',
							'label' => $this->l('Audio'),
						],
					],
				],
				*/
				[
					'type' => 'text',
					'label' => $this->l('Post Title'),
					'name' => 'post_title',
					'id' => 'name', // for copyMeta2friendlyURL compatibility
					'class' => 'copyMeta2friendlyURL',
					'desc' => $this->l('Enter Your Blog Post Title'),
					'lang' => true,
				],
				[
					'type' => 'textarea',
					'label' => $this->l('Post Excerpt'),
					'name' => 'post_excerpt',
					'desc' => $this->l('Enter Your Blog Post Excerpt'),
					'lang' => true,
				],
				[
					'type' => 'textarea',
					'label' => $this->l('Post Content'),
					'name' => 'post_content',
					'desc' => $this->l('Enter Your Blog Post Content'),
					'lang' => true,
					'autoload_rte' => true,
				],
				[
					'type' => 'text',
					'label' => $this->l('Meta Title'),
					'name' => 'meta_title',
					'desc' => $this->l('Enter Your Post Meta Title for SEO'),
					'lang' => true,
				],
				[
					'type' => 'textarea',
					'label' => $this->l('Meta Description'),
					'name' => 'meta_description',
					'desc' => $this->l('Enter Your Post Meta Description for SEO'),
					'lang' => true,
				],
				[
					'type' => 'tags',
					'label' => $this->l('Meta Keyword'),
					'name' => 'meta_keyword',
					'desc' => $this->l('Enter Your Post Meta Keyword for SEO. Separate by comma(,)'),
					'lang' => true,
				],
				
				[
					'type' => 'file',
					'label' => "Meta Image </br> 1200 x 678",
					'name' => 'post_img',
					'desc' => $post_img_temp.$this->l('Format Please Upload Feature Image From Your Computer.'),
				],
				
				[
					'type' => 'select_multiple',
					// 'type' => 'select',
					'label' => $this->l('Select Related Products'),
					'name' => 'related_products_temp',
					'defaults' => $prod_temp,
					'options' => [
						'query' => self::getallproducts(),
						'id' => 'id',
						'name' => 'name',
					],
				],
				[
					'type' => 'gallery',
					'label' => "Image dans l'article </br> 1200 x 678",
					'name' => 'gallery_temp',
					'defaults' => $gallery_temp,
					'defaults_str' => $gallery_temp_str,
					'url' => $gallery_url,
					'desc' => $this->l('Please give Image url for Gallery post. Separate by comma(,). You can add Any Kind of Image URL.'),
				],
				/*
				[
					// 'type' => 'textarea',
					'type' => 'textarea',
					'label' => $this->l('Video'),
					'name' => 'video_temp',
					'defaults' => $video_temp,
					'desc' => $this->l('Please give video iframe url for video post. Separate by comma(,). You can add youtube or vimeo video url.'),
				],
				*/
				[
					// 'type' => 'textarea',
					'type' => 'textarea',
					'label' => $this->l('Video'),
					'name' => 'video',
					//'defaults' => $video_temp,
					'desc' => $this->l('Please give video iframe url for video post. Separate by comma(,). You can add youtube or vimeo video url.'),
				],
				[
					'type' => 'textarea',
					//'type' => 'text_multiple',
					'label' => $this->l('Audio'),
					'name' => 'audio',
					//'name' => 'audio_temp',
					//'defaults' => $audio_temp,
					'desc' => $this->l('Please give Audio url for Audio post. Separate by comma(,). You can add any kind of an audio source.'),
				],
				[
					'type' => 'text',
					'label' => $this->l('URL Rewrite'),
					'name' => 'link_rewrite',
					'desc' => $this->l('Enter Your Post Url for SEO'),
					'lang' => true,
				],
				[
					'type' => 'select',
					'label' => $this->l('Comment Status'),
					'name' => 'comment_status',
					'options' => [
						'query' => [
							[
								'id' => 'open',
								'name' => 'Open',
							],
							[
								'id' => 'close',
								'name' => 'Closed',
							],
							[
								'id' => 'disable',
								'name' => 'Disabled',
							],
						],
						'id' => 'id',
						'name' => 'name',
					],
				],
				[
					'type' => 'switch',
					'label' => $this->l('Status'),
					'name' => 'active',
					'required' => false,
					'class' => 't',
					'is_bool' => true,
					'values' => [
						[
							'id' => 'active',
							'value' => 1,
							'label' => $this->l('Enabled'),
						],
						[
							'id' => 'active',
							'value' => 0,
							'label' => $this->l('Disabled'),
						],
					],
				],
			],
			'submit' => [
				'title' => $this->l('Save'),
				'class' => 'btn btn-default pull-right',
			],
		];
		if (Shop::isFeatureActive()) {
			$this->fields_form['input'][] = [
				'type' => 'shop',
				'label' => $this->l('Shop association:'),
				'name' => 'checkBoxShopAsso',
			];
		}
		if (!($Chcreapost = $this->loadObject(true))) {
			return;
		}
		$this->setdefaultvalue($Chcreapost);
		$this->fields_form['submit'] = [
			'title' => $this->l('Save   '),
			'class' => 'btn btn-default pull-right',
		];
		$this->tpl_form_vars = [
			'active' => $this->object->active,
			'PS_ALLOW_ACCENTED_CHARS_URL', (int) Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL'),
		];
		Media::addJsDef(['PS_ALLOW_ACCENTED_CHARS_URL' => (int) Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL')]);

		// print('<pre>'.print_r($this->fields_form,true).'</pre>');exit();
		// print('<pre>'.print_r($this->override_folder,true).'</pre>');exit();

		return parent::renderForm();
	}

	public function setdefaultvalue($obj)
	{
		if (isset($obj->post_format) && !empty($obj->post_format)) {
			$this->fields_value['post_format'] = $obj->post_format;
		} else {
			$this->fields_value['post_format'] = 'standrad';
		}
		if (isset($obj->active) && !empty($obj->active)) {
			$this->fields_value['active'] = $obj->active;
		} else {
			$this->fields_value['active'] = 1;
		}
	}

	public function renderList()
	{
		if (isset($this->_filter) && '' == trim($this->_filter)) {
			$this->_filter = $this->original_filter;
		}
		$this->addRowAction('edit');
		$this->addRowAction('delete');

		return parent::renderList();
	}

	public static function getallproducts()
	{
		$rslt = [];
		$rslt[0]['id'] = 0;
		$rslt[0]['name'] = 'Select Products';
		$id_lang = (int) Context::getContext()->language->id;
		$sql = 'SELECT p.`id_product`, pl.`name`
				FROM `'._DB_PREFIX_.'product` p
				'.Shop::addSqlAssociation('product', 'p').'
				LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` '.Shop::addSqlRestrictionOnLang('pl').')
				WHERE pl.`id_lang` = '.(int) $id_lang.' ORDER BY pl.`name`';
		$products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
		if (isset($products)) {
			$i = 1;
			foreach ($products as $r) {
				$rslt[$i]['id'] = $r['id_product'];
				$rslt[$i]['name'] = $r['name'];
				++$i;
			}
		}

		return $rslt;
	}

	public function processPosition()
	{
		// ------------------------------------------------------------------------------
		// error_log("-----:function:".__FUNCTION__, 0);

		     
        print_r($_POST);
        exit();

		if ('1' !== $this->tabAccess['edit']) {
			$this->errors[] = Tools::displayError('You do not have permission to edit this.');
		} elseif (!Validate::isLoadedObject($object = new Chcreapost((int) Tools::getValue($this->identifier, Tools::getValue('id_chcreaposts', 1))))) {
			$this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').' <b>'.
			$this->table.'</b> '.Tools::displayError('(cannot load object)');
		}
		if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
			$this->errors[] = Tools::displayError('Failed to update the position.');
		} else {
			$object->regenerateEntireNtree();
			Tools::redirectAdmin(self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_chcreaposts = (int) Tools::getValue($this->identifier)) ? ('&'.$this->identifier.'='.$id_chcreaposts) : '').'&token='.Tools::getAdminTokenLite('Adminxipcategory'));
		}
	}

	public function ajaxProcessUpdatePositions()
	{
		$id_chcreaposts = (int) Tools::getValue('id');
		$way = (int) Tools::getValue('way');
		$positions = Tools::getValue($this->table);

		if (is_array($positions)) {
			foreach ($positions as $key => $value) {
				$pos = explode('_', $value);
				if ((isset($pos[1], $pos[2])) && ($pos[2] == $id_chcreaposts)) {
					$position = $key + 1;

					break;
				}
			}
		}
		$Chcreapost = new Chcreapost($id_chcreaposts);

		if (Validate::isLoadedObject($Chcreapost)) {
			if (isset($position) && $Chcreapost->updatePosition($way, $position)) {
				Hook::exec('action'.$this->className.'Update');

				exit(true);
			}

			exit('{"hasError" : true, errors : "Can not update Chcreapost position"}');
		}

		exit('{"hasError" : true, "errors" : "This Chcreapost can not be loaded"}');
	}

}
