<?php

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

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


$chatid = cot_import('chat', 'G', 'INT');
$a = cot_import('a', 'G', 'TXT');
$checkmsg = cot_import('checkmsg', 'G', 'TXT');

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

cot_sendheaders();
$result = array();

if (!empty($chatid))
{
  $dialogsql = $db->query("SELECT * FROM $db_ds_dialog WHERE id = $chatid LIMIT 1")->fetch();    //определяем диалог
  
  $fromuserid = $usr['id'];

  $supportchat = 0;
  if(!in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {
    $supportchat = cot_chat_id($usr['id'], 0);
  } elseif($dialogsql['id'] > 0) {
    $supportchat = cot_chat_id((($dialogsql['fromid'] == 0) ? $dialogsql['toid'] : $dialogsql['fromid']), 0);
    if($dialogsql['id'] == $supportchat) $fromuserid = 0;
  }

  if (!empty($dialogsql) && ($dialogsql['fromid'] == $usr['id'] || $dialogsql['toid'] == $usr['id'] || $dialogsql['id'] == $supportchat))     //проверяем есть ли такой диалог для этого пользователя
  {
   $to = ($dialogsql['fromid'] == $fromuserid) ? $dialogsql['toid'] : $dialogsql['fromid'];  //определяем с кем диалог
   $newpm = ($dialogsql['fromid'] == $fromuserid) ? $dialogsql['fromstatus'] : $dialogsql['tostatus'];  //определяем есть ли в диалоге новые сообщения для меня
   $tonewpm = ($dialogsql['fromid'] == $fromuserid) ? array('tostatus' => '1') : array('fromstatus' => '1');  //для установки статуса нового сообщения для собеседника
   $readpm =  ($dialogsql['fromid'] == $fromuserid) ? array('fromstatus' => '0') : array('tostatus' => '0'); //для того что бы указать что сообщения прочитаны

   //$result[999] = $newpm;

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

   if($dialogsql['id'] == $supportchat) {
      $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($to == 0) {
       $opptags['DS_ROW_USER_NICKNAME'] = $cfg['ds']['supportinfo']['name'];
       $opptags['DS_ROW_USER_AVATAR_SRC'] = $cfg['ds']['supportinfo']['avatar'];
       $opptags['DS_ROW_USER_ONLINE'] = $supportonline;
     } else {
       $usrtags['DS_ROW_USER_NICKNAME'] = $cfg['ds']['supportinfo']['name'];
       $usrtags['DS_ROW_USER_AVATAR_SRC'] = $cfg['ds']['supportinfo']['avatar'];
       $usrtags['DS_ROW_USER_ONLINE'] = $supportonline;
     }
   }

   $t = new XTemplate(cot_tplfile(array('ds', 'newmsg')));
   
  if ($a == 'send')      //если это отправка сообщения
  {
    $message_type = cot_import('message_type', 'P', 'TXT');
    $mavatars_count = array();
    $mtype = 0;
    $mdata = array();

    /* === Hook === */
  	foreach (cot_getextplugins('ds.ajax.send.first') as $pl)
  	{
  		include $pl;
  	}
   	/* ===== */
    
    $resend_join = cot_import('resend', 'P', 'TXT');
    $resend = array();

    $newpmtext = cot_import('message_body', 'P', 'TXT');

    if(!empty($resend_join)) {
      $resend_join = explode(',', $resend_join);
      foreach($resend_join as $rsnd) {
        if($rsnd > 0) $resend[] = $rsnd;
      }
      $resend_join = $resend;
      $resend = array();

      if(count($resend_join) > 0) {
        $resend_msg = $db->query("SELECT m.id as mid FROM $db_ds_msg as m LEFT JOIN $db_ds_dialog as d ON m.dialog=d.id
            WHERE (d.fromid=".$usr['id']." OR d.toid=".$usr['id'].") AND (m.id=".implode(' OR m.id=', $resend_join).")")->fetchAll(PDO::FETCH_COLUMN);
        foreach($resend_msg as $rmid) {
          if($rmid > 0) $resend[] = $rmid;
        }
      }
    }

    if($dialogsql['id'] == $supportchat && in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {
      $rmodertheme = cot_import('rmodertheme', 'P', 'TXT');
      if(!empty($rmodertheme)) {
        $newpmtext = '<b>'.$rmodertheme.'</b> <br>'.$newpmtext;
      }
    }
          
    if (count($mavatars_count) > 0 && mb_strlen($newpmtext) < 1 && count($resend) == 0)
    {
      $newpmtext = $L['ds_upload'];
    }

    if($dialogsql['id'] != $supportchat && (($usr['ban']['banned'] && $usr['ban']['block']['ds']) || $usr['dsblock'])) {
		   $t->assign(array('ERROR_MSG' => 'Личные сообщения заблокированы'));
		   $t->parse('MAIN.ERROR');
    }
    elseif ($mtype == 0 && mb_strlen($newpmtext) < 1 && count($mavatars_count) == 0 && count($resend) == 0)
    {
		   $t->assign(array('ERROR_MSG' => $L['ds_shortmsg']));
		   $t->parse('MAIN.ERROR');
	  }
    else
    {
      /* === Hook === */
    	foreach (cot_getextplugins('ds.ajax.send.presend') as $pl)
    	{
    		include $pl;
    	}
     	/* ===== */

      $pm['resend'] = json_encode($resend);

      $pm['mtype'] = $mtype;
      $pm['mdata'] = json_encode($mdata);

      $pm['dialog'] = (int)$chatid;
      $pm['date'] = (int)$sys['now'];
		  $pm['text'] = nl2br($newpmtext); 
      $pm['fruser'] = $usr['id'];
      $pm['touser'] = $to;

      if($dialogsql['id'] == $supportchat && in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {
        $rmodername = cot_import('rmodername', 'P', 'TXT');
        $rmodernameshide = cot_import('rmodernameshide', 'P', 'INT');
        $rmoderfromauto = cot_import('rmoderfromauto', 'P', 'INT');

        if($usr['maingrp'] != 5) $rmodername = $usr['profile']['user_MODERNAME'];

        $pm['fruser'] = (($rmoderfromauto == 1 && $usr['maingrp'] == 5) ? 0 : $usr['id']);
        $pm['modername'] = (($pm['fruser'] == 0 || ($rmodernameshide == 1 && $usr['maingrp'] == 5)) ? '' : $rmodername);

        if($to == 0) {
          $opptags['DS_ROW_USER_NICKNAME'] = (!empty($pm['modername']) ? $pm['modername'] : $cfg['ds']['supportinfo'][($pm['fruser'] > 0 ? 'name' : 'nameauto')]);
        } else {
          $usrtags['DS_ROW_USER_NICKNAME'] = (!empty($pm['modername']) ? $pm['modername'] : $cfg['ds']['supportinfo'][($pm['fruser'] > 0 ? 'name' : 'nameauto')]);
        }
      }

      $pmsql = $db->insert($db_ds_msg, $pm);
      $pm['id'] = $db->lastInsertId();

      $dstate = cot_ds_dstate(0, $dialogsql, $pm['id'], $usr['id']);

      $tonewpm['lastmsg'] = (int)$sys['now'];
      $pmsql = $db->update($db_ds_dialog, $tonewpm, "id = ".(int)$chatid."");   //устанавливаем статус нового сообщения для собеседника
        
  		 /* === Hook === */
  		 foreach (cot_getextplugins('ds.ajax.send.done') as $pl)
  		 {
  		 	include $pl;
  		 }
       /* === Hook === */
      
      $mdata = cot_ds_get_mdata($pm['mtype'], $pm['mdata']);

      if($pm['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.OUTBOX.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.OUTBOX.DS_TYPE3_GEXTRAS');
        }
      }

      $t->assign($usrtags);
		  $t->assign(array(
       'DS_ROW_ID' => $pm['id'],
			 'DS_ROW_DATE' => cot_date('H:i', $pm['date']),
			 'DS_ROW_DATE_STAMP' => $pm['date'],
			 'DS_ROW_TEXT' => $pm['text'],
       'DS_ROW_RESEND' => cot_ds_resend_msg($pm['resend']),
       'DS_ROW_MTYPE' => $pm['mtype'],
       'DS_ROW_MDATA' => $mdata,
		  ));
    
     $t->parse('MAIN.OUTBOX');
   }

 }else{$t->assign(array('ERROR_MSG' => $L['msg950_body'],));$t->parse('MAIN.ERROR');}              //парсим ошибку если она есть
 }else{$t->assign(array('ERROR_MSG' => $L['msg401_title'],));$t->parse('MAIN.ERROR');}
}

$t->parse('MAIN');
$result[1] = $t->text("MAIN");

if ($a == 'send')
{
 echo $result[1];
}
else
{
 $result[1] = htmlspecialchars($result[1]);
 echo json_encode($result);
}
exit;