<?=ob_start()?>
<style>
.comments ul ul {
 margin-left: 60px;
}
.comments .comment img {
 margin-right: 20px;
}
.comments .comment {
 padding: 6px;
}
.comments .comment:hover {
 background: #eee;
}
#openFile{
	display:none;
}
</style>
<?php
$title = 'Отзывы к товару';
include_once($_SERVER["DOCUMENT_ROOT"].'/php/style/head.php');
$_GET['id'] = abs(intval($_GET['id']));
$query = $db->query("SELECT * FROM `products` WHERE `id`='".$_GET['id']."'");
if($query->num_rows == 0){
	header('location:/');
	// Товара не существует
}
$product = $query->fetch_assoc();
$cat = $db->query("SELECT * FROM `categories` WHERE `id`='".$product['id_categorie']."'")->fetch_assoc();

?>
<div class="container theme-showcase" role="main">
<div class="jumbotron">
  		<h1><?=output($product['name'])?></h1>
  		<div class="row">
				<?
				$query = $db->query("SELECT * FROM `products_images` WHERE `id_product`=".$_GET['id']."");
				while($img = $query->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>
		  					</div>					<?
				}?>
		</div>
  		<p>
  			<h3>Стоимость <?=$product['price']?> руб.</h3>
			<?if(isUser()){?>
				<a class="btn btn-primary btn-lg" href="/cart/add/<?=$product['id']?>" role="button">Добавить в корзину <span class="badge"><?=$product['in_stock']?> шт. в наличии</span></a>
			<?}?>
			<?if($user['admin'] >= 2){
				?>
				<a class="btn btn-warning btn-lg" href="/admin/products/edit/<?=$_GET['id']?>" role="button">Редактировать товар</a>
				<a class="btn btn-danger btn-lg" href="/admin/products/delete/<?=$_GET['id']?>" role="button">Удалить товар</a>
				<?
			}?>
  		</p>
  	</div>


	<div class="row">
		<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>
		<ul class="nav nav-pills nav-justified">
		  <li role="presentation" ><a href="/product/<?=$_GET['id']?>">Описание</a></li>
		  <li role="presentation" ><a href="/product/<?=$_GET['id']?>/comments" >Комментарии <span class="badge"><?=$db->query("SELECT `id` FROM `products_comments` WHERE `id_product`=".$_GET['id']."")->num_rows?></span></a></li>
		  <li role="presentation" class="active" style="border-radius: 0px;"><a href="#">Отзывы <span class="badge"><?=$db->query("SELECT `id` FROM `products_reviews` WHERE `id_product`=".$product['id']."")->num_rows?></span></a></li>
		</ul>
	</div>
	
	<div class="row">
		<?if(isset($_POST['send'])){
			if(!isUser()){?>
				<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Оставлять отзывы могут только авторизованные пользователи!</div>
			<?}else{
				if($db->query("SELECT * FROM `purchased` WHERE `id_user`=".$user['id']." AND `id_product`=".$_GET['id']."")->num_rows == 0){?>
					<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Оставлять отзывы могут только пользователи, которые купили этот товар!</div>
				<?}elseif($db->query("SELECT * FROM `products_reviews` WHERE `id_user`=".$user['id']." AND `id_product`=".$_GET['id']."")->num_rows != 0){?>
					<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Вы уже оставляли отзыв к этому товару!</div>
				<?}else{
					$_POST['text_plus'] = input($_POST['text_plus']);
					$_POST['text_minus'] = input($_POST['text_minus']);
					$_POST['text_comm'] = input($_POST['text_comm']);
					$_POST['rate'] = input($_POST['rate']);
					if(empty($_POST['text_plus'])){?>
						<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Опишите плюсы товара!</div>
					<?}elseif(empty($_POST['text_minus'])){?>
						<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Опишите минусы товара!</div>
					<?}elseif(empty($_POST['text_comm'])){?>
						<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Введите комментарий!</div>
					<?}elseif(empty($_POST['rate'])){
						?>
						<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Поставьте оценку товару!</div>
						<?
					}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/reviews/'.$name);
							$db->query("INSERT INTO `products_reviews` SET `id_product`='".$_GET['id']."', `id_user`=".$user['id'].", `rating`='".$_POST['rate']."', `text`='".$_POST['text_comm']."', `date`='".time()."', `plus`='".$_POST['text_plus']."', `minus`='".$_POST['text_minus']."'");
							$last = $db->insert_id;
							$db->query("INSERT INTO `products_reviews_images` SET `id_review`='".$last."', `image`='".$name."'");
							header('location:/product/'.$product['id'].'/reviews');
						}
					}else{
						$db->query("INSERT INTO `products_reviews` SET `id_product`='".$_GET['id']."', `id_user`=".$user['id'].", `rating`='".$_POST['rate']."', `text`='".$_POST['text_comm']."', `date`='".time()."', `plus`='".$_POST['text_plus']."', `minus`='".$_POST['text_minus']."'");
						header('location:/product/'.$product['id'].'/reviews');
					}
					}
				}
			}
		}
		if(isUser() && $db->query("SELECT * FROM `products_reviews` WHERE `id_user`=".$user['id']." AND `id_product`=".$_GET['id']."")->num_rows == 0 AND $db->query("SELECT * FROM `purchased` WHERE `id_user`=".$user['id']." AND `id_product`=".$_GET['id']."")->num_rows != 0){
			?>
			<form action="" method="POST" enctype="multipart/form-data">
				<div class="form-row">
					<div class="form-group">
						<label for="inputPlus">Достоинства</label>
						<textarea class="form-control" placeholder="Расскажите о достоинствах товара" rows="5" name="text_plus" id="inputPlus"></textarea>
					</div>
				</div>
				<div class="form-row">
					<div class="form-group">
						<label for="inputMinus">Недостатки</label>
						<textarea class="form-control" placeholder="Расскажите о недостатках товара" rows="5" name="text_minus" id="inputMinus"></textarea>
					</div>
				</div>
				<div class="form-row">
					<div class="form-group">
						<label for="inputText">Комментарий</label>
						<textarea class="form-control" placeholder="Оставьте Ваш комментарий" rows="5" name="text_comm" id="inputText"></textarea>
					</div>
				</div>
					<div class="form-row">
						<div class="form-group">
					    	<label for="inputRate">Оценка</label>
					    	<select id="inputRate" class="form-control" name="rate">
					    		<option selected>Выберите...</option>
					    		<option value="1">1 (ужасно)</option>
					    		<option value="2">2 (плохо)</option>
					    		<option value="3">3 (удовлетворительно)</option>
					    		<option value="4">4 (хорошо)</option>
					    		<option value="5">5 (отлично)</option>
					    	</select>
					    </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>
		<?}?>
	</div>
	<div class="row">
		<div class="panel panel">
			<div class="panel-body comments">
				<ul class="media-list">
					<?
					$query = $db->query("SELECT * FROM `products_reviews` WHERE `id_product`=".$_GET['id']."");
					while($review = $query->fetch_assoc()){
						$us = $db->query("SELECT * FROM `users` WHERE `id`=".$review['id_user']."")->fetch_assoc();?>
						<li class="media">
				 			<div class="comment">
				 				<a href="/user/<?=$us['id']?>" class="pull-left">
				 					<?if(file_exists($_SERVER["DOCUMENT_ROOT"].'/files/images/avatars/'.$us['id'].'.jpg')){
				 						?>
				 						<img src="/files/images/avatars/<?=$us['id']?>.jpg" alt="" class="img-circle" width="60" height="60">
				 						<?
				 					}else{?>
				 						<img src="/files/images/avatars/no_avatar.png" alt="" class="img-circle" width="60" height="60">
				 					<?}?>
				 				</a>
				 				<div class="media-body">
				 					<strong class="text-success"><a href="/user/<?=$us['id']?>" class="text-success" style="text-decoration: none;"><?=output($us['name'].' '.$us['surname'])?></a></strong>
				 					<span class="text-muted">
				 						<small class="text-muted"><?=datef($review['date'])?> поставил <span class="label label-warning"><?if($review['rating']>=1){?><span class="glyphicon glyphicon-star" aria-hidden="true"></span><?}?> <?if($review['rating']>=2){?><span class="glyphicon glyphicon-star" aria-hidden="true"></span><?}?> <?if($review['rating']>=3){?><span class="glyphicon glyphicon-star" aria-hidden="true"></span><?}?> <?if($review['rating']>=4){?><span class="glyphicon glyphicon-star" aria-hidden="true"></span><?}?> <?if($review['rating']>=5){?><span class="glyphicon glyphicon-star" aria-hidden="true"></span><?}?></span></small>
				 					</span>
				 					<span class="text-muted pull-right">
					 					<a href="/product/<?=$product['id']?>/reviews/<?=$review['id']?>/comments"><small class="btn btn-default btn-xs"><i class="glyphicon glyphicon-comment"></i> Комментарии <span class="badge"><?=$db->query("SELECT `id` FROM `products_reviews_comm` WHERE `id_review`=".$review['id']."")->num_rows?></span></small> </a>
					 					<?
				 						if($user['admin'] >= 1 OR $review['id_user'] == $user['id']){?>
					 						<a href="/product/<?=$product['id']?>/reviews/<?=$review['id']?>/edit"><small class="btn btn-primary btn-xs"><i class="glyphicon glyphicon-pencil"></i> Редактировать</small></a>
					 						<a href="/product/<?=$product['id']?>/reviews/<?=$review['id']?>/delete"><small class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-remove"></i> Удалить</small></a>
				 						<? } ?>
				 					</span>
				 					<p>
										<div class="panel panel-success">
											<div class="panel-heading">
												<h3 class="panel-title">Достоинства</h3>
											</div>
											<div class="panel-body">
												<?=output($review['plus'])?>
											</div>
										</div>
										<div class="panel panel-danger">
											<div class="panel-heading">
												<h3 class="panel-title">Недостатки</h3>
											</div>
											<div class="panel-body">
												<?=output($review['minus'])?>
											</div>
										</div>
										<div class="panel panel-info">
											<div class="panel-heading">
												<h3 class="panel-title">Комментарий</h3>
											</div>
											<div class="panel-body">
												<?=output($review['text'])?>
											</div>
										</div>
										<? $imgq = $db->query("SELECT * FROM `products_reviews_images` WHERE `id_review`=".$review['id']."");
										if($imgq->num_rows != 0){
											while($img = $imgq->fetch_assoc()){
												?>
												<div class="col-xs-6 col-md-3">
												    <a href="/files/images/reviews/<?=output($img['image'])?>" class="thumbnail">
												      <img src="/files/images/reviews/<?=output($img['image'])?>">
												    </a>
												</div>
												<?
											}
										}?>
									</p>
				 				</div>
				 				<div class="clearfix"></div>
				 			</div>
				 		</li>
				 	<?}?>
				</ul>
			</div>
		</div>
	</div>
</div>

<?
include_once($_SERVER["DOCUMENT_ROOT"].'/php/style/foot.php');
?>