<?php

/**
 * Dialog System
 * @version 2.2
 * @package DS
 * @copyright (c) Alexeev Vlad
 */

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

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('ds', 'a');
if(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) $usr['isadmin'] = true;

cot_block($usr['auth_read']);

$type = cot_import('type', 'G', 'TXT');
$sq = cot_import('sq', 'G', 'TXT');

$support = cot_import('support', 'G', 'INT');
$support = (($support == 1 && $usr['isadmin']) ? true : false);

$sqsearch = '';
if(!empty($sq)) {
  $sq = strtolower($sq);
  $sqsearch = $db->prep($sq);
}

/* === Hook === */
foreach (cot_getextplugins('ds.list.first') as $pl)
{
	include $pl;
}
/* ===== */

$title[] = array(cot_url('ds'), $L['Private_Messages']);

/* === Hook === */
foreach (cot_getextplugins('ds.list.main') as $pl)
{
	include $pl;
}
/* ===== */

$title_params = array(
	'DS' => $L['ds_dialogs'],
);
$out['subtitle'] = cot_title('{DS}', $title_params);
$out['head'] .= $R['code_noindex'];

require_once $cfg['system_dir'] . '/header.php';

$t = new XTemplate(cot_tplfile(array('ds', 'list', ($support ? 'support' : ''))));

$supportchat = 0;
if(!$usr['isadmin']) {
  $supportchat = cot_create_chat($usr['id'], 0);
} elseif(cot_chat_id($usr['id'], 0) > 0) {
  $delid = cot_chat_id($usr['id'], 0);
  if($delid > 0) {
    $db->delete($db_ds_dialog, 'id='.$delid);
    $db->delete($db_ds_msg, 'dialog='.$delid);
  }
}
$supportonline = 1;

if(cot_plugin_active('whosonline')) {
  $supportonline = 0;
  $modersql = $db->query("SELECT * FROM $db_users WHERE user_maingrp=".implode(' OR user_maingrp=', $cfg['ds']['supportinfo']['modergroups']))->fetchAll();
  foreach($modersql as $val) {
    if(cot_userisonline($val['user_id'])) {
      $supportonline = 1;
      break;
    }
  }
}

if(!empty($sq) || in_array($type, array('unread', 'important'))) {
  $dialogsfilter = "(toid = '".$usr['id']."' AND act_tid!=0) OR (fromid = '".$usr['id']."' AND act_fid!=0) OR d.id=".$supportchat;
  if($support) {
    $dialogsfilter = '((toid=0 OR fromid=0) AND m.id>0)';
  }

  $dialogs = $db->query("SELECT d.* FROM $db_ds_dialog as d
     LEFT JOIN $db_ds_msg as m ON d.id=m.dialog
     WHERE $dialogsfilter GROUP BY d.id ORDER BY m.date DESC")->fetchAll();

  $jj=0;
  if(count($dialogs) > 0) {
    $wheretags = array();
    $wheredial = array();
    foreach($dialogs as $dial) {
      $issopportchat = false;
      $fromuser = $usr['id'];
      if(($dial['toid'] == 0 || $dial['fromid'] == 0) && $usr['isadmin']) {
        $issopportchat = true;
        $fromuser = 0;
      }

      $act_f = ($dial['fromid'] == $fromuser) ? 'act_fid' : 'act_tid';
      if($type == 'important') {
        $wheredial[] = $act_f.'=2 AND dialog='.$dial['id'];
      } else {
        $wheredial[] = $act_f.'!=0 AND dialog='.$dial['id'];
      }
      $wheretags[$dial['id']] = $dial;
    }

    $fmsgs = $db->query("SELECT * FROM $db_ds_msg WHERE (".implode(' OR ', $wheredial).")".(!empty($sqsearch) ? " AND text LIKE '%".$sqsearch."%'" : '')."".($type == 'unread' ? " AND (touser=".$usr['id'].($usr['isadmin'] ? ' OR touser=0' : '').') AND status=1' : '')." ORDER BY id DESC")->fetchAll();

    /* === Hook - Part1 : Set === */
    $extp = cot_getextplugins('ds.list.loop');
    /* ===== */
    $jj = 0;
    foreach ($fmsgs as $msg)
    {
      $jj++;  //счетчик, если равен 0 то парсим "Диалогов нет"

      $row = $wheretags[$msg['dialog']];

      $issopportchat = false;
      $fromuser = $usr['id'];
      if(($row['toid'] == 0 || $row['fromid'] == 0) && $usr['isadmin']) {
        $issopportchat = true;
        $fromuser = 0;
      }

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

      $msg['text'] = strtolower($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'] = 'Пересылаемое сообщение';
        }
      }

      $dialogurls = array(
        'dialog' => cot_url('ds', 'm=dialog&id='.$row['id'].'&msg='.$msg['id']),
        'delete' => '',
      );

      if($supportchat > 0 && $row['id'] == $supportchat) {
        $issopportchat = true;

        $t->assign(array(
          'DS_OPPONENT_NICKNAME' => $cfg['ds']['supportinfo'][($msg['fruser'] > 0 ? 'name' : 'nameauto')],
          'DS_OPPONENT_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar'],
          'DS_OPPONENT_ONLINE' => $supportonline
        ));
        if(!$msg['id']) {
          $msg['text'] = $cfg['ds']['supportinfo']['placeholder'];
        }

        $dialogurls = array(
          'dialog' => cot_url('ds', 'm=dialog&al=support'.'&msg='.$msg['id']),
          'delete' => '',
        );
      } else {
        $t->assign(cot_generate_usertags($opponent, 'DS_OPPONENT_'));
        if($issopportchat) {
          $dialogurls = array(
            'dialog' => cot_url('ds', 'm=dialog&al=support&id='.$opponent.'&msg='.$msg['id']),
            'delete' => '',
          );
        }
      }

      if($issopportchat) {
        $t->assign(array(
          'DS_OPPONENT_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar'],
        ));
      }

      $waitfastanswer = 0;
      $dstate = cot_ds_dstate(0, $row);
      if(is_array($dstate['waitanswer24hour'])) foreach($dstate['waitanswer24hour'] as $mfastansw) {
        if(!$mfastansw['lowrtg'] && $mfastansw['uid'] != $usr['id'] && $mfastansw['date'] > ($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time'])) {
          $waitfastanswer = 1;
          break;
        }
      }

    	$t->assign(array(
        'DS_MSG_ID' => $msg['id'],
        'DS_TIME_AGO' => (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' => '',
        'DS_DIAOG_URL' => $dialogurls['dialog'],   //ссылка на диалог
        'DS_NEW_CNT' => 0,
        'DS_STATUS' => (($msg['touser'] != $fromuser && !$msg['status']) ? 0 : 1),  //прочитано или нет
      	'DS_TEXT' => (!empty($sqsearch) ? preg_replace("/($sq)/iu",'<span style="background-color: #ffcbb1;">$1</span>', $msg['text']) : $msg['text']),
        'DS_OPPONENT' => $opponent,
        'DS_NEW_OF_LAST20DAY_MSG' => $waitfastanswer
    	));

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

    	$t->parse('MAIN.DS_ROW');
    }
  }
  if ($jj == 0)
  {
  	$t->parse('MAIN.DS_EMPTY');
  }
} else {
  $dialogsfilter = "(toid = '".$usr['id']."' AND act_tid!=0) OR (fromid = '".$usr['id']."' AND act_fid!=0) OR d.id=".$supportchat;
  if($support) {
    $dialogsfilter = '((toid=0 OR fromid=0) AND m.id>0)';
  }

  $dialogs = $db->query("SELECT d.* FROM $db_ds_dialog as d
     LEFT JOIN $db_ds_msg as m ON d.id=m.dialog
     WHERE $dialogsfilter GROUP BY d.id ORDER BY lastmsg DESC")->fetchAll();

  /* === Hook - Part1 : Set === */
  $extp = cot_getextplugins('ds.list.loop');
  /* ===== */
  $jj = 0;
  foreach ($dialogs as $row)
  {
    $jj++;  //счетчик, если равен 0 то парсим "Диалогов нет"

    $issopportchat = false;
    $fromuser = $usr['id'];
    if(($row['toid'] == 0 || $row['fromid'] == 0) && $usr['isadmin']) {
      $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'] = 'Пересылаемое сообщение';
      }
    }

    $dialogurls = array(
      'dialog' => cot_url('ds', 'm=dialog&id='.$row['id']),
      'delete' => cot_url('ds', 'm=delete&id='.$row['id'].'&x='.$sys['xk']),
    );

    if($supportchat > 0 && $row['id'] == $supportchat) {
      $issopportchat = true;

      $t->assign(array(
        'DS_OPPONENT_NICKNAME' => $cfg['ds']['supportinfo'][($msg['fruser'] > 0 ? 'name' : 'nameauto')],
        'DS_OPPONENT_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar'],
        'DS_OPPONENT_ONLINE' => $supportonline
      ));
      if(!$msg['id']) {
        $msg['text'] = $cfg['ds']['supportinfo']['placeholder'];
      }

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

    if($issopportchat) {
      $t->assign(array(
        'DS_OPPONENT_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar'],
      ));
    }

    $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']];
      }
    }


    $waitfastanswer = 0;
    $dstate = cot_ds_dstate(0, $row);
    if(is_array($dstate['waitanswer24hour'])) foreach($dstate['waitanswer24hour'] as $mfastansw) {
      if(!$mfastansw['lowrtg'] && $mfastansw['uid'] != $usr['id'] && $mfastansw['date'] > ($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time'])) {
        $waitfastanswer = 1;
        break;
      }
    }

  	$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),
      'DS_NEW_OF_LAST20DAY_MSG' => $waitfastanswer
  	));

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

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

  if ($jj == 0)
  {
  	$t->parse('MAIN.DS_EMPTY');
  }
}

$t->assign(array(
	'DS_PAGETITLE' => cot_breadcrumbs($title, $cfg['homebreadcrumb']),
	'DS_SUBTITLE' => $subtitle,
));

if($usr['isadmin']) {
  $usersql = $db->query("SELECT user_id, user_name FROM $db_users WHERE user_maingrp>3 AND user_maingrp!=".implode(' AND user_maingrp!=', $cfg['ds']['supportinfo']['modergroups']))->fetchAll(PDO::FETCH_KEY_PAIR);

  $t->assign(array(
  	'DS_MODERSENDTOUSER' => cot_selectbox('', 'rmodertouser[]', array_keys($usersql), array_values($usersql), true)
  ));
  $t->parse('MAIN.DS_MODER');
  $t->parse('MAIN.DS_MODER_LINK');
}

/* === Hook === */
foreach (cot_getextplugins('ds.list.tags') as $pl)
{
	include $pl;
}
/* ===== */

$t->parse('MAIN');
$t->out('MAIN');


require_once $cfg['system_dir'] . '/footer.php';
