<?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);
}

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

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

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

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

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

$opparr = $db->query("SELECT * FROM $db_users WHERE user_id = $opponent LIMIT 1")->fetch();
$moderWmoder = (in_array($opparr['user_maingrp'], $cfg['moder_group_ids']) && in_array($usr['maingrp'], $cfg['moder_group_ids']));

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

$title_params = array(
	'DIALOG' => $L['ds_dialogwith'],
	'OPP' => $opparr['user_name'],
);
$out['subtitle'] = cot_title('{DIALOG} {OPP}', $title_params);
$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')));

$t->assign(cot_generate_usertags($opponent, 'DS_OPONENT_'));

$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)
	{
    $mdata = cot_ds_get_mdata($row['mtype'], $row['mdata']);
    $pretext = '';

    if($row['mtype'] == 5) {
      $mdata['item_url'] = '<a href="'.cot_url('market', 'id='.$mdata['item_id']).'">'.$mdata['item_title'].'</a>';
      $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][5], array('item_title' => $mdata['item_url']));
    } elseif($row['mtype'] == 6) {
      $mdata['item_url'] = '<a href="'.cot_url('projects', 'id='.$mdata['item_id']).'">'.$mdata['item_title'].'</a>';
      $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][6], array('item_title' => $mdata['item_url']));
    }

    $t->assign(array(
			'DS_ROW_ID' => $row['id'],
			'DS_ROW_DATE' => cot_date('H:i', $row['date']),
      'DS_ROW_MODER_GROUP' => (($row['touser'] == $usr['id'] && $moderWmoder) ? '['.$cot_groups[$opparr['user_maingrp']]['title'].']' : ''),
			'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_MTYPE' => $row['mtype'],
      'DS_ROW_MDATA' => $mdata,
      'DS_ROW_PRETEXT' => $pretext,
		));

    if($row['mtype'] == 3) {
      require_once cot_incfile('catcostplans', 'plug');

      $item_cache = $mdata['item_cache'];
      $item_catcostplans = (!empty($item_cache['item_catcostplans']) ? json_decode($item_cache['item_catcostplans'],1) : array());
      if($item_catcostplans['bundle_type'] == 'package') {
        /* plan data parse */
          #входные переменные $item_cache, $item_catcostplans, $mdata
        require_once cot_incfile('catcostplans', 'plug', 'ds_plan_parse');
        /* plan data parse */
        $t->assign(array(
          'DS_ROW_COSTPLAN' => cot_get_costplan_bydata($item_catcostplans, $mdata['package_type']),
        ));
      } else {
        foreach($item_catcostplans['bundles']['custom'] as $key => $val) {
          if(in_array($key, $mdata['gextras']) && $mdata['gextras_count'][$key] > 0) {
            $val['price'] = $costplans_prices[$val['price']];
            $val['count'] = $mdata['gextras_count'][$key];
            $t->assign(array(
        			'DS_GEXTRAS_DATA' => $val,
        		));
            $t->parse('MAIN.DS_ROW.DS_TYPE3_GEXTRAS');
          }
        }
        $t->assign(array(
          'DS_ROW_COSTPLAN' => cot_get_costplan_bydata($item_catcostplans),
        ));
      }
      if(is_array($mdata['gextras_custom'])) foreach($mdata['gextras_custom'] as $val) {
        $t->assign(array(
      	  'DS_GEXTRAS_DATA' => array(
            'name' => $val['name'],
            'duration' => $val['time'],
            'price' => $val['price'],
            'count' => 1,
          ),
      	));
        $t->parse('MAIN.DS_ROW.DS_TYPE3_GEXTRAS');
      }
    }

    if ($row['touser'] == $usr['id'])
    {
      $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=".$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&id='.$chatid),
	'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';
