<?php

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

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

require_once cot_incfile('forms');

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('ds', 'a');
cot_block($usr['auth_read']);

$maxrowsperpage = 40;
list($pn, $d, $d_url) = cot_import_pagenav('d', $maxrowsperpage);

$chatid = cot_import('id','G','INT');
$msgcroll = cot_import('msg','G','INT');
if(!$msgcroll) $msgcroll = 0;
$sq = cot_import('sq', 'G', 'TXT');
$resend = cot_import('resend', 'G', 'INT');

$list_url_path = array('m' => 'dialog', 'id' => $chatid, 'sq' => $sq);

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

$issupport = in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups']);

$supportchat = 0;
if(!$issupport) {
  $supportchat = cot_create_chat($usr['id'], 0);
} elseif($chatid > 0) {
  $supportchat = cot_chat_id($chatid, 0);
}

if (empty($supportchat))
{
  cot_redirect(cot_url('ds'));
}

$dialogsql = $db->query("SELECT * FROM $db_ds_dialog WHERE id = $supportchat LIMIT 1")->fetch();    //определяем диалог

if (empty($dialogsql) || !($dialogsql['fromid'] == $usr['id'] || $dialogsql['toid'] == $usr['id'] || $issupport))     //проверяем есть ли такой чат для этого пользователя
{
	cot_redirect(cot_url('ds'));
}

$chatid = $dialogsql['id'];

$opponent = ($dialogsql['fromid'] == 0) ? $dialogsql['toid'] : $dialogsql['fromid'];  //определяем c кем переписка
$newpm = ($dialogsql['fromid'] == 0) ? $dialogsql['fromstatus'] : $dialogsql['tostatus'];  //определяем есть ли в диалоге новые сообщения для меня
$state = ($dialogsql['fromid'] == 0) ? array('fromstatus' => '0') : array('tostatus' => '0');
$act_f = ($dialogsql['fromid'] == 0) ? 'act_fid' : 'act_tid';

$oppname = $db->query("SELECT user_name FROM $db_users WHERE user_id = $opponent LIMIT 1")->fetch();    //для вывода в название

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

if($issupport) {
  $title_params = array(
  	'DIALOG' => $L['ds_dialogwith'],
  	'OPP' => $oppname['user_name'],
  );
  $out['subtitle'] = cot_title('{DIALOG} {OPP}', $title_params);
} else {
  $out['subtitle'] = $cfg['ds']['supportinfo']['pagetitle'];
}
$out['head'] .= $R['code_noindex'];

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

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

$t = new XTemplate(cot_tplfile(array('ds', 'dialog.support')));

$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($issupport) {
  $t->assign(cot_generate_usertags($opponent, 'DS_OPONENT_'));
} else {
  $t->assign(array(
    'DS_OPONENT_NICKNAME' => $cfg['ds']['supportinfo']['name'],
    'DS_OPONENT_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar'],
    'DS_OPONENT_ONLINE' => $supportonline
  ));
}

$lastdate = '';
$date_segodna = cot_date('d.m.Y', $sys['now']);
$date_vchera = cot_date('d.m.Y', $sys['now']-86400);

$totalitems = $db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE dialog = '".$chatid."' AND $act_f!=0 ".(!empty($sqsearch) ? " AND text LIKE '%".$sqsearch."%'" : ''))->fetchColumn();

$pagenav = cot_pagenav('ds', $list_url_path, $d, $totalitems, $maxrowsperpage);

$lastpage = true;
$dsearch = ($totalitems > 0 ? $pagenav['total'] : 1);

if($totalitems > 0 && $pagenav['current'] > 0 && isset($_GET['d'])) {
  $dsearch -= $pagenav['current'];
  if($dsearch != 0) $lastpage = false;
} else {
  $pagenav = cot_pagenav('ds', $list_url_path, ($dsearch-1)*$maxrowsperpage, $totalitems, $maxrowsperpage);
  if(!isset($_GET['d'])) $dsearch = 0;
}
$dsearch = $dsearch*$maxrowsperpage;
if(($dsearch + $maxrowsperpage) > $totalitems) $dsearch = $totalitems-$maxrowsperpage;
if($dsearch < 0) $dsearch = 0;

$dialog_history = $db->query("SELECT * FROM $db_ds_msg WHERE dialog = '".$chatid."' AND $act_f!=0 ".(!empty($sqsearch) ? " AND text LIKE '%".$sqsearch."%'" : '')." ORDER BY id DESC LIMIT $dsearch, " . $maxrowsperpage)->fetchAll();
if (!empty($dialog_history))
{
  $dialog_history = array_reverse($dialog_history);

  if (isset($_SESSION['dialogs'][$opponent]))
  {
   $opptags = $_SESSION['dialogs'][$opponent];
  }else{
   $opptags = cot_generate_usertags($opponent, 'DS_ROW_USER_');
   $_SESSION['dialogs'][$opponent] = $opptags;
  }
  if (isset($_SESSION['dialogs']['my']))
  {
   $usrtags = $_SESSION['dialogs']['my'];
  }else {
   $usrtags = cot_generate_usertags($usr['id'], 'DS_ROW_USER_');
   $_SESSION['dialogs']['my'] = $usrtags;
  }

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

	foreach ($dialog_history as $row)
	{
    $msgscore = $db->query("SELECT * FROM $db_ds_score WHERE s_mid=".$row['id'].' LIMIT 1')->fetch();
    if(!$msgscore['s_mid']) $msgscore['s_mid'] = 0;

    $t->assign(array(
			'DS_ROW_ID' => $row['id'],
      'DS_ROW_TOUSER' => ($row['touser'] > 0 ? $row['touser'] : $usr['id']),
      'DS_ROW_TOUSER_REAL' => $row['touser'],
      'DS_ROW_FRUSER' => $row['fruser'],
			'DS_ROW_DATE' => cot_date('H:i', $row['date']),
			'DS_ROW_TEXT' => (!empty($sqsearch) ? preg_replace("/($sq)/iu",'<span style="background-color: #ffcbb1;">$1</span>', $row['text']) : $row['text']),
      'DS_ROW_RESEND' => cot_ds_resend_msg($row['resend']),
      'DS_ROW_STATUS' => $row['status'],
      'DS_ROW_STAR' => ($row[$act_f] == 2 ? 1 : 0),
      'DS_ROW_SCROLL' => (($msgscroll > 0 && $msgscroll == $row['id']) ? 'data-msgscroll=""' : ''),
      'DS_ROW_SCORE' => $msgscore
		));

    if($opponent == 0) {
      $opptags['DS_ROW_USER_NICKNAME'] = (!empty($row['modername']) ? $row['modername'] : $cfg['ds']['supportinfo'][($row['fruser'] > 0 ? 'name' : 'nameauto')]);
      $opptags['DS_ROW_USER_AVATAR_SRC'] = $cfg['ds']['supportinfo']['avatar'];
      $opptags['DS_ROW_USER_ONLINE'] = $supportonline;
    } else {
      $usrtags['DS_ROW_USER_NICKNAME'] = (!empty($row['modername']) ? $row['modername'] : $cfg['ds']['supportinfo'][($row['fruser'] > 0 ? 'name' : 'nameauto')]);
      $usrtags['DS_ROW_USER_AVATAR_SRC'] = $cfg['ds']['supportinfo']['avatar'];
      $usrtags['DS_ROW_USER_ONLINE'] = $supportonline;
    }

    if ($row['touser'] != $opponent)
    {
      $t->assign($opptags);
    }else{
		  $t->assign($usrtags);
    }

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

    $row['date'] = cot_date('d.m.Y', $row['date']);
    if(empty($lastdate) || $lastdate != $row['date']) {
      $t->assign(array(
  			'DS_ROW_HR' => ($row['date'] == $date_segodna ? 'сегодня' : ($row['date'] == $date_vchera ? 'вчера' : $row['date'])),
  		));
      $t->parse('MAIN.DS_ROW.DS_HR');
      $lastdate = $row['date'];
    }

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

$cntnewmsgs = $db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE dialog = '".$chatid."' AND touser=".($issupport ? 0 : $usr['id'])." AND status=1 AND $act_f!=0 ".(!empty($sqsearch) ? " AND text LIKE '%".$sqsearch."%'" : ''))->fetchColumn();
if(!$cntnewmsgs) $cntnewmsgs = 0;

$t->assign(array(
  'CNTNEWMSGS' => $cntnewmsgs,
  'DIALOG_ID' => $chatid,
  'DS_FORM_SEARCH' => cot_url('ds', 'm=dialog&al=support'),
	'DS_FORM_SEND' => cot_url('ds', 'm=ajax&a=send&chat='.$chatid),
	'DS_FORM_TEXT' => cot_textarea('newpmtext', $newpmtext, 4, 56),
	"PAGENAV_PAGES" => $pagenav['main'],
	"PAGENAV_PREV" => $pagenav['prev'],
	"PAGENAV_NEXT" => $pagenav['next'],
  "PAGENAV_LAST" => $pagenav['lastlink'],
	"PAGENAV_COUNT" => $totalitems,
));

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

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

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