<?
if ($level == 0){
	$system['title'] = 'Покупка рекламы';
	require SYS . 'header.php';
	echo '<div class="home_menu">';
	echo '<b>Требуется авторизация</b></div>';

	die('');
  //header('Location: /index.php');
  //exit;
}


if (!$system['wmid'] || !$system['wmpurse']) {
  //die('Этот раздел временно не работает');
}

$ads['color'] = null;
$ads['days'] = null;
$ads['name'] = null;
$ads['url'] = null;
$ads['fonts'] = 0;
$ads['wmr'] = 0;
$ads['id_goods'] = 0;
$ads['time_last'] = 0;


if (isset($_GET['id_goods'])) {
  $id_goods = (int) $_GET['id_goods'];
  
  if ($sql -> selectCount("SELECT COUNT(*) FROM `shop_goods` WHERE `id` = '$id_goods' AND `active` = '1' AND `id_user` = $user[id]") > 0) {
    $ads['id_goods'] = $id_goods;
    $goods = $sql -> fetch("SELECT * FROM `shop_goods` WHERE `id` = '$id_goods' AND `active` = '1' AND `id_user` = $user[id]");
    $ads['name'] = $goods['name'];
  }
}

$ads['end_wmr'] = ($ads['id_goods'] == 0 ? $system['ads_coins_sites'] : $system['ads_coins_goods']);
/*
if ($ads['id_goods'] == 0 && $sql -> selectCount("SELECT COUNT(*) FROM `ads` WHERE `pays` = '1' AND `time_last` > '" . time() . "' AND `type` = 'sites'") >= 10) {
  $err[] = 'Все площадки заняты, зайдите позже!';
}

if ($ads['id_goods'] != 0 && $sql -> selectCount("SELECT COUNT(*) FROM `ads` WHERE `pays` = '1' AND `time_last` > '" . time() . "' AND `type` = 'goods'") >= 10) {
  $err[] = 'Все площадки заняты, зайдите позже!';
}
*/
if (isset($_POST['name'])) {
  $ads['color'] = $_POST['color'];
  $ads['days'] = (int) $_POST['days'];
  $ads['fonts'] = (int) $_POST['fonts'];
  $ads['name'] = $_POST['name'];
  
  if ($ads['id_goods'] == 0) {
    $ads['url'] = $_POST['url'];
  }
  
	if ($ads['color'] && !preg_match("/^#?([A-z0-9]{6}|[A-z0-9]{3})$/", $ads['color'])) {
    $err[] = 'В цвете присутствуют запрещенные символы';
  }
 
   $ads['url'] = str_replace("https://","", $ads['url']);
   $ads['url'] = str_replace("http://","", $ads['url']);
  
  if ($ads['id_goods'] == 0 && strlen2($ads['url']) > 64) {
    $err[] = 'Ссылка слишком длинная';
  }
  
  if ($ads['days'] < 1) {
    $err[] = 'Минимум для заказа укажите 1 день';
  }
  
  if (strlen2($ads['name']) > 32) {
    $err[] = 'Название слишком длинное';
  } elseif (strlen2($ads['name']) < 8) {
    $err[] = 'Название слишком короткое';
  }
  
  if (!isset($err)) {
    $ok = true;
  }
  
  if (!isset($err) && isset($_POST['success'])) {
    $ads['wmr'] = ($ads['days'] * $ads['end_wmr']) + ($ads['color'] ? $system['ads_coins_color'] : 0) + ($ads['fonts'] == 1 ? $system['ads_coins_b'] : 0);
    
    $sql -> insert("INSERT INTO `ads` (`name`, `url`, `days`, `type`, `id_user`, `wmr`, `color`, `fonts`, `id_goods`)  VALUES ('" . $sql->esc($ads['name']) . "', '" . $sql->esc($ads['url']) . "', '$ads[days]', '".($ads['id_goods'] == 0 ? 'sites' : 'goods')."', '$user[id]', '" . $ads['wmr'] . "', '$ads[color]', '$ads[fonts]', '$ads[id_goods]')");
    $returnID = $sql->insert_id();
    
    header('Location: ?func=service.payment&id=' . $returnID);
    exit;
  }
}

$colors = array(
			"Красные" => array (
				"IndianRed"   => 0xCD5C5C, 
				"LightCoral"  => 0xF08080, 
				"Salmon"      => 0xFA8072, 
				"DarkSalmon"  => 0xE9967A, 
				"LightSalmon" => 0xFFA07A, 
				"Crimson"     => 0xDC143C, 
				"Red"         => 0xFF0000, 
				"FireBrick"   => 0xB22222, 
				"DarkRed"     => 0x8B0000, 
			), 
			
			"Розовые" => array (
				"Pink"            => 0xFFC0CB, 
				"LightPink"       => 0xFFB6C1, 
				"HotPink"         => 0xFF69B4, 
				"DeepPink"        => 0xFF1493, 
				"MediumVioletRed" => 0xC71585, 
				"PaleVioletRed"   => 0xDB7093, 
			), 
			
			"Оранжевые" => array (
				"Coral"      => 0xFF7F50, 
				"Tomato"     => 0xFF6347, 
				"OrangeRed"  => 0xFF4500, 
				"DarkOrange" => 0xFF8C00, 
				"Orange"     => 0xFFA500, 
			), 
			
			"Жёлтые" => array (
				"Gold"                 => 0xFFD700, 
				"Yellow"               => 0xFFFF00, 
				"LightYellow"          => 0xFFFFE0, 
				"LemonChiffon"         => 0xFFFACD, 
				"LightGoldenrodYellow" => 0xFAFAD2, 
				"PapayaWhip"           => 0xFFEFD5, 
				"Moccasin"             => 0xFFE4B5, 
				"PeachPuff"            => 0xFFDAB9, 
				"PaleGoldenrod"        => 0xEEE8AA, 
				"Khaki"                => 0xF0E68C, 
				"DarkKhaki"            => 0xBDB76B, 
			), 
			
			"Фиолетовые" => array (
				"Lavender"      => 0xE6E6FA, 
				"Thistle"       => 0xD8BFD8, 
				"Plum"          => 0xDDA0DD, 
				"Violet"        => 0xEE82EE, 
				"Orchid"        => 0xDA70D6, 
				"Fuchsia"       => 0xFF00FF, 
				"Magenta"       => 0xFF00FF, 
				"MediumOrchid"  => 0xBA55D3, 
				"MediumPurple"  => 0x9370DB, 
				"BlueViolet"    => 0x8A2BE2, 
				"DarkViolet"    => 0x9400D3, 
				"DarkOrchid"    => 0x9932CC, 
				"DarkMagenta"   => 0x8B008B, 
				"Purple"        => 0x800080, 
				"Indigo"        => 0x4B0082, 
				"SlateBlue"     => 0x6A5ACD, 
				"DarkSlateBlue" => 0x483D8B, 
			), 
			
			"Зелёные" => array (
				"GreenYellow"       => 0xADFF2F, 
				"Chartreuse"        => 0x7FFF00, 
				"LawnGreen"         => 0x7CFC00, 
				"Lime"              => 0x00FF00, 
				"LimeGreen"         => 0x32CD32, 
				"PaleGreen"         => 0x98FB98, 
				"LightGreen"        => 0x90EE90, 
				"MediumSpringGreen" => 0x00FA9A, 
				"SpringGreen"       => 0x00FF7F, 
				"MediumSeaGreen"    => 0x3CB371, 
				"SeaGreen"          => 0x2E8B57, 
				"ForestGreen"       => 0x228B22, 
				"Green"             => 0x008000, 
				"DarkGreen"         => 0x006400, 
				"YellowGreen"       => 0x9ACD32, 
				"OliveDrab"         => 0x6B8E23, 
				"Olive"             => 0x808000, 
				"DarkOliveGreen"    => 0x556B2F, 
				"MediumAquamarine"  => 0x66CDAA, 
				"DarkSeaGreen"      => 0x8FBC8F, 
				"LightSeaGreen"     => 0x20B2AA, 
				"DarkCyan"          => 0x008B8B, 
				"Teal"              => 0x008080, 
			), 
			
			"Синие" => array (
				"Aqua"            => 0x00FFFF, 
				"Cyan"            => 0x00FFFF, 
				"LightCyan"       => 0xE0FFFF, 
				"PaleTurquoise"   => 0xAFEEEE, 
				"Aquamarine"      => 0x7FFFD4, 
				"Turquoise"       => 0x40E0D0, 
				"MediumTurquoise" => 0x48D1CC, 
				"DarkTurquoise"   => 0x00CED1, 
				"CadetBlue"       => 0x5F9EA0, 
				"SteelBlue"       => 0x4682B4, 
				"LightSteelBlue"  => 0xB0C4DE, 
				"PowderBlue"      => 0xB0E0E6, 
				"LightBlue"       => 0xADD8E6, 
				"SkyBlue"         => 0x87CEEB, 
				"LightSkyBlue"    => 0x87CEFA, 
				"DeepSkyBlue"     => 0x00BFFF, 
				"DodgerBlue"      => 0x1E90FF, 
				"CornflowerBlue"  => 0x6495ED, 
				"MediumSlateBlue" => 0x7B68EE, 
				"RoyalBlue"       => 0x4169E1, 
				"Blue"            => 0x0000FF, 
				"MediumBlue"      => 0x0000CD, 
				"DarkBlue"        => 0x00008B, 
				"Navy"            => 0x000080, 
				"MidnightBlue"    => 0x191970, 
			), 
			
			"Коричневые" => array (
				"Cornsilk"       => 0xFFF8DC, 
				"BlanchedAlmond" => 0xFFEBCD, 
				"Bisque"         => 0xFFE4C4, 
				"NavajoWhite"    => 0xFFDEAD, 
				"Wheat"          => 0xF5DEB3, 
				"BurlyWood"      => 0xDEB887, 
				"Tan"            => 0xD2B48C, 
				"RosyBrown"      => 0xBC8F8F, 
				"SandyBrown"     => 0xF4A460, 
				"Goldenrod"      => 0xDAA520, 
				"DarkGoldenrod"  => 0xB8860B, 
				"Peru"           => 0xCD853F, 
				"Chocolate"      => 0xD2691E, 
				"SaddleBrown"    => 0x8B4513, 
				"Sienna"         => 0xA0522D, 
				"Brown"          => 0xA52A2A, 
				"Maroon"         => 0x800000, 
			), 
			
			"Белые" => array (
				"White"         => 0xFFFFFF, 
				"Snow"          => 0xFFFAFA, 
				"Honeydew"      => 0xF0FFF0, 
				"MintCream"     => 0xF5FFFA, 
				"Azure"         => 0xF0FFFF, 
				"AliceBlue"     => 0xF0F8FF, 
				"GhostWhite"    => 0xF8F8FF, 
				"WhiteSmoke"    => 0xF5F5F5, 
				"Seashell"      => 0xFFF5EE, 
				"Beige"         => 0xF5F5DC, 
				"OldLace"       => 0xFDF5E6, 
				"FloralWhite"   => 0xFFFAF0, 
				"Ivory"         => 0xFFFFF0, 
				"AntiqueWhite"  => 0xFAEBD7, 
				"Linen"         => 0xFAF0E6, 
				"LavenderBlush" => 0xFFF0F5, 
				"MistyRose"     => 0xFFE4E1, 
			), 
			
			"Серые" => array (
				"Gainsboro"      => 0xDCDCDC, 
				"LightGray"      => 0xD3D3D3, 
				"Silver"         => 0xC0C0C0, 
				"DarkGray"       => 0xA9A9A9, 
				"Gray"           => 0x808080, 
				"DimGray"        => 0x696969, 
				"LightSlateGray" => 0x778899, 
				"SlateGray"      => 0x708090, 
				"DarkSlateGray"  => 0x2F4F4F, 
				"Black"          => 0x000000, 
			)
		); 
    
if (isset($_GET['act']) && isset($_GET['color']) && $_GET['act'] == 'color' && preg_match("/^([A-z0-9]{3,20})$/", $_GET['color'])){
  $_SESSION['color'] = text($_GET['color']);	
	header('Location: ?func=' . $func . '&id_goods=' . $ads['id_goods']);
	exit;
}

if (isset($_SESSION['color']) && !isset($_POST['color'])) {
	$ads['color'] = '#' . text($_SESSION['color']);
}

$system['title'] = 'Покупка рекламы для ' . ($ads['id_goods'] == 0 ? 'сайта' : 'товара');
require SYS . 'header.php';


if (isset($_GET['act']) && $_GET['act'] == 'color'){
	foreach ($colors as $group => $colors) {
		echo '<div class="title">' . $group . '</div>'; 
		echo '<table>'; 
		foreach ($colors as $color_name => $color_value) {
			$save_vars[] = $color_value; 
			echo '<tr>'; 
			echo '<td style="width: 16px; height: 16px; border: 1px solid #000; background-color: #'.sprintf("%06X", $color_value).'"></td>'; 
			echo '<td><a href="?func=' . $func . '&amp;id_goods=' . $ads['id_goods'] . '&amp;act=' . text($_GET['act']) . '&amp;color=' . sprintf("%06X", $color_value) . '">'.$color_name.'</a> #' . sprintf("%06X", $color_value) . '</td>'; 
			echo '</tr>'; 
		}
		echo '</table>'; 
	}
} else {
?>
<div class="alert" style="margin: 2px; margin-bottom: 6px;">
Стоимость рекламы (1 сутки): <b><?= $ads['end_wmr']?> wmr</b><br />
Выделить жирным шрифтом: <b><?= $system['ads_coins_b']?> wmr</b><br />
Цвет ссылки: <b><?= $system['ads_coins_color']?> wmr</b><br />
<span class="on">У вас на счету: <b><?= $user['wmr']?> wmr</b></span><br />
<? if ($ads['id_goods'] == 0) { ?><br />
Это покупка рекламы для сайтов а не товаров.<br />
Чтобы заказать рекламу для товара - зайдите на страницу своего товара (который хотите прорекламировать) и нажмите Рекламировать товар.<br /><br />
* <b>Реклама сайтов проходит модерацию</b>
<? } ?>

</div>

<div class="nav1">
<form class="form-horizontal" action="?func=<?= $func?>&amp;id_goods=<?= $ads['id_goods']?>" method="POST" style="margin: 2px;">
  
  <? if (isset($ok)) { ?>
  
    <input type="hidden" name="color" value="<?= text($ads['color'])?>" />
    <input type="hidden" name="name" value="<?= text($ads['name'])?>" />
    <input type="hidden" name="url" value="<?= text($ads['url'])?>" />
    <input type="hidden" name="fonts" value="<?= $ads['fonts']?>" />
    <input type="hidden" id="days" name="days" value="<?= $ads['days']?>" />
    
    <b>Ваш заказ:</b><br />
    Название: <?= text($ads['name'])?><br />
    <? if ($ads['id_goods'] == 0) { ?>
    URL: <?= text($ads['url'])?><br />
    <? } else { ?>
    ID товара: <?= $ads['id_goods']?><br />
    <? } ?>
    Дней: <?= text($ads['days'])?><br />
    <span class="on">Стоимость: <?= ($ads['days'] * $ads['end_wmr'])?> wmr</span><br /><br />
    <b>Дополнительные услуги:</b><br />
    Цвет: <?= ($ads['color'] ? '<span style="color: ' . text($ads['color']) . '">&radic; ' . text($ads['color']) . '</span>' : 'Нет')?><br />
    Жирность: <?= ($ads['fonts'] == 1 ? '<span style="font-weight: bold;">&radic; да</span>' : 'Нет')?><br />
    
    <span class="on">Итого к оплате: <b>
    <?= ($ads['days'] * $ads['end_wmr'] + ($ads['color'] ? $system['ads_coins_color'] : 0) + ($ads['fonts'] == 1 ? $system['ads_coins_b'] : 0))?> wmr
    </b></span><br /><br />
    
    <button type="submit" name="success" class="btn">Перейти к оплате</button>
    
  <? } else { ?>
  <div class="control-group">
    <label class="control-label" for="color">Цвет (например #FF0000)</label>
    <div class="controls">
  		<input type="text" id="color" name="color" value="<?= text($ads['color'])?>" /> [<a href="?func=<?= $func?>&amp;id_goods=<?= $ads['id_goods']?>&amp;act=color">выбрать цвет</a>]
    </div>
  </div>
  
  <div class="control-group">
    <label class="control-label" for="name">Название (8-32 символов)</label>
    <div class="controls">
  		<input type="text" id="name" name="name" value="<?= text($ads['name'])?>" />
    </div>
  </div>
  
  <? if ($ads['id_goods'] == 0) { ?>
  <div class="control-group">
    <label class="control-label" for="url">Адрес </label>
    <div class="controls">
  		<input type="text" id="url" name="url" value="<?= text($ads['url'])?>" />
    </div>
  </div>
  <? } ?>
  
  <div class="control-group">
    <label class="control-label" for="fonts">Жирность</label>
    <div class="controls">
      <label><input type="radio" name="fonts" value="1" <?= ($ads['fonts'] == 1 ? 'checked' : '')?> /> да</label>
      <label><input type="radio" name="fonts" value="0" <?= ($ads['fonts'] == 0 ? 'checked' : '')?> /> нет</label>
    </div>
  </div>
  
  <div class="control-group">
    <label class="control-label" for="days">Количество дней</label>
    <div class="controls">
  		<input type="text" id="days" name="days" value="<?= $ads['days']?>" />
    </div>
  </div>
  
  <div class="control-group">
    <div class="controls">
      <button type="submit" class="btn">Далее</button>
    </div>
  </div>
  
  <? } ?>
</form>
</div>
<?
}
?>
<div class="foot">
&laquo; <a href="?func=service">Дополнительные услуги</a>
</div>