<?php ob_start();?>
<style>
#openFile{
	display:none;
}
</style>
<?php
$title = 'Редактирование товара';
include_once($_SERVER["DOCUMENT_ROOT"].'/php/style/head.php');
admin(3);
$_GET['id'] = abs(intval($_GET['id']));
$query = $db->query("SELECT * FROM `products` WHERE `id`='".$_GET['id']."'");
if($query->num_rows==0){
	header('location:/admin');
}
$product = $query->fetch_assoc();
$cat = $db->query("SELECT * FROM `categories` WHERE `id`='".$product['id_categorie']."'")->fetch_assoc();
if(isset($_POST['send'])){
	$_POST['name'] = input($_POST['name']);
	$_POST['description'] = input($_POST['description']);
	$_POST['in_stock'] = abs(intval($_POST['in_stock']));
	$_POST['price'] = abs(intval($_POST['price']));
	$_POST['categorie'] = abs(intval($_POST['categorie']));
	if(empty($_POST['name'])){
		showAlertDanger('Введите имя');
	}elseif(empty($_POST['description'])){
		showAlertDanger('Введите описание');
	}elseif($_POST['in_stock'] < 0){
		showAlertDanger('Кол-во в наличии не должно быть меньше нуля');
	}elseif($_POST['price'] < 0){
		showAlertDanger('Цена должна быть не менее нуля');
	}elseif($db->query("SELECT `id` FROM `categories` WHERE `id`='".$_POST['categorie']."'")->num_rows==0){
		showAlertDanger('Выбранной категории не существует');
	}else{
		if(file_exists($_FILES['file']['tmp_name'])){
			$types = explode(',', 'png,jpg,jpeg,bmp,ico,JPG');
			$upfiletype = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".") + 1);
			if($_FILES['file']['size'] > (1048576 * 5)){
				?>
				<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Размер выгружаемого файла, не должен превышать 5 мб!</div>
				<?
			}elseif(!in_array($upfiletype, $types)){
				?>
				<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Файл такого типа выгружать запрещено!</div>
				<?
			}else{
				$name = md5($_GET['id'] + time()).'.'.$upfiletype;
				copy($_FILES['file']['tmp_name'], $_SERVER["DOCUMENT_ROOT"].'/files/images/products/'.$name);
				$db->query("INSERT INTO `products_images` SET `id_product`=".$_GET['id'].", `image`='".$name."'");
			}
		}
		$db->query("UPDATE `products` SET `name`='".$_POST['name']."', `id_categorie`='".$_POST['categorie']."', `description`='".$_POST['description']."', `in_stock`='".$_POST['in_stock']."', `price`='".$_POST['price']."' WHERE `id`='".$_GET['id']."'");
		$product = $db->query("SELECT * FROM `products` WHERE `id`='".$_GET['id']."'")->fetch_assoc();
	}
}
?>
<div class="container theme-showcase" role="main">
	<div class="jumbotron" style="background-color: white;">
  		<h1>Редактирование товара "<b><?=output($product['name'])?></b>"</h1>
  			<div class="page-header">
			<ol class="breadcrumb">
				<li><a href="/categories">Разделы</a></li>
				<?
		  			if($cat['podkat'] != 0){
		  				$tcat = $cat['podkat'];
		  				while($tcat != 0){
		  					$kcat = $db->query("SELECT * FROM `categories` WHERE `id`='".$tcat."'")->fetch_assoc();
		  					?>
		  					<li><a href="/categories/<?=$kcat['id']?>"><?=output($kcat['name'])?></a></li>
		  					<?php
		  					$tcat = $kcat['podkat'];
		  				}
		  			}
		  			?>
		  		<li><a href="/categories/<?=$cat['id']?>"><?=output($cat['name'])?></a></li>
				<li class><a href="/product/<?=$product['id']?>"><?=output($product['name'])?></a></li>
				<li class="active">Редактирование товара</li>
			</ol>
		</div>
		<form action="" method="POST" enctype="multipart/form-data">
				<div class="form-row">
					<div class="form-group">
						<label for="name">Название</label>
						<input type="text" class="form-control" placeholder="Введите название товара" rows="5" name="name" id="name" value="<?=output($product['name'])?>">
					</div>
				</div>
				<div class="form-row">
					<div class="form-group">
						<label for="description">Описание</label>
						<textarea class="form-control" placeholder="Введите описание товара" rows="5" name="description" id="description"><?=output($product['description'])?></textarea>
					</div>
				</div>
				<div class="form-row">
						<div class="form-group">
					    	<label for="inputCategorie">Категория</label>
					    	<select id="inputCategorie" class="form-control" name="categorie">
					    		<option>Выберите...</option>
					    		<?
								$query = $db->query("SELECT * FROM `categories`");
								while($categorie = $query->fetch_assoc()){
									?>
									<option value="<?=$categorie['id']?>" <?if($product['id_categorie']==$categorie['id']){?>selected<?}?>><?=output($categorie['name'])?></option>
									<?
								}
								?>
					    	</select>
					    </div>
				</div>
				<div class="form-row">
					<div class="form-group">
						<label for="inputInStock">В наличии</label>
						<input type="number" class="form-control" placeholder="Введите кол-во в наличии" rows="5" name="in_stock" id="inputInStock" value="<?=$product['in_stock']?>">
					</div>
				</div>
				<div class="form-row">
					<div class="form-group">
						<label for="inputPrice">Цена</label>
						<input type="number" class="form-control" placeholder="Введите кол-во в наличии" rows="5" name="price" id="inputPrice" value="<?=$product['price']?>">
					</div>
				</div>
					<input type="file" name="file" id="openFile" accept="image/*,image/jpeg">
					<label for="openFile"><small class="btn btn-default btn-xs"><i class="glyphicon glyphicon-camera"></i> Прикрепить изображение</small></label>    
					<button type="submit" class="btn btn-info pull-right" name="send">Редактировать</button>
				</div>
			</form>

			 	<?
		  	$imgq = $db->query("SELECT * FROM `products_images` WHERE `id_product`=".$product['id']."");
		  	if($imgq->num_rows != 0){
		  		?>
		  		<h3></h3>
		  		<div class="panel panel-default">
  					<div class="panel-heading">
    					<h3 class="panel-title">Прикреплённые изображения:</h3>
  					</div>
  					<div class="panel-body">
				  		<?
				  		while($img = $imgq->fetch_assoc()){
				  			?>
							<div class="col-xs-2 col-md-2">
		    					<div class="thumbnail">
		      						<a href="/files/images/products/<?=output($img['image'])?>">
										<img src="/files/images/products/<?=output($img['image'])?>">
									</a>
		      						<div class="caption">
		        						<p><a href="/admin/products/images/delete/<?=$img['id']?>" class="btn btn-danger" role="button">Удалить</a></p>
		      						</div>
		    					</div>
		  					</div>
				  			<?
				  		}?>
				  	</div>
				</div>
			<?}?>
    </div>
</div>
<?
include_once($_SERVER["DOCUMENT_ROOT"].'/php/style/foot.php');
?>