<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Форма добаления/редактирования скидок.
 *
 * Файл: /admin/shop/action/form_edit_add_discount.php
 *
 * @author Hostmake LLC
 * @version 5.x
 */
if (isset($id))
{
	$edit_discount = $id;
}
else
{
	$edit_discount = 0;
}
$datetime = & singleton('DateClass');

$form_params = array();

$form_params['title'] = $edit_discount==0?$GLOBALS['MSG_shops']['item_discount_add_form_title']:$GLOBALS['MSG_shops']['item_discount_edit_form_title'];

$form_params['form_attribs']['method'] = 'post';
$form_params['form_attribs']['action'] = '/admin/shop/shop.php';
$form_params['form_attribs']['name'] = 'EditAddDiscount';

$shop_shops_id = to_int($_REQUEST['shop_shops_id']);
$shop = & singleton('shop');
$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

$admin_forms_fields = new admin_forms_fields();

$DataBase = & singleton('DataBase');

$row = $shop->GetShop($shop_shops_id);

$path_array = $shop->GetShopPathArray($shop_groups_parent_id, false);

// Преобразуем идентификаторы групп в ссылки на группы.
$new_path_array = array();
$new_path_array[0]['name'] = $GLOBALS['MSG_shops']['header_admin__list_forms'];
$new_path_array[0]['link'] = $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');
$new_path_array[0]['onclick'] = $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');

$new_path_array[1]['name'] = $row['shop_shops_name'];
$new_path_array[1]['link'] = $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');
$new_path_array[1]['onclick'] = $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');

if ($path_array)
{
	foreach ($path_array as $key => $value)
	{
		$new_path_array[] = array (
		'link' => $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
		'onclick' => $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
		'name' => $value);
	}
}

// Если пришли из формы списка модификаций товара
if (isset($_REQUEST['shop_items_catalog_modification_id']) && isset($_REQUEST['item_id']))
{
	// Получаем имя товара
	$shop_items_catalog_item_id = to_int($_REQUEST['item_id']);

	$row = $shop->GetItem($shop_items_catalog_item_id);

	$new_path_array[] = array("name" => sprintf($GLOBALS['MSG_shops']['item_modification_title'], $row['shop_items_catalog_name']),
	"link" => $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_modification_id=$shop_items_catalog_item_id", 81, 'load_data'),
	"onclick" => $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_modification_id=$shop_items_catalog_item_id", 81, 'load_data'));
}

if (isset($_REQUEST['shop_items_catalog_item_id']) && to_int($_REQUEST['shop_items_catalog_item_id']) != 0)
{
	$shop_items_catalog_item_id = to_int($_REQUEST['shop_items_catalog_item_id']);

	$res = $shop->GetItem($shop_items_catalog_item_id);

	if (isset($_REQUEST['item_id']))
	{

		$item_id = to_int($_REQUEST['item_id']);

		$new_path_array[] = array("name" => sprintf($GLOBALS['MSG_shops']['show_item_discount_title'], $res['shop_items_catalog_name']),
		"link" => $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id=$shop_items_catalog_item_id&item_id=$item_id&shop_items_catalog_modification_id=$item_id", 72, 'load_data'),
		"onclick" => $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id=$shop_items_catalog_item_id&item_id=$item_id&shop_items_catalog_modification_id=$item_id", 72, 'load_data')
		);
	}
	else
	{
		$new_path_array[] = array("name" => sprintf($GLOBALS['MSG_shops']['show_item_discount_title'], $res['shop_items_catalog_name']),
		"link" => $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id=$shop_items_catalog_item_id", 72, 'load_data'),
		"onclick" => $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id=$shop_items_catalog_item_id", 72, 'load_data')
		);
	}
}
else
{
	$new_path_array[] = array("name" => $GLOBALS['MSG_shops']['discount_add_form_link'],
	"link" => $admin_forms_fields->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data'),
	"onclick" => $admin_forms_fields->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data')
	);
}

$form_params['path_array'] = $new_path_array;

$admin_forms_fields->admin_forms_fields($form_params);

// Параметры.
$tab_id = $admin_forms_fields->AddTab($GLOBALS['MSG_shops']['tab']);


if (!isset($_REQUEST['shop_items_catalog_item_id']))
{
	// Редактировние производителя
	if ($edit_discount)
	{
		$type = 1;

		$result = $shop->GetDiscount($edit_discount);

		$shop_shop_id = to_int($result['shop_shops_id']);

		$shop_discount_name = to_str($result['shop_discount_name']);

		$shop_discount_from =  $datetime->datetime_format($result['shop_discount_from']);

		$shop_discount_to =  $datetime->datetime_format($result['shop_discount_to']);

		$shop_discount_is_active = to_int($result['shop_discount_is_active']);

		$shop_discount_percent = to_int($result['shop_discount_percent']);

		$users_id = to_int($result['users_id']);
	}
	// Добавление производителя
	else
	{
		$shop_discount_name = '';

		$shop_discount_from = date("d.m.Y H:i:s");

		$shop_discount_to = date("d.m.Y H:i:s");

		$shop_discount_is_active = 0;

		$shop_discount_percent = '';
	}

	// Название скидки
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'discount_name';
	$params['caption'] = $GLOBALS['MSG_shops']['order_discount_form_name'];
	$params['type'] = 0; // Поле ввода.
	$params['value'] = $shop_discount_name;
	$params['attributes']['class'] = 'large';
	$params['format']['minlen']['value'] = 1;
	$params['format']['maxlen']['value'] = 255;
	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);

	// Дата начала действия скидки
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['html_id'] = 'discount_from';
	$params['name'] = 'discount_from';
	$params['caption'] = $GLOBALS['MSG_shops']['discount_add_form_from'];
	$params['type'] = 11; // Дата-время
	$params['value'] = $shop_discount_from;

	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);

	// Дата окончания действия скидки
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['html_id'] = 'discount_to';
	$params['name'] = 'discount_to';
	$params['caption'] = $GLOBALS['MSG_shops']['discount_add_form_to'];
	$params['type'] = 11; // Поле ввода.
	$params['value'] = $shop_discount_to;

	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);


	// Активность
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'discount_is_active';
	$params['caption'] = $GLOBALS['MSG_shops']['discount_is_active'];
	$params['type'] = 1; // Флажок
	$params['value'] = $shop_discount_is_active;

	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);

	// Процент скидки
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'discount_percent';
	$params['caption'] = $GLOBALS['MSG_shops']['discount_add_form_percent'];
	$params['type'] = 0; // Поле ввода.
	$params['value'] = $shop_discount_percent;
	$params['format']['lib']['value'] = 'decimal';
	$params['format']['lib']['message'] = $GLOBALS['MSG_shops']['show_invalid_characters_decimal'];
	$params['format']['minlen']['value'] = 1;
	$params['format']['maxlen']['value'] = 11;
	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);
}
else
{
	$shop_items_catalog_item_id = to_int($_REQUEST['shop_items_catalog_item_id']);
	
	// При редактировании скидки для товара оставляем в списке скидок редактируемую (см. ниже)
	if ($edit_discount)
	{
		// Получаем информацию о скидке для товара
		$discount_res = $shop->GetItemDiscount($edit_discount);
		
		if ($discount_res)
		{			
			$where = " AND `shop_discount_id` != '".$discount_res['shop_discount_id']."'";
		}		
	}
	else
	{
		$where = '';
	}

	// Получаем список всех скидок для данного товара
	$query = "SELECT * FROM `shop_item_discount_table` WHERE `shop_items_catalog_item_id` = '$shop_items_catalog_item_id' $where";

	$array_of_discounts = array();

	$data_source = $DataBase->query($query);

	while ($row = mysql_fetch_assoc($data_source))
	{
		$array_of_discounts[] = $row['shop_discount_id'];
	}
	
	// Получаем список всех скидок данного магазина
	$arr = array();
	
	$res = $shop->GetAllDiscounts($shop_shops_id);

	while ($row = mysql_fetch_assoc($res))
	{
		// Мы должны исключить из списка скидок те скидки, которые уже определены за данным товаром, во избежание дублирования скидок
		if (in_array($row['shop_discount_id'], $array_of_discounts))
		{
			continue;
		}
			
		$arr[$row['shop_discount_id']] = $row['shop_discount_name'];
	}
	
	if (!count($arr))
	{
		$arr[0] = ' ... ';
	}
	
	// Список скидок доступных для определенного товара
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'discount_id_for_item';
	$params['caption'] = $GLOBALS['MSG_shops']['item_discount_name'];
	$params['type'] = 2; // Выпадающий список
	$params['value'] = to_int($discount_res['shop_discount_id']);
	$params['items'] = $arr;

	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);
	
	// Флажок, указывающий применять ли скидку и к модификациям данного товара
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'apply_discount_to_modification';
	$params['caption'] = $GLOBALS['MSG_shops']['shop_apply_modification_discount'];
	$params['type'] = 1; // Выпадающий список
	$params['value'] = 1;

	$admin_forms_fields->AddField($params);

	// Разделитель.
	$admin_forms_fields->AddSeparator($tab_id);
}

// передеам скрытое поле с идентификатором адреса если он есть
if ($edit_discount)
{
	$params = array();
	$params['tab_id'] = $tab_id;
	$params['name'] = 'edit_discount';
	$params['caption'] = '';
	$params['type'] = 4; // hidden.
	$params['value'] = $edit_discount;
	$admin_forms_fields->AddField($params);
}

$params = array();
$params['tab_id'] = $tab_id;
$params['name'] = 'action';
$params['caption'] = '';
$params['type'] = 4; // hidden.
$params['value'] = 'show_discount';
$admin_forms_fields->AddField($params);


$params = array();
$params['tab_id'] = $tab_id;
$params['name'] = 'shop_shops_id';
$params['caption'] = '';
$params['type'] = 4; // hidden.
$params['value'] = $shop_shops_id;
$admin_forms_fields->AddField($params);

$params = array();
$params['tab_id'] = $tab_id;
$params['name'] = 'shop_groups_parent_id';
$params['caption'] = '';
$params['type'] = 4; // hidden.
$params['value'] = $shop_groups_parent_id;
$admin_forms_fields->AddField($params);

if (!isset($_REQUEST['shop_items_catalog_item_id']))
{
	// Кнопка "Сохранить".
	$param = array();
	$param['name'] = 'save_discount';
	$param['caption'] = $GLOBALS['MSG_shops']['save'];
	$param['attributes']['onclick'] = "return SendForm('{$admin_forms_fields->GetWindowId()}', '{$admin_forms_fields->AAction}', '{$admin_forms_fields->AAdditionalParams}', this, ".to_int($_REQUEST['admin_forms_id']).", 'load_data', " . to_int($admin_forms_fields->form_params['current_page']) . ", " . to_int($admin_forms_fields->form_params['on_page']) . " )";
	$param['attributes']['type'] = 'button';
	$admin_forms_fields->AddButton($param);

	// Кнопка "Применить".
	$params = array();
	$params['name'] = 'add_discount';
	$params['caption'] = $GLOBALS['MSG_shops']['apply'];
	$params['image'] = '/admin/images/add.gif';
	$params['attributes']['onclick'] = "return SendForm('{$admin_forms_fields->GetWindowId()}', '{$admin_forms_fields->AAction}', '{$admin_forms_fields->AAdditionalParams}', this, ".to_int($_REQUEST['admin_forms_id']).")";
	$params['attributes']['type'] = 'submit';
	$admin_forms_fields->AddButton($params);
}
else
{
	// Кнопка "Применить".
	$params = array();
	$params['name'] = 'add_discount_for_item';
	$params['caption'] = to_int($discount_res['shop_discount_id']) == 0 ? $GLOBALS['MSG_shops']['shop_add_form_button_value1'] : $GLOBALS['MSG_shops']['apply'];
	$params['image'] = '/admin/images/add.gif';
	$params['attributes']['onclick'] = "return SendForm('{$admin_forms_fields->GetWindowId()}', '{$admin_forms_fields->AAction}', '{$admin_forms_fields->AAdditionalParams}', this, ".to_int($_REQUEST['admin_forms_id']).")";
	$params['attributes']['type'] = 'submit';
	$admin_forms_fields->AddButton($params);
}

// Отображение формы.
$admin_forms_fields->ShowForm();
?>