<?
 if ($level > 0) {
if (isset($ID)) {
  $goods = $sql -> fetch("SELECT * FROM `shop_goods` WHERE `id` = '$ID' LIMIT 1");
  $pays = $sql -> fetch("SELECT * FROM `shop_pays` WHERE `id_user` = '$user[id]' AND `id_goods` = '$goods[id]' AND `pays` = '1' LIMIT 1");
}

if (!isset($goods['id'])){
  die('К сожалению товар не найден или он был удален');
}


if ($goods['unlink'] == 1 && $level < 3) {
  die('Ошибка: Товар удален');
}

if (isset($_GET['type']) && $_GET['type'] == 1) {
  $type = 1;
} else {
  $type = 0;
}

if (isset($_GET['delete'])) {
  $delete = (int) $_GET['delete'];
  $delete = $sql -> fetch("SELECT * FROM `shop_votes` WHERE `id_goods` = '$ID' AND `id_user` = '$delete' LIMIT 1");
  
  if ($level > 2 || ($delete['id_user'] == $user['id'] && $type == 0)) {
      
      if ($delete['id_user'] != $user['id']) {
        admin_log($user['id'], 'Магазин|Отзывы о товаре', 'Удаление '.($type == 1 ? 'положительного отзыва: [green]\"' . $delete['msg'] . '\"[/green]' : 'отрицательного отзыва: [red]\"' . $delete['msg'] . '\"[/red]').'\rПользователя [url=?func=user.profile&id=' . $delete['id_user'] . ']' . login($delete['id_user']) . '[/url] у товара [url=?func=shop.goods&id=' . $goods['id'] . ']' . $goods['name'] . '[/url]');
      }
      
    if ($delete['type'] == 0) {
      $sql -> update("UPDATE `shop_goods` SET `rating` = `rating` + '1' WHERE `id` = '$goods[id]' LIMIT 1");
      $sql -> update("UPDATE `users` SET `rating` = `rating` + '1' WHERE `id` = '$goods[id_user]' LIMIT 1");  
      $sql -> update("UPDATE `shop_pays` SET `ok` = '0' WHERE `id_goods` = '$goods[id]' AND `id_user` = '$delete[id_user]' LIMIT 1");   
    } else {
      $sql -> update("UPDATE `shop_goods` SET `rating` = `rating` - '1' WHERE `id` = '$goods[id]' LIMIT 1");
      $sql -> update("UPDATE `users` SET `rating` = `rating` - '1' WHERE `id` = '$goods[id_user]' LIMIT 1");    
    }

    $sql -> delete("DELETE FROM `shop_votes` WHERE `id_user` = '$delete[id_user]' AND `id_goods` = '$goods[id]' LIMIT 1");
    $messages[] = 'Отзыв успешно удален';    
  }
}


if (isset($_POST['msg']) && $level > 0 && $pays['id'] && ($sql -> selectCount("SELECT COUNT(*) FROM `shop_votes` WHERE `id_goods` = '$goods[id]' AND `id_user` = '$user[id]'") == 0)) {
  $msg = $sql->esc($_POST['msg']);
  
  if (strlen2($msg) > 512) {
    $err[] = 'Сообщение слишком длинное';
  } elseif (strlen2($msg) < 2) {
    $err[] = 'Сообщение слишком короткое';
  }
  
  if (!isset($err)) {
    journal($goods['id_user'], 'goods', "Пользователь [b]$user[login] [/b], оставил".($user['pol']==0?'a':null)." ".($type == 1 ? '[green]положительный[/green]' : '[red]отрицательный[/red]')." отзыв к вашему товару [url=?func=shop.votes&id=" . $goods['id'] . "&type=$type]" . $goods['name'] . "[/url]");
    
    if ($type == 1) {
      $sql -> update("UPDATE `shop_goods` SET `rating` = `rating` + '1' WHERE `id` = '$goods[id]' LIMIT 1");
      $sql -> update("UPDATE `users` SET `rating` = `rating` + '1' WHERE `id` = '$goods[id_user]' LIMIT 1");
      
      if ($pays['out_time'] == 0) {
        $sql -> update("UPDATE `shop_pays` SET `ok` = '1', `out_wmr` = '0' WHERE `id_goods` = '$goods[id]' AND `id_user` = '$user[id]' LIMIT 1"); 
      }
      
    } elseif ($type == 0) {
      $sql -> update("UPDATE `shop_goods` SET `rating` = `rating` - '1' WHERE `id` = '$goods[id]' LIMIT 1");
      $sql -> update("UPDATE `users` SET `rating` = `rating` - '1' WHERE `id` = '$goods[id_user]' LIMIT 1");

/*sms оповещение*/
$TelSms = $sql -> fetch("SELECT * FROM `users` WHERE `id` = '" . $goods['id_user'] . "' AND `date_last` < '". time() ."' LIMIT 1");
if ($TelSms['MyTelefonOk'] == 1 && $TelSms['tel_jaloba']== 1 && $TelSms['date_last'] < time()-600 && $TelSms['wmr'] >= 1)
{

    if ($sql -> select("SELECT * FROM `smsantiflud` WHERE `id_user` = '".$TelSms['id']."' AND `mod` = 'jaloba'") == 0)
    {
    include_once FUNC.'smsc_api.php';
    $r = send_sms($TelSms['MyTelefon'], "У Вас новая жалоба на товар 4i4i.Ru");

    if ($r[1] > 0)
        {
					
        $sql -> update("UPDATE `users` SET `wmr` = `wmr` - '1' WHERE `id` = '".$TelSms['id']."' LIMIT 1");
		$BySMS = "Списание за смс оповещение о жалобе к товару на мобильный телефон.";
        $sql -> insert("INSERT INTO `billing_log` (`time`, `type`, `id_user`, `coins`, `msg`) VALUES ('".time()."', 'Mysms', '$TelSms[id]', '-1', '$BySMS')");
		$sql -> insert("INSERT INTO `smsantiflud`(`time`, `id_user`, `mod`) VALUES('".time()."', '".$TelSms['id']."', 'jaloba')");
        }
    }
}
      /*sms оповещение*/

      if ($pays['out_time'] == 0) {
        $sql -> update("UPDATE `shop_pays` SET `out_wmr` = '2' WHERE `id_goods` = '$goods[id]' AND `id_user` = '$user[id]' LIMIT 1"); 
      }
      
      admin_journal($user['id'], 'votes', " оставил".($user['pol']==0?'a':null)." [red]отрицательный[/red] отзыв к товару [url=?func=shop.votes&id=" . $goods['id'] . "&type=$type]" . $goods['name'] . "[/url]");
    }
    
    $sql -> insert("INSERT INTO `shop_votes` (`id_user`, `id_goods`, `time`, `msg`, `type`) VALUES ('" . $user['id'] . "', '" . $ID . "', '$time', '$msg', '$type')");
    
    $_SESSION['message'] = 'Отзыв успешно отправлен';
    header('Location: ?func=' . $func . '&id=' . $ID . '&type=' . $type);
    exit;
  }
}

$system['title'] = ($type == 1 ? 'Положительные' : 'Отрицательные') . ' отзывы - ' . text($goods['name']);
require SYS . 'header.php';

if ($pays['id'] && $sql -> selectCount("SELECT COUNT(*) FROM `shop_votes` WHERE `id_goods` = '$goods[id]' AND `id_user` = '$user[id]'") == 0) {
?>
<form action="?func=shop.votes&amp;id=<?= $goods['id']?>&amp;type=<?= $type?>" method="POST" style="margin: 2px;">
  <? if (is_file(THEME . 'php/form.textarea.php')) {
    require THEME . 'php/form.textarea.php';
  } else {
    ?><textarea style="width: 75%;" name="msg" id="msg" placeholder="Cообщение..."><?= $insert?></textarea><br /><?
  }
  ?>
  <button type="submit" class="btn">Отправить отзыв</button>
</form>
<?  
}

$k_post = $sql -> selectCount("SELECT COUNT(*) FROM `shop_votes` WHERE `id_goods` = '$goods[id]' AND `type` = '$type'");

if ($k_post == 0) {
  ?>
  <div class="alert" style="margin: 2px;">Список отзывов пуст</div>
  <?
} else {
  $k_page = k_page($k_post, $system['page_str']);
  $page = page($k_page);
  $start =  $system['page_str'] * $page -  $system['page_str'];

  $array = $sql -> select("SELECT * FROM `shop_votes` WHERE  `id_goods` = '$goods[id]' AND `type` = '$type' ORDER BY `time` DESC LIMIT $start, $system[page_str]");

  foreach ($array AS $post) {
    $num++;
    ?>
    <div class="<?= ($num % 2 ? "nav1" : "nav2")?>">
      <? if ($level > 2 || ($post['id_user'] == $user['id'] && $type == 0)) { ?>
      <a class="close" href="?func=shop.votes&amp;id=<?= $goods['id']?>&amp;type=<?= $type?>&amp;delete=<?= $post['id_user']?>"><i class="icon-remove"></i></a>
      <? } ?>
      
      <?= login($post['id_user'], 1)?> (<?= vremja($post['time'])?>)<br />
      <span class="<?= ($type == 0 ? 'off' : 'on')?>"><?= text_out($post['msg'])?></span><br />
    </div>
    <?
  }

  if ($k_page > 1) { 
    str('?func=' . $func . '&amp;id=' . $goods['id'] . '&amp;type=' . $type . '&amp;', $k_page, $page);
  }  
}
?>
<div class="foot">
  &laquo; <a href="?func=shop.goods&amp;id=<?= $goods['id']?>">На страницу товара</a><br />
</div>
<?
} else {
require SYS . 'header.php';
?>
  <div class="alert alert-error" style="margin: 2px;">
    <center>
      <img src="<?= ICONS?>big_err.png" /> Для того чтобы зайти в раздел отзывов о товаре, вам необходимо авторизоваться в нашем магазине !<br /><br />
      <a href="?func=user.auth" class="btn">Авторизация</a>
    </center>
  </div>
<?
}
?>
