<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=moderation.page.mnotfind
 * [END_COT_EXT]
 */

defined('COT_CODE') or die('Wrong URL');

if(in_array('ds_dialogs', $moderauth)) {
  $t->parse('MAIN.LINE_DS_DIALOGS');
}

if(in_array('ds', $moderauth)) {
  require_once cot_incfile('ds', 'module');
  require_once cot_langfile('ds', 'module');

  $dialogs = $db->query("SELECT d.* FROM $db_ds_dialog as d
     LEFT JOIN $db_ds_msg as m ON d.id=m.dialog
     WHERE ((d.toid=0 OR d.fromid=0) AND m.id>0 AND m.touser=0 AND ((d.fromid=0 AND m.act_fid!=0) OR (d.toid=0 AND m.act_tid!=0)) AND m.status=1) GROUP BY d.id ORDER BY d.lastmsg DESC")->fetchAll();

  /* === Hook - Part1 : Set === */
  $extp = cot_getextplugins('ds.list.loop');
  /* ===== */

  $jj = 0;
  foreach ($dialogs as $row)
  {
    $jj++;  //счетчик, если равен 0 то парсим "Диалогов нет"

    $issopportchat = true;
    $fromuser = 0;

    $act_f = ($row['fromid'] == $fromuser) ? 'act_fid' : 'act_tid';
    $msgfilter = "(dialog = '".$row['id']."' AND $act_f!=0)";
    $msg = $db->query("SELECT * FROM $db_ds_msg WHERE $msgfilter ORDER BY id DESC LIMIT 1")->fetch();   //получаем последнее сообщение из диалога

    $opponent = ($row['toid'] == $fromuser) ? $row['fromid'] : $row['toid'];  //определяем с каким пользователем идет переписка в этом диалоге
    $from_user = ($msg['touser'] == $fromuser) ? $opponent : $fromuser;  //определяем кто его отправил

    if($msg['text'][0] == '<' && $msg['text'][1] == 'b' && $msg['text'][2] == '>')
      $msg['text'] = preg_replace('/^(<b>(.*)<\/b>)(.*)/i', '$3', $msg['text']);

    $msg['text'] = explode('<br>', $msg['text']);
    $msg['text'][0] = trim($msg['text'][0]);
    $msg['text'] = (!empty($msg['text'][0]) ? $msg['text'][0] : $msg['text'][1]);

    $msg['text'] = strip_tags($msg['text']);

    if(empty($msg['text'])) {
      $msg['resend_arr'] = (!empty($msg['resend']) ? json_decode($msg['resend'],1) : array());
      if(count($msg['resend_arr']) > 0) {
        $msg['text'] = 'Пересылаемое сообщение';
      }
    }

    $t->assign(cot_generate_usertags($opponent, 'DS_OPPONENT_'));
    $dialogurls = array(
      'dialog' => cot_url('ds', 'm=dialog&al=support&id='.$opponent),
      'delete' => '',
    );

    $mdata = cot_ds_get_mdata($msg['mtype'], $msg['mdata']);

    $pretext = '';
    if($msg['mtype'] == 0) {
      $pretext = cot_string_truncate($msg['text'], 65, true, false, "...");
    } else {
      if($msg['mtype'] == 5) {
        $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][5], $mdata);
        $pretext = cot_string_truncate($pretext, 65, true, false, "...");
      } elseif($msg['mtype'] == 6) {
        $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][6], $mdata);
        $pretext = cot_string_truncate($pretext, 65, true, false, "...");
      }else {
        $pretext = $cfg['ds']['mtypes_notytitle'][$msg['mtype']];
      }
    }

  	$t->assign(array(
      'DS_DIALOG_ID' => $row['id'],
      'DS_TIME_AGO' => ($msg['date'] > 0 ? (cot_date('d.m.Y', $msg['date']) == cot_date('d.m.Y', $sys['now']) ? (($msg['date'] > ($sys['now'] - 3600)) ? cot_build_timeago($msg['date']) : 'сегодня в '.cot_date('H:i', $msg['date'])) : (cot_date('d.m.Y', $msg['date']) == cot_date('d.m.Y', $sys['now']-86400) ? 'вчера в '.cot_date('H:i', $msg['date']) : cot_date('d.m.y, H:i', $msg['date']))) : ''),
      'DS_DIAOG_DELETE' => $dialogurls['delete'],
    	'DS_DIAOG_URL' => $dialogurls['dialog'],
      'DS_NEW_CNT' => $db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE $msgfilter AND touser=".$fromuser.' AND '.$act_f.'!=0 AND status=1')->fetchColumn(),  //прочитано или нет
      'DS_STATUS' => (($msg['touser'] != $fromuser && !$msg['status']) ? 0 : 1),  //прочитано или нет
  		'DS_TEXT' => $pretext,   //сокрашенный текст где 65 это колл-во символов после чего сокращяем
      'DS_OPPONENT' => $opponent,
      'DS_ISSOPPORTCHAT' => ($issopportchat ? 1 : 0),
    ));

  	/* === Hook - Part2 : Include === */
  	foreach ($extp as $pl)
  	{
  		include $pl;
  	}
  	/* ===== */

  	$t->parse('MAIN.LINE_DS.DS_ROW');
  }

 	$t->assign(array(
    'DS_NEW_SUPPORT_MSG_CNT' => $jj,
  ));


  $t->parse('MAIN.LINE_DS');
}