<?php
/**
* ---------------------------------------------------------------------------------
*
* This file is part of the 'giftonordermodule' module feature (main || related module)
* Developped for Prestashop platform.
* You are not allowed to use it on several site
* You are not allowed to redistribute this module
* This header must not be removed
*
* @category  giftonordermodule
* @author    OleaCorner <contact@oleacorner.com> <www.oleacorner.com>
* @copyright OleaCorner
* @version   4.3
* @license   XXX
*
* ---------------------------------------------------------------------------------
*/

require_once _PS_MODULE_DIR_.'giftonordermodule/Giftonorder.php';

class AdminOleagiftonorderController extends ModuleAdminController
{

	static $states_array;

	protected $position_identifier = 'position';

	public function __construct()
	{
		$this->bootstrap = true;
		$this->table = 'giftonorder';
		$this->className = 'Giftonorder';
		$this->lang = true;
		$this->addRowAction ('edit');
		$this->addRowAction('duplicate');
		$this->addRowAction ('delete');
		$this->bulk_actions = array(
			'delete' => array(
				'text' => $this->l('Delete selected'),
				'confirm' => $this->l('Delete selected items?')
			)
		);
		Giftonorder::oleaAddObjectTableAssociation ('giftonorder');

		$this->_defaultOrderBy = 'position';

		$this->criteria_type_names = array();
		$this->criteria_type_names[_GIFTONORDER_TYPE_SYSTEMATIC_] = $this->l('All Orders');
		$this->criteria_type_names[_GIFTONORDER_TYPE_FIRSTORDER_] = $this->l('First Order');
		$this->criteria_type_names[_GIFTONORDER_TYPE_NEXTORDER_] = $this->l('Re-Order');

		$this->fields_list = array(
			'id_giftonorder' => array(
				'title' => $this->l('ID'),
				'align' => 'center',
				'width' => 25
			),
			'active' => array(
				'title' => $this->l('Active'),
				'align' => 'center',
				'active' => 'status',
				'type' => 'bool',
				'width' => 30
			),
			'position' => array(
				'title' => $this->l('Position'),
				'width' => 40,
				'filter_key' => 'a!position',
				'align' => 'center',
				'position' => 'position'
			),
			'name' => array(
				'title' => $this->l('Name'),
				'filter_key' => 'b!name'
			),
			'criteria_type' => array(
				'title' => $this->l('Type'),
				'width' => 80,
				'callback' => 'callbackTypeName'
			),
			'criteria_cart_amount' => array(
				'title' => $this->l('Cart amount'),
				'width' => 70,
				'align' => 'right',
				'type' => 'price',
				'currency' => false
			),
			/*
			'allow_other_gift' => array(
				'title' => $this->l('Other'),
				'width' => 25,
				'align' => 'center',
				'icon' => array(
					0 => 'disabled.gif',
					1 => 'enabled.gif'
				),
				'type' => 'bool',
				'orderby' => false
			),
			*/
			'criteria_date_from' => array(
				'title' => $this->l('From'),
				'width' => 120,
				'type' => 'date',
				'align' => 'right'
			),
			'criteria_date_to' => array(
				'title' => $this->l('To'),
				'width' => 120,
				'type' => 'date',
				'align' => 'right'
			)
		);

		$this->fields_options = array(
			'general' => array(
				'title' => $this->l('General configuration'),
				'fields' => array(
					'OLEA_GIFTONORDER_AMOUNT_REDUC' => array(
						'title' => $this->l('Cart amount with reduction'),
						'desc' => $this->l('Include or not reduction when checking card amount'),
						'cast' => 'intval',
						'type' => 'bool',
						'default' => '0'
					),
					'OLEA_GIFTONORDER_ALLGIFTTPL' => array(
						'title' => $this->l('All gifts page full display'),
						'desc' => $this->l('For the FO page displaying all the gifts, choose a condensed or extended display'),
						'cast' => 'intval',
						'type' => 'bool',
						'default' => '0'
					),
					'GIFTONORDER_MESSAGE_ALLGIFTS' => array(
						'title' => $this->l('All gifts page message'),
						'desc' => $this->l('Top message displayed in the gift summary page of front office'),
						'cols' => 100,
						'rows' => 8,
						'type' => 'textareaLang',
						'autoload_rte' => true
					),
					'OLEA_GIFTONORDER_CMSID' => array(
						'title' => $this->l('CMS ID for all gifts page'),
						'desc' => $this->l('Set a CMS ID if you want to replace the default All Gifts page by a CMS page. 0 to keep default page.'),
						'cast' => 'intval',
						'type' => 'text',
						'default' => '0'
					),
				)
				,
				'submit' => array(
					'title' => $this->l('Save')
				)
			)
		);

		parent::__construct ();

		if (version_compare (_PS_VERSION_, '1.6') < 0)
		{
			$this->addJS (array(
				_PS_JS_DIR_.'tiny_mce/tiny_mce.js',
				_PS_JS_DIR_.'tinymce.inc.js'
			));
		}
	}

	public function callbackTypeName($value, $tr)
	{
		return $this->criteria_type_names[$tr['criteria_type']];
	}

	private function build_attribute_selector($criteria_attributes)
	{
		$retour = '';
		$irow = 0;
		$all_attributes_groups = AttributeGroup::getAttributesGroups (Context::getContext ()->cookie->id_lang);
		$criteria_attributes = explode (';', $criteria_attributes); // $obj->criteria_attributes
		$retour .= '<table>';
		foreach ($all_attributes_groups as $tr)
		{
			$id = (int)($tr['id_attribute_group']);
			$retour .= '
			<tr'.($irow ++ % 2 ? ' class="alt_row"' : '').'>
				<td style="vertical-align: top; padding: 4px 10px 4px 10px; cursor: pointer" onclick="openCloseLayer(\'#attributes_'.$id.'\');">'.$tr['name'].'</td>
				<td style="vertical-align: top; padding: 4px 0 4px 0; width: 340px">
					<span  style="cursor: pointer" class="bold" onclick="openCloseLayer(\'#attributes_'.$id.'\');">'.$this->l('<< Open >>').'</span>
					<div id="attributes_'.$id.'" style="display: none">
					<table class="table" cellpadding="0" cellspacing="0">
						<tr>
							<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'attributeBox['.$id.'][]\', this.checked)" /></th>
							<th width="100%">'.$this->l('Attribute').'</th>
						</tr>';
			$attributes = AttributeGroup::getAttributes ((int)(Context::getContext ()->cookie->id_lang), $id);
			foreach ($attributes as $attribute)
			{
				$retour .= '
						<tr>
							<td class="center"><input type="checkbox" name="attributeBox['.$id.'][]" value="'.$attribute['id_attribute'].'" class="noborder" '.(in_array ($attribute['id_attribute'], $criteria_attributes) ? 'CHECKED' : '').'/></td>
							<td>
								'.($tr['is_color_group'] ? '<div style="float: left; width: 18px; height: 12px; border: 1px solid #996633; background-color: '.$attribute['color'].'; margin-right: 4px;"></div>' : '').$attribute['name'].'
							</td>
						</tr>';
			}
			$retour .= '
					</table>
					</div>
					</td>';

			$retour .= '
			</tr>';
		}
		$retour .= '</table>';

		return $retour;
	}

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

		$this->addJs (_PS_JS_DIR_.'admin-categories-tree.js');
	}

    public function renderListNotused()
    {
        $this->addRowAction('duplicate');
        $this->addRowAction('delete');
        return parent::renderList();
    }

	public function renderForm()
	{
		if (!($obj = $this->loadObject (true)))
			return;
		$obj->criteria_cart_amount = number_format ($obj->criteria_cart_amount, 2);
		$obj->criteria_categroy_amount = number_format ($obj->criteria_category_amount, 2);

		$id_category = (int)Configuration::get ('OLEA_GIFTONORDER_GIFT_CATEGORY');
		if ($id_category)
			$prods_list = Product::getProducts (Context::getContext ()->cookie->id_lang, 0, 0, 'name', 'asc', $id_category);
		else
			$prods_list = array();

		$order_types = array();
		foreach ($this->criteria_type_names as $id_type => $type_name)
			$order_types[] = array(
				'id_type' => $id_type,
				'name' => $type_name
			);

		$carrier_groups_ids = $obj->getGroups ();
		$groups = Group::getGroups ($this->context->language->id);
		foreach ($groups as $group)
			$this->fields_value['groupBox_'.$group['id_group']] = Tools::getValue ('groupBox_'.$group['id_group'], (in_array ($group['id_group'], $carrier_groups_ids) || empty ($carrier_groups_ids) && !$obj->id));

		$manufacturers = array_merge (array(
			array(
				'name' => $this->l('-- Any manufacturers --'),
				'id_manufacturer' => 'any'
			)
		), Manufacturer::getManufacturers ());
		$manufacturers_ids = $obj->getManufacturers ();
		foreach ($manufacturers as $manufacturer)
			$this->fields_value['manufacturers_'.$manufacturer['id_manufacturer']] = Tools::getValue ('manufacturer_'.$manufacturer['id_manufacturer'], (in_array ($manufacturer['id_manufacturer'], $manufacturers_ids) || empty ($manufacturers_ids) && !$obj->id));

		$suppliers = array_merge (array(
			array(
				'name' => $this->l('-- Any suppliers --'),
				'id_supplier' => 'any'
			)
		), Supplier::getSuppliers ());
		$suppliers_ids = $obj->getSuppliers ();
		foreach ($suppliers as $supplier)
			$this->fields_value['suppliers_'.$supplier['id_supplier']] = Tools::getValue ('supplier_'.$supplier['id_supplier'], (in_array ($supplier['id_supplier'], $suppliers_ids) || empty ($suppliers_ids) && !$obj->id));

		$this->fields_value['gift_id_product_list[]'] = explode (',', $obj->gift_id_product_list);

		$helper = new Helper ();
		if ($obj->criteria_categories == 'vide')
			$selected_cat = array();
		elseif ((string)$obj->criteria_categories == '')
		{
			$selected_cat = array();
			foreach (Category::getCategories (false, false, false) as $cat)
				$selected_cat[$cat['id_category']] = $cat;
		}
		else
			$selected_cat = Category::getCategoryInformations (explode (';', $obj->criteria_categories));
		$category_tree = $helper->renderCategoryTree (null, $selected_cat, 'categoryBox', true, false /*use_search*/, array(), false, true);

		$categories_selector = (version_compare ('1.6', _PS_VERSION_) <= 0) ? array(
			'type' => 'categories',
			'label' => $this->l('Associated categories:'),
			'name' => 'categoryBox',
			'tree' => array(
				'id' => 'id_category',
				'name' => 'name_category',
				'selected_categories' => array_keys ($selected_cat),
			    'root_category' => Configuration::get('PS_HOME_CATEGORY'),
				'use_search' => 'true',
				'use_checkbox' => 'true'
			)
		) : array(
			'type' => 'categories_select',
			'name' => 'categoryBox',
			'label' => $this->l('Associated categories:'),
			'category_tree' => $category_tree,
			'use_search' => false,
			'desc' => $this->l('Categories to which the cart product must belong to')
		);

		$inline_script = '<script>
			$(document).ready(function(){
				'.((version_compare ('1.6', _PS_VERSION_) <= 0) ? '$(\'#suppliers_any\').closest(\'.checkbox\').siblings(\'.checkbox\').addClass(\'select_criteria_suppliers\');
				$(\'#suppliers_any\').removeClass(\'select_criteria_suppliers\');
				$(\'#manufacturers_any\').closest(\'.checkbox\').siblings(\'.checkbox\').addClass(\'select_criteria_manufacturers\');
				$(\'#manufacturers_any\').removeClass(\'select_criteria_manufacturers\');
				' : '$(\'#suppliers_any\').siblings().addClass(\'select_criteria_suppliers\');
				$(\'#suppliers_any\').removeClass(\'select_criteria_suppliers\');
				$(\'#manufacturers_any\').siblings().addClass(\'select_criteria_manufacturers\');
				$(\'#manufacturers_any\').removeClass(\'select_criteria_manufacturers\');
				').

		'	$(\'#suppliers_any\').change(function () {
					if ($(this).attr(\'checked\') == \'checked\')
						$(\'.select_criteria_suppliers\').hide();
					else
						$(\'.select_criteria_suppliers\').show();
				})
				.next().removeClass(\'select_criteria_suppliers\');
				if ($(\'#suppliers_any\').attr(\'checked\') == \'checked\')
					$(\'.select_criteria_suppliers\').hide();

				$(\'#manufacturers_any\').change(function () {
					if ($(this).attr(\'checked\') == \'checked\')
						$(\'.select_criteria_manufacturers\').hide();
					else
						$(\'.select_criteria_manufacturers\').show();
				})
				.next().removeClass(\'select_criteria_manufacturers\');
				if ($(\'#manufacturers_any\').attr(\'checked\') == \'checked\')
					$(\'.select_criteria_manufacturers\').hide();

				});
		</script>';

		$this->multiple_fieldsets = true;
		$this->fields_form = array(
			array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Gift on order')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'radio',
							'label' => $this->l('Enable:'),
							'name' => 'active',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'active_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'active_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							)
						),
						array(
							'type' => 'text',
							'label' => $this->l('Name:'),
							'name' => 'name',
							'size' => 33,
							'required' => true,
							'lang' => true
						),
						array(
							'type' => 'textarea',
							'label' => $this->l('Description:'),
							'name' => 'description',
							'cols' => 50,
							'rows' => 5,
							'required' => false,
							'lang' => true,
							'desc' => $this->l('Your personnal note on this rule')
						),
						array(
							'type' => 'select',
							'multiple' => true,
							'label' => $this->l('Gifts to offer'),
							'name' => 'gift_id_product_list[]',
							'desc' => $this->l('Multiple select to allow customer to choose his gift'),
							'empty_message' => $this->l('ERROR : the gift category must be initialized from the module configuration pane'),
							'options' => array(
								'query' => $prods_list,
								'id' => 'id_product',
								'name' => 'name'
							),
							'size' => 10,
							'class' => 'gift_id_product_list_selector',
							'onchange' => 'goochangeonselect()'
						),
						array(
							'type' => 'select',
							'label' => $this->l('Default gift'),
							'name' => 'gift_id_product',
							'desc' => $this->l('Default gift in case of multiple gifts choice'),
							'empty_message' => $this->l('ERROR : the gift category must be initialized from the module configuration pane'),
							'options' => array(
								'query' => $prods_list,
								'id' => 'id_product',
								'name' => 'name'
							)
						),
						array(
							'type' => 'radio',
							'label' => $this->l('Allows other gifts:'),
							'name' => 'allow_other_gift',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'allow_other_gift_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'allow_other_gift_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							),
							'desc' => $this->l('Autorize execution of following rule when this one offers a gift')
						)
					)
				)
			),
			array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Global criteria')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'text',
							'label' => $this->l('Minimum cart amount:'),
							'name' => 'criteria_cart_amount',
							'size' => 10,
							'desc' => $this->l('Minimum cart amount to offer the gift, port excluded'),
							'suffix' => '€ Tx Incl.'
						),
						array(
							'type' => 'date',
							'label' => $this->l('Date from:'),
							'name' => 'criteria_date_from',
							'size' => 20,
							'maxlength' => 10,
							'required' => true,
							'desc' => $this->l('Format: YYYY-MM-DD')
						),
						array(
							'type' => 'date',
							'label' => $this->l('Date to:'),
							'name' => 'criteria_date_to',
							'size' => 20,
							'maxlength' => 10,
							'required' => true,
							'desc' => $this->l('Format: YYYY-MM-DD')
						)
					)
				)
			),
			array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Customer criteria')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'select',
							'label' => $this->l('Order type'),
							'name' => 'criteria_type',
							'desc' => $this->l('Type of order on which the gift is offered'),
							'options' => array(
								'query' => $order_types,
								'id' => 'id_type',
								'name' => 'name'
							)
						),
						array(
							'type' => 'text',
							'label' => $this->l('Maximum per customer:'),
							'name' => 'criteria_max_per_customer',
							'size' => 10,
							'desc' => $this->l('Let 0 for no limit')
						),
						array(
							'type' => 'group',
							'label' => $this->l('Group access:'),
							'name' => 'groupBox',
							'values' => $groups,
							'desc' => $this->l('Customer group to which the gift can be offered')
						)
					)
				)
			),
			array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Product criteria')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'text',
							'label' => $this->l('Nb different products:'),
							'name' => 'criteria_different_products',
							'size' => 10,
							'desc' => $this->l('Number of different product to detect in a association')
						),
						array(
							'type' => 'text',
							'label' => $this->l('Nb associations:'),
							'name' => 'criteria_nb_products',
							'size' => 10,
							'desc' => $this->l('Number of association to detect in the cart')
						),
						array(
							'type' => 'radio',
							'label' => $this->l('Gift on each association:'),
							'name' => 'criteria_qty_multiple',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'criteria_qty_multiple_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'criteria_qty_multiple_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							),
							'desc' => $this->l('Attribute the gift on each association found in the cart')
						),
						array(
							'type' => 'text',
							'label' => $this->l('Minimum categories amount:'),
							'name' => 'criteria_category_amount',
							'size' => 10,
							'desc' => $this->l('Minimum amount to detect in the following categories'),
							'suffix' => '€ Tx Incl.'
						),
						array(
							'type' => 'radio',
							'label' => $this->l('Include discounted products:'),
							'name' => 'criteria_cumulable_reduced_products',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'criteria_cumulable_reduced_products_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'criteria_cumulable_reduced_products_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							),
							'desc' => $this->l('Include discounted product in products detection')
						),

						$categories_selector,

						array(
							'type' => 'categories_select',
							'name' => 'attributesBox_unused',
							'label' => $this->l('Products attributes:'),
							'category_tree' => $this->build_attribute_selector ($obj->criteria_attributes),
							'desc' => $this->l('Attributes the products must have to offer the gift')
						),
						array(
							'type' => 'radio',
							'label' => $this->l('Product with all attributes:'),
							'name' => 'criteria_attributes_detectsall',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'criteria_attributes_detectsall_on',
									'value' => 1,
									'label' => $this->l('All')
								),
								array(
									'id' => 'criteria_attributes_detectsall_off',
									'value' => 0,
									'label' => $this->l('At least one')
								)
							),
							'desc' => $this->l('Include products that have either all either at least one attribute of the previous selection')
						),
						array(
							'type' => 'categories_select',
							'name' => 'name_toto',
							'category_tree' => $inline_script
						),
						array(
							'type' => 'checkbox',
							'label' => $this->l('Suppliers:'),
							'name' => 'suppliers',
							'values' => array(
								'query' => $suppliers,
								'id' => 'id_supplier',
								'name' => 'name'
							),
							'desc' => $this->l('Supplier of the products'),
							'class' => 'select_criteria_suppliers'
						),
						array(
							'type' => 'checkbox',
							'label' => $this->l('Manufacturers:'),
							'name' => 'manufacturers',
							'values' => array(
								'query' => $manufacturers,
								'id' => 'id_manufacturer',
								'name' => 'name'
							),
							'desc' => $this->l('Manufacturer of the product'),
							'class' => 'select_criteria_manufacturers'
						)
					)
				)

			),
			array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Customer communication')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'radio',
							'label' => $this->l('Communication in front office:'),
							'name' => 'fo_display',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'fo_display_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'fo_display_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							),
							'desc' => $this->l('Indicates if this rule must be displayed in the all gifts page summary in front office')
						),
						array(
							'type' => 'textarea',
							'lang' => true,
							'cols' => 80,
							'rows' => 10,
							'autoload_rte' => true,
							'label' => $this->l('Front Office message:'),
							'name' => 'message_fo',
							'size' => 50,
							'desc' => $this->l('Message displayed displayed in the all gifts page summary in extended mode')
						),
						array(
							'type' => 'text',
							'lang' => true,
							'label' => $this->l('Gift selection message:'),
							'name' => 'gift_selector_message',
							'size' => 50,
							'desc' => $this->l('Message displayed before the gift selection in the order summary page')
						),
						array(
							'type' => 'radio',
							'label' => $this->l('Gift preselection in product page:'),
							'name' => 'gift_preselector_product_page',
							'required' => false,
							'class' => 't',
							'is_bool' => true,
							'values' => array(
								array(
									'id' => 'gift_preselector_product_page_on',
									'value' => 1,
									'label' => $this->l('Enabled')
								),
								array(
									'id' => 'gift_preselector_product_page_off',
									'value' => 0,
									'label' => $this->l('Disabled')
								)
							),
							'desc' => $this->l('If activated, the gift choice will be proposed in the product page in front office')
						)
					)
				)
			)
		);

		if (Shop::isFeatureActive ())
		{
			$this->fields_form[] = array(
				'form' => array(
					'legend' => array(
						'title' => $this->l('Shop association')
					),
					'submit' => array(
						'title' => $this->l('Save')
					),
					'input' => array(
						array(
							'type' => 'shop',
							'label' => $this->l('Shop association:'),
							'name' => 'checkBoxShopAsso'
						)
					)
				)
			);
		}

		return parent::renderForm ();
	}

	protected function copyFromPost(&$object, $table)
	{
		$products = array_filter (Tools::getValue ('gift_id_product_list'), 'intval');
		$discounts = array_map ('pSQL', explode (';', Tools::getValue ('criteria_discounts')));
		parent::copyFromPost ($object, $table);
		$object->gift_id_product_list = implode (',', array_filter ($products));
		$object->criteria_discounts = implode (';', array_map ('trim', $discounts));
		if (get_class ($object) != $this->className)
			return;

		$cat_box = Tools::getValue('categoryBox');
		if (count ($cat_box))
			$object->criteria_categories = implode (';', array_filter ($cat_box));
		else
			$object->criteria_categories = 'vide';

		if ($object->position == 0)
		{
			$sqlReq = '
				SELECT IFNULL(MAX(`position`), 0) + 1 AS max
				FROM `'._DB_PREFIX_.$this->table.'` a
				WHERE 1';
			$queryPosition = Db::getInstance ()->getRow ($sqlReq);
			$object->position = $queryPosition['max'];
		}

		$attributes_box = (array)Tools::getValue('attributeBox');
		if (isset($attributes_box[0]))
			unset($attributes_box[0]);
		if (count ($attributes_box))
		{
			$all_attributes = array();
			foreach ($attributes_box as $attr)
				$all_attributes = array_merge ($all_attributes, $attr);
			$object->criteria_attributes = implode (';', array_filter ($all_attributes));
		}
		else
			$object->criteria_attributes = '';

		$manufacturers = array();
		$suppliers = array();
		foreach ($_POST as $kpost => $vpost)
		{
			if (Tools::substr ($kpost, 0, 14) == 'manufacturers_')
				$manufacturers[] = str_replace ('manufacturers_', '', $kpost);
			if (Tools::substr ($kpost, 0, 10) == 'suppliers_')
				$suppliers[] = str_replace ('suppliers_', '', $kpost);
		}
		$object->setManufacturers ($manufacturers);
		$object->setSuppliers ($suppliers);
	}

	protected function afterAdd($object)
	{
		$object->updateGroup (Tools::getValue ('groupBox'));
		return true;
	}

	protected function afterUpdate($object)
	{
		$object->updateGroup (Tools::getValue ('groupBox'));
		return true;
	}

    public function initToolbarNotUsed()
	{
		parent::initToolbar ();
		unset ($this->toolbar_btn['new']);
	}

    public function initProcess()
    {
    	if (Tools::getIsset('duplicate'.$this->table)) {
    		if ($this->tabAccess['add'] === '1') {
    			$this->action = 'duplicate';
    		} else {
    			$this->errors[] = Tools::displayError('You do not have permission to add this.');
    		}
    	}
		else
	    	parent::initProcess();
    }

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

		foreach ($positions as $position => $value)
		{
			$pos = explode ('_', $value);

			if (isset ($pos[2]) && (int)$pos[2] === $id_giftonorder)
			{
				if ($giftonorder = new Giftonorder ((int)$pos[2]))
					if (isset ($position) && $giftonorder->updatePosition ($way, $position))
						echo 'ok position '.(int)$position.' for giftonorder '.(int)$pos[1].'\r\n';
					else
						echo '{"hasError" : true, "errors" : "Can not update giftonorder '.(int)$id_giftonorder.' to position '.(int)$position.' "}';
				else
					echo '{"hasError" : true, "errors" : "This giftonorder ('.(int)$id_giftonorder.') can t be loaded"}';

				break;
			}
		}
	}

	public function processDuplicate()
	{
		if (Validate::isLoadedObject($old_giftonorder = new Giftonorder((int)Tools::getValue('id_giftonorder')))) {
			$new_giftonorder = new Giftonorder((int)Tools::getValue('id_giftonorder'));
			unset ($new_giftonorder->id);
			unset ($new_giftonorder->id_giftonorder);
			$new_giftonorder->active = false;
			$new_giftonorder->save();

			$new_giftonorder->addGroups($old_giftonorder->getGroups());
			$new_giftonorder->addShops($old_giftonorder->getShops());

			$this->redirect_after = self::$currentIndex.'&conf=19&token='.$this->token;
		}
	}
}
