<?php ob_start();?>
<style>
#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_reviews` WHERE `id`='".$_GET['id']."'");
if($query->num_rows == 0){
	header('location:/');
	// Отзыва не существует
}
$review = $query->fetch_assoc();
$_GET['id_product'] = abs(intval($_GET['id_product']));
$query = $db->query("SELECT * FROM `products` WHERE `id`='".$_GET['id_product']."'");
if($query->num_rows == 0){
	header('location:/');
	// Товара не существует
}
$product = $query->fetch_assoc();
$cat = $db->query("SELECT * FROM `categories` WHERE `id`='".$product['id_categorie']."'")->fetch_assoc();
if($review['id_product'] != $product['id']){
	header('location:/');
	// Несоответсвие ид товара и отзыва
}
if($user['admin'] < 1 && $user['id']!=$review['id_user']){
	header('location:/');
	// Недостаточно прав
}
?>
<div class="container theme-showcase" role="main">
	<div class="jumbotron" style="background-color: white;">
  		<h1>Редактирование отзыва</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><a href="/product/<?=$product['id']?>/reviews">Отзывы</a></li>
      <li class="active">Редактирование</li>
    </ol>
    </div>
  		<?
  		if(isset($_POST['send'])){
  			$_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_images` SET `id_review`=".$_GET['id'].", `image`='".$name."'");
						}
					}
					$db->query("UPDATE `products_reviews` SET `rating`='".$_POST['rate']."', `text`='".$_POST['text_comm']."', `plus`='".$_POST['text_plus']."', `minus`='".$_POST['text_minus']."'");
					header('location:/product/'.$product['id'].'/reviews/'.$review['id'].'/edit/success');
				}
  		}
  		if(isset($_GET['success'])){
  			showAlertSuccess('Отзыв успешно отредактирован!');
  		}
  		?>
  		<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"><?=output($review['plus'])?></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"><?=output($review['minus'])?></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"><?=output($review['text'])?></textarea>
					</div>
				</div>
					<div class="form-row">
						<div class="form-group">
					    	<label for="inputRate">Оценка</label>
					    	<select id="inputRate" class="form-control" name="rate">
					    		<option>Выберите...</option>
					    		<option value="1" <?if($review['rating']==1){?>selected<?}?>>1 (ужасно)</option>
					    		<option value="2" <?if($review['rating']==2){?>selected<?}?>>2 (плохо)</option>
					    		<option value="3" <?if($review['rating']==3){?>selected<?}?>>3 (удовлетворительно)</option>
					    		<option value="4" <?if($review['rating']==4){?>selected<?}?>>4 (хорошо)</option>
					    		<option value="5" <?if($review['rating']==5){?>selected<?}?>>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>
					  	<?
		  	$imgq = $db->query("SELECT * FROM `products_reviews_images` WHERE `id_review`=".$review['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-6 col-md-4">
		    					<div class="thumbnail">
		      						<a href="/files/images/reviews/<?=output($img['image'])?>">
										<img src="/files/images/reviews/<?=output($img['image'])?>">
									</a>
		      						<div class="caption">
		        						<p><a href="/reviews/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');
?>