<?
if (isset($ID)) {
  $support = $sql -> fetch("SELECT * FROM `support_id` WHERE `id` = '$ID' LIMIT 1");
  
  if (!isset($support['id'])) {
    die('Нет такого тикета');
  }
}

if ((isset($support['id']) && $level < 2 && $user['id'] != $support['id_user']) || $level == 0){
  header('Location: /index.php');
  exit;
}

$cats = array('1' => 'Личные данные', '2' => 'Магазин', '3' => 'Товары', '4' => 'Вывод на другие системы', '5' => 'Прочее');
 
if (isset($_GET['close']) && $support['id']) {
  if ($_GET['close'] >= 0 && $_GET['close'] <= 1 && $support['close'] != $_GET['close']) {
    $close = (int) $_GET['close'];
    
    if ($close == 1 && $support['id_user'] == $user['id']) {
      $sql -> update("UPDATE `support_id` SET `close` = '1' WHERE `id` = '$support[id]'");
      $support['close'] = $close;
    } elseif ($support['id_user'] != $user['id']) {
      $sql -> update("UPDATE `support_id` SET `close` = '$close' WHERE `id` = '$support[id]'");
      $support['close'] = $close;
    }
    
    if ($support['id_user'] != $user['id'] && $close == 1) {
      journal($support['id_user'], 'support', "Ваш тикет [url=?func=support&id=$support[id]]$support[title] [/url] закрыл".($user['pol']==0?'a':null)." [url=?func=user.profile&id=$user[id]]" . login($user['id'], 0) . "[/url]");
    } elseif ($support['id_user'] != $user['id'] && $close == 0) {
      journal($support['id_user'], 'support', "Ваш тикет [url=?func=support&id=$support[id]]$support[title] [/url] cнова был открыт [url=?func=user.profile&id=$user[id]]" . login($user['id'], 0) . "[/url]");
    }

    if ($close == 1) {
      $messages[] = 'Тикет успешно закрыт';
    } elseif ($close == 0 && $support['id_user'] != $user['id']) {
      $messages[] = 'Тикет успешно открыт';
    }
  }
}

if (isset($support['id']) && $user['id'] == $support['id_user']) {
  $sql -> update("UPDATE `support` SET `read` = '1' WHERE `id_tiket` = '$support[id]' AND `level` > '1' AND `id_user` != '$user[id]' AND `read` = '0'");
} elseif (isset($support['id']) && $user['id'] != $support['id_user']) {
  $sql -> update("UPDATE `support` SET `read` = '1' WHERE `id_tiket` = '$support[id]' AND `level` = '1' AND `read` = '0'");
}

if (isset($_POST['msg'])) {
  $title = null;
  $type = null;
  
  $msg = $sql->esc($_POST['msg']);
  
  if (isset($_GET['create']) && !isset($support['id'])) {
    $title = $sql->esc($_POST['title']);
    $type = $sql->esc($_POST['type']);
    $screens = 0;
    
    if (strlen2($title) > 1024) {
      $err[] = 'Тема слишком длинная';
    } elseif (strlen2($title) < 2) {
      $err[] = 'Тема слишком короткая';
    }  
    
    if (isset($_FILES['screen']['name'][0])) {
      for ($i = 0; count($_FILES['screen']['name']) > $i; $i++) {
    		if (isset($_FILES['screen']['tmp_name'][$i]) && $imgc = @imagecreatefromstring(file_get_contents($_FILES['screen']['tmp_name'][$i])))	{
          $cache = md5($_FILES['screen']['name'][$i].$time);
          $screen[] = $cache;
          @copy($_FILES['screen']['tmp_name'][$i], SRC.'screen/support/' . $cache . '.png');
    		}
      }    
    }
    
    if (isset($screen) && is_array($screen)) {
      $screens = serialize($screen);
    } else {
      $screens = null;
    }
  }
  
  if (strlen2($msg) > 1024) {
    $err[] = 'Сообщение слишком длинное';
  } elseif (strlen2($msg) < 2) {
    $err[] = 'Сообщение слишком короткое';
  }
  
  if (!isset($err)) {
    
    if (isset($_GET['create']) && !isset($support['id'])) {
      $sql -> insert("INSERT INTO `support_id` (`id_user`, `time`, `time_last`, `type`, `id_last`, `title`, `screens`, `msg`) 
      VALUES ('$user[id]', '$time', '$time', '$type', '$user[id]', '$title', '$screens', '$msg')");
      $support['id'] = $sql->insert_id();
      
      $sql -> insert("INSERT INTO `support` (`id_user`, `id_tiket`, `time`, `msg`) VALUES ('0', '$support[id]', '$time', '[green]Вы создали новое обращение в службу поддержки нашего магазина, администрация ответит вам в ближайшее время..[/green]')");
      
      $_SESSION['message'] = 'Тикет успешно создан';
    } else { 
      if ($user['id'] != $support['id_user']) {
        journal($support['id_user'], 'support', "На Ваш тикет [url=?func=support&id=$support[id]]$support[title] [/url] ответил".($user['pol']==0?'a':null)." [url=?func=user.profile&id=$user[id]]" . login($user['id'], 0) . "[/url]");
      }
      
      $sql -> insert("INSERT INTO `support` (`id_user`, `id_tiket`, `time`, `msg`, `level`) VALUES ('$user[id]', '$support[id]', '$time', '$msg', '$level')");
      $_SESSION['message'] = 'Сообщение успешно отправлено';
    }

    $sql -> update("UPDATE `support_id` SET `time_last` = '$time', `id_last` = '$user[id]' WHERE `id` = '$support[id]' LIMIT 1");

    header('Location: ?func=' . $func . '&id=' . $support['id']);
    exit;
  } elseif (!isset($support['id'])) {
    foreach($screens AS $key => $cache) {
      @unlink(SRC . 'screen/support/' . $cache . '.png');
    }
  }
}

$system['title'] = 'Онлайн-поддержка';
require SYS . 'header.php';

if (isset($support['id'])) {
  
  ?><div class="nav2"><b><font color="blue">Автор</font></b>: <?= login($support['id_user'], 1)?> | Тема: <b><?= text($support['title'])?></b> | <b><?= ($support['close'] == 0 ? '<span class="on">Открыт</span>' : '<span class="off">Закрыт</span>')?></b></div>
  <div class="nav1">Сообщение: <?= text_out($support['msg'])?></div><?
  if ($support['screens']) {
    $screens = unserialize($support['screens']);
    
    ?>
    <table class="table table-bordered" style="margin: 2px; width: 99%;">
     <tr>
      <td style="width: 25px;">#ID</td>
      <td>Скриншот</td>
     </tr>
     
      <?
      foreach ($screens AS $key => $value) {
        ?>
        <tr>
         <td  class="success" style="width: 25px;"><center><?= $key?></center></td>
         <td  class="success" ><a href="/_images/screen/support/<?= $value?>.png"><i class="icon-picture"></i> <?= $value?>.png</a></td>
        </tr>
        <?
      }
      ?>
    </table><?
  }
  
  ?>
  <div class="foot">
  <? if ($support['close'] == 0 || $level > 1) { ?>
  <?= ($support['close'] != 1 ? '<a href="?func=support&amp;id=' . $ID . '&amp;close=1"><i class="icon-off"></i> Закрыть тикет</a>' : '<a href="?func=support&amp;id=' . $ID . '&amp;close=0"><i class="icon-refresh"></i> Открыть тикет</a>')?>
  <? } elseif ($support['close'] == 1) { ?>
    <i class="icon-lock"></i> <span class="off"> Тикет закрыт</span>
  <? } ?>
  </div> 
  <?

  $k_post = $sql -> selectCount("SELECT COUNT(*) FROM `support` WHERE `id_tiket` = '$support[id]'");

  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 `support` WHERE `id_tiket` = '$support[id]' ORDER BY `time` DESC LIMIT $start, $system[page_str]");

    foreach ($array AS $post) {
      $num++;
      
      ?>
      <div class="<?= ($num % 2 ? "nav2" : "nav1")?>">
        <?= login($post['id_user'], 1)?> <?= vremja($post['time'])?> <?= ($post['read'] == 0 && $post['id_user'] != 0 ? '<span class="off">[не прочитано]</span>' : '')?> <br />
        <?= text_out($post['msg'])?><br />
      </div>
      <?
    }

    if ($k_page > 1) { 
      str('?func=' . $func . '&amp;id=' . $support['id'] . '&amp;', $k_page, $page);
    }  
  }
  
  if ($support['close'] == 0) {
    ?>
    <form class="form_t" action="?func=support&amp;id=<?= $ID?>" method="POST" style="margin: 2px;">
      <? if (is_file(THEME . 'php/form.textarea.php')) {
        require THEME . 'php/form.textarea.php';
      } else {
        ?><textarea style="width: auto;" name="msg" id="msg" placeholder="Cообщение..."></textarea><br /><?
      }
      ?>
      <button type="submit" class="btn">Отправить</button>  &nbsp; <a href="?func=support&amp;id=<?= $support['id']?>" class="btn">Обновить</a>
    </form>
    <?    
  }
} elseif (isset($_GET['create'])) {
?>
<div class="nav2">
<form class="form-horizontal" action="?func=<?= $func?>&amp;create" method="POST" style="margin: 2px;" enctype="multipart/form-data">
  
  <div class="control-group">
    <label class="control-label" for="title">Тема обращения</label>
    <div class="controls">
      <input type="text" id="title" name="title" />
    </div>
  </div>
  
  <div class="control-group">
    <label class="control-label" for="msg">Сообщение</label>
    <div class="controls">
      <? if (is_file(THEME . 'php/form.textarea.php')) {
        require THEME . 'php/form.textarea.php';
      } else {
        ?><textarea style="width: auto;" name="msg" id="msg" placeholder="Cообщение..."></textarea><br /><?
      }
      ?>
    </div>
  </div>
  
  <div class="control-group">
    <label class="control-label" for="type">Категория</label>
    <div class="controls">
  		<select name="type" id="type" style="width: auto;">
        <? foreach ($cats AS $keys => $values) { ?>
  		  <option value='<?= $keys?>'><?= $values?></option>
        <? } ?>
  		</select>
    </div>
  </div>
  
  <div class="control-group warning">
    <label class="control-label" for="screen">Скриншоты</label>
    <div class="controls" id="screens">
      <input type="file" name="screen[]" id="screen1" style="width: 200px" /><br />
    </div>
    
    <div class="controls" style="padding: 4px; padding-left: 50px;">
    <a href="#screens" onclick="addScreen()" class="btn">Добавить ещё</a>
    </div>
  </div>
  
  <script>
  var countScreen = 1;
  
  function addScreen() {
    if (countScreen <= 10) {
      countScreen++;
      $('#screens').append('<input type="file" name="screen[]" id="screen' + countScreen + '"  style="width: 200px" /><br />');
    } else {
      alert('Разрешается выгружать не более 10 скриншотов');
    }
  }
  </script>
  
  <div class="control-group">
    <div class="controls">
      <button type="submit" class="btn">Создать</button>
    </div>
  </div>
</form>
</div>
<?
} else {
  ?>
  <div class="foot">
    <a href="?func=<?= $func?>&amp;create"><i class="icon-plus-sign"></i> Новый тикет</a><br />
  </div>
  <?

  $k_post = $sql -> selectCount("SELECT COUNT(*) FROM `support_id` WHERE `id_user` = '$user[id]'");

  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 `support_id` WHERE `id_user` = '$user[id]' ORDER BY `time_last` DESC LIMIT $start, $system[page_str]");

    foreach ($array AS $post) {
      
      $count = $sql -> fetch("SELECT 
        SUM(IF(`read` = '0' AND `level` > '1' AND `id_tiket` = '$post[id]', 1, 0)) AS 'new',
        SUM(IF(`level` = '1' AND `id_tiket` = '$post[id]' AND `id_user` != '0', 1, 0)) AS 'user',
        SUM(IF(`level` > '1' AND `id_tiket` = '$post[id]', 1, 0)) AS 'contact'
        FROM `support`");
        
      $count = array('new' => (int) $count['new'], 'contact' => (int) $count['contact'], 'user' => (int) $count['user']);
      $num++;
      ?>
      <div class="<?= ($num % 2 ? "nav1" : "nav2")?>">
        <? if ($level == 4) { ?>
        <a href="?func=admin.support&amp;delete=<?= $post['id']?>&amp;page=<?= $page?>&amp;close=<?= $close?>" class="close">&times;</a>
        <? } ?>
        <a href="?func=support&amp;id=<?= $post['id']?>"><i class="icon-comment"></i> <?= text($post['title'])?></a> 
        [<?= $count['contact']?>/<?= $count['user']?>]<?= ($count['new'] > 0 ? ' <span class="off">+' . $count['new'] . '</span>' : '')?>  (<?= vremja($post['time'])?>)<br />
        Категория: <b><?= $cats[$post['type']]?></b><br />
        Посл.: <?= login($post['id_last'], 1)?> (<?= vremja($post['time_last'])?>)<br />
        Статус: <b><?= ($post['close'] == 0 ? '<span class="on">Открытый тикет</span>' : '<span class="off">Закрытый тикет</span>')?></b><br />
        
      </div>
      <?
    }

    if ($k_page > 1) { 
      str('?func=' . $func . '&amp;', $k_page, $page);
    }
  }
}


if (isset($support['id']) && $support['id_user'] != $user['id']) {
  ?>
  <div class="foot">
    &laquo; <a href="?func=admin.support&amp;create">Список тикетов</a><br />
  </div>
  <?
} elseif (isset($support['id']) || isset($_GET['create'])) {
  ?>
  <div class="foot">
    &laquo; <a href="?func=support">Список тикетов</a><br />
  </div>
  <?
} else {
  ?>
  <div class="foot">
    &laquo; <a href="?func=user.main">В кабинет</a><br />
  </div>
  <?
}
?>