<?php
/* ============================ */
/*         SalesMan CRM         */
/* ============================ */
/* (C) 2016 Vladislav Andreev   */
/*       SalesMan Project       */
/*        www.isaler.ru         */
/*        ver. 2019.x           */
/* ============================ */

error_reporting(E_ERROR);
header("Pragma: no-cache");

$rootpath = dirname(__DIR__, 2);

include $rootpath."/inc/config.php";
include $rootpath."/inc/dbconnector.php";
include $rootpath."/inc/auth.php";
include $rootpath."/inc/func.php";
include $rootpath."/inc/settings.php";
// Доступ только для администратора
if ($isadmin != 'on' && $tipuser != 'Администратор') {
	print 'Доступ запрещен';
	exit();
}


$thisfile = basename( __FILE__ );

$action    = $_REQUEST['action'];
$tid       = (int)$_REQUEST['tid'];
$title     = $_REQUEST['title'];
$isDefault = $_REQUEST['isDefault'];


if ($action == "delete.do") {

	//обрабатываем все записи
	$db -> query("UPDATE {$sqlname}dogovor SET ?u WHERE tip = '$tid' and identity = '$identity'", array('tip' => $_REQUEST['newid']));

	//удаляем тип
	$db -> query("delete from {$sqlname}dogtips where tid = '$tid' and identity = '$identity'");

	print "Сделано";


	unlink($rootpath."/cash/".$fpath."settings.all.json");

	exit();

}
if ($action == "edit.on") {

	//снимем умолчания
	if ($isDefault == 'yes') {
		$db -> query("UPDATE {$sqlname}dogtips SET isDefault = '' WHERE identity = '$identity'");
	}

	if ($tid < 1) {

		$db -> query("INSERT INTO {$sqlname}dogtips SET ?u", [
			'title'     => $title,
			'isDefault' => ($isDefault == 'yes') ? $isDefault : 'no',
			'identity'  => $identity
		]);

	}
	else {

		$db -> query("UPDATE {$sqlname}dogtips SET ?u WHERE tid = '$tid' and identity = '$identity'", [
			'title'     => $title,
			'isDefault' => ($isDefault == 'yes') ? $isDefault : 'no',
		]);

	}

	print "Сделано";

	unlink($rootpath."/cash/".$fpath."settings.all.json");

	exit();

}

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
	print '<div class="warning text-center"><br>Доступ запрещен.<br>Обратитесь к администратору.<br><br></div>';
	exit();
}

if ($action == "edit") {

	if ($tid > 0) {
		$result    = $db -> getRow("SELECT * FROM {$sqlname}dogtips where tid = '".$tid."' and identity = '$identity'");
		$title     = $result["title"];
		$isDefault = $result["isDefault"];
	}
	?>
	<div class="zagolovok"><b>Изменить / Добавить</b></div>
	<FORM method="post" action="/content/admin/<?php echo $thisfile; ?>" name="form" id="form">
		<INPUT name="action" id="action" type="hidden" value="edit.on">
		<INPUT name="tid" id="tid" type="hidden" value="<?= $tid ?>">

		<div class="row">

			<div class="column12 grid-3 fs-12 pt10 right-text">Название:</div>
			<div class="column12 grid-9">
				<INPUT name="title" type="text" class="wp97" id="title" value="<?= $title ?>">
			</div>

			<div class="column12 grid-3 fs-12 pt10 right-text">&nbsp;</div>
			<div class="column12 grid-9">
				<label><input id="isDefault" name="isDefault" type="checkbox" value="yes" <?php if ($isDefault == 'yes') print 'checked' ?> />&nbsp;Использовать по-умолчанию&nbsp;</label>
			</div>

		</div>

		<hr>

		<div class="button--pane text-right">

			<A href="javascript:void(0)" onclick="$('#form').trigger('submit')" class="button">Сохранить</A>&nbsp;
			<A href="javascript:void(0)" onclick="DClose();" class="button">Отмена</A>

		</div>
	</FORM>
	<script>
		$('#form').ajaxForm({
			beforeSubmit: function () {

				var $out = $('#message');
				var em = checkRequired();

				if (em === false) return false;

				$('#dialog').css('display', 'none');
				$('#dialog_container').css('display', 'none');
				$out.css('display', 'block').append('<div id=loader><img src=/assets/images/loader.gif> Загрузка данных. Пожалуйста подождите...</div>');
				return true;

			},
			success: function (data) {

				//$('#contentdiv').load('content/admin/<?php echo $thisfile; ?>');
				razdel(hash);

				$('#message').fadeTo(1, 1).css('display', 'block').html(data);
				setTimeout(function () {
					$('#message').fadeTo(1000, 0);
				}, 20000);

				DClose();
			}
		});
	</script>
	<?php
	exit();

}
if ($action == "delete") {

	$tip = $db -> getOne("SELECT title FROM {$sqlname}dogtips WHERE tid = '".$tid."' and identity = '$identity'");

	?>
	<div class="zagolovok">Удалить "<?= $tip ?>"</div>
	<FORM action="/content/admin/<?php echo $thisfile; ?>" method="POST" name="form" id="form">
		<input type="hidden" id="tid" name="tid" value="<?= $tid ?>">
		<input name="action" type="hidden" value="delete.do" id="action"/>

		<div class="infodiv">В случае удаления, данный тип останется в существующих записях и они не будут участвовать в отчетах. Вы можете перевести их на новый тип.</div>

		<hr>

		<div class="row">

			<div class="column12 grid-3 fs-12 pt10 right-text">Новый тип:</div>
			<div class="column12 grid-9">
				<select name="newid" id="newid" class="required wp100">
					<option value="">--выбрать--</option>
					<?php
					$result_a = $db -> getAll("SELECT * FROM {$sqlname}dogtips WHERE tid != '$tid' and identity = '$identity' ORDER by title");
					foreach ($result_a as $data) {

						print '<option value="'.$data['tid'].'">'.$data['title'].'</option>';

					}
					?>
				</select>
			</div>

		</div>

		<hr>

		<div class="button--pane text-right">

			<A href="javascript:void(0)" onclick="$('#form').trigger('submit')" class="button">Сохранить</A>&nbsp;
			<A href="javascript:void(0)" onclick="DClose()" class="button">Отмена</A>

		</div>

	</FORM>
	<script>
		$('#dialog').css('width', '600px');

		$('#form').ajaxForm({
			beforeSubmit: function () {

				var $out = $('#message');
				var em = checkRequired();

				if (em === false) return false;

				$('#dialog').css('display', 'none');
				$('#dialog_container').css('display', 'none');
				$out.css('display', 'block').append('<div id=loader><img src=/assets/images/loader.gif> Загрузка данных. Пожалуйста подождите...</div>');
				return true;

			},
			success: function (data) {

				//$('#contentdiv').load('content/admin/<?php echo $thisfile; ?>');
				razdel(hash);

				$('#message').fadeTo(1, 1).css('display', 'block').html(data);
				setTimeout(function () {
					$('#message').fadeTo(1000, 0);
				}, 20000);

				DClose();
			}
		});

	</script>
	<?php
	exit();
}

if ($action == '') {
	?>
	<h2>&nbsp;Раздел: "<?php echo $fieldsNames['dogovor']['tip'];?>"</h2>
	<h3 class="gray-dark fs-09 pl10">Стандарт: Типы сделок</h3>

	<form id="list">

		<TABLE id="rowtablee">
			<thead class="hidden-iphone sticked--top">
			<TR class="th40">
				<Th class="text-center">Название</Th>
				<Th class="w120 text-center">Действия</Th>
			</TR>
			</thead>
			<?php
			$result = $db -> getAll("SELECT * FROM {$sqlname}dogtips WHERE identity = '$identity' ORDER by title");
			foreach ($result as $datar) {

				$df = ($datar['isDefault'] == 'yes') ? ' [ <b class="red">По-умолчанию</b> ]' : '';

				$srv = '';

				if (stripos(texttosmall($datar['title']), 'месячный') !== false) $srv = ' [ <b class="blue">Сервисная</b> ]';
				if (stripos(texttosmall($datar['title']), 'сервис') !== false) $srv = ' [ <b class="blue">Сервисная</b> ]';
				if (stripos(texttosmall($datar['title']), 'абонент') !== false) $srv = ' [ <b class="blue">Сервисная</b> ]';

				?>
				<TR class="ha th40">
					<TD>
						<span class="gray2">ID <?= $datar['tid'] ?>:</span> <B class="fs-12"><?= $datar['title'] ?></B><?= $df ?><?= $srv ?>
					</TD>
					<TD class="text-center">
						<A href="javascript:void(0)" onclick="doLoad('/content/admin/<?php echo $thisfile; ?>?action=edit&tid=<?= $datar['tid'] ?>');" class="button dotted bluebtn"><i class="icon-pencil"></i></A>
						<A href="javascript:void(0)" onclick="doLoad('/content/admin/<?php echo $thisfile; ?>?tid=<?= $datar['tid'] ?>&action=delete')" class="button dotted redbtn"><i class="icon-cancel"></i></A>
					</TD>
				</TR>
			<?php } ?>
		</TABLE>

	</form>

	<div class="button--group1 box--child" style="position: fixed; bottom: 40px; left: 380px; z-index: 100;">

		<a href="javascript:void(0)" onclick="doLoad('/content/admin/<?php echo $thisfile; ?>?action=edit');" class="button bluebtn box-shadow" title="Добавить"><i class="icon-plus-circled"></i>Добавить</a>

	</div>

	<div class="pagerefresh refresh--icon admn red" onclick="doLoad('/content/admin/<?php echo $thisfile; ?>?action=edit');" title="Добавить"><i class="icon-plus-circled"></i></div>
	<div class="pagerefresh refresh--icon admn orange" onclick="openlink('https://salesman.pro/docs/34')" title="Документация"><i class="icon-help"></i></div>

	<div class="space-100"></div>

<?php } ?>