<?php
/**
 * DS function.
 * @version 2.2
 * @package DS
 * @copyright (c) Alexeev Vlad (http://cmsworks.ru/users/alexvlad)
 */

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

// Requirements
require_once cot_langfile('ds', 'module');

cot::$db->registerTable('ds_msg');
cot::$db->registerTable('ds_dialog');
cot::$db->registerTable('ds_score');
$db_ds_files = (isset($db_ds_files)) ? $db_ds_files : $db_x . 'ds_files';
cot::$cfg['ds']['turnajax'] = cot::$cfg['ds']['turnajax'] && cot::$cfg['jquery'] && cot::$cfg['turnajax'];

/**
 * mtypes
 * 0 - обычное
 * 1 - сообщение с индивидуальным заказом из профиля (от заказчика)
 * 2 - сообщение с индивидуальной услугой из диалога
 * 3 - предложена услуга из диалога
 * 4 - заказ по индивид. услуга создана
 * 5 - сообщение со страницы услуги
 */

$cfg['ds']['mtypes_notytitle'] = array(
  1 => 'Индивидуальное предложение',
  2 => cot_sitename('padeg_individ', 'i', 'fcharup'),
  3 => cot_sitename('declension', 'predlogen', 'declension', 1, true),
  4 => 'Заказ создан',
  5 => 'Добрый день. Тема: '.cot_sitename('padeg', 'i').' "{$item_title}".',
  6 => 'Добрый день. Тема: предложение по запросу "{$item_title}".'
);

$cfg['ds']['waitanswer24hour_time'] = array(
  'title' => array(
    'i' => '24 часа',
    'r' => '24 часов',
  ),
  'time' => 86400 //время на быстрый ответ
);

$ds_allow_filepath = 'datas/ds';

$cfg['ds']['supportinfo'] = array(
  'modergroups' => array(5, 8),
  'pagetitle' => 'Диалог со службой поддержки',
  'name' => 'Служба поддержки',
  'nameauto' => 'Автоуведомление',
  'placeholder' => 'Мы готовы ответить на все ваши вопросы',
  'avatar' => 'datas/defaultav/support.jpg'
);

function cot_ds_dstate($chatid = 0, $dialog = array(), $newmsg = 0, $senderuid = 0) {
  global $sys, $cfg, $db, $db_ds_dialog, $db_ds_msg;

  $dstate = array();
  if($chatid > 0) {
    $dialog = $db->query("SELECT * FROM $db_ds_dialog WHERE id=".$chatid." LIMIT 1")->fetch();
  }
  $dstate = (!empty($dialog['dstate']) ? json_decode($dialog['dstate'], 1) : array());
  if(!is_array($dstate)) $dstate = array();

  if($dialog['id'] > 0 && $newmsg) {
    $dstate_needupdate = 0;
    $dialog_update = array();
    $dstate_update = array();

    cot_log('cot_ds_dstate 1='.$senderuid);

    if($senderuid > 0) {
      cot_log('cot_ds_dstate dialog='.print_r($dialog,1));
      cot_log('cot_ds_dstate 2='.$dialog['fromid'] .' & '.$dialog['toid']);

      if($dialog['fromid'] > 0 && $dialog['toid'] > 0) {
        if(is_array($dstate['waitanswer24hour'])) foreach($dstate['waitanswer24hour'] as $mfastansw) {
          cot_log('cot_ds_dstate 4='.print_r($mfastansw,1));

          if(!$mfastansw['lowrtg'] && $mfastansw['uid'] != $senderuid) {
            if($mfastansw['date'] > ($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time'])) {
              cot_log('cot_ds_dstate 5 unset!');
              $dstate_needupdate = 1;
            } else {
              $dstate_update[] = $mfastansw;
            }
          } else {
            $dstate_update[] = $mfastansw;
          }
        }

        $prelastmsg = $db->query("SELECT * FROM $db_ds_msg WHERE dialog=".$dialog['id']." AND id!=".$newmsg." ORDER BY date DESC LIMIT 1")->fetch();
        if(!$prelastmsg['id'] || ($prelastmsg['date'] > 0 && ($prelastmsg['date'] < ($sys['now'] - 86400*20)))) {
          $dstate_update[] =  array(
            'mid' => $newmsg,
            'uid' => $senderuid,
            'date' => $sys['now'],
            'lowrtg' => 0
          );
          $dstate_needupdate = 1;
        }
      } elseif(is_array($dstate['waitanswer24hour']) && count($dstate['waitanswer24hour']) > 0) {
        $dstate['waitanswer24hour'] = array();
        $dstate_needupdate = 1;
      }
      if($dstate_needupdate) {
        $dstate['waitanswer24hour'] = $dstate_update;
        $dialog_update['dstate'] = json_encode($dstate);

        $db->update($db_ds_dialog, $dialog_update, "id=".(int)$dialog['id']);
      }
    }
  }
  return (is_array($dstate) ? $dstate : array());
}

function cot_chat_id($fromuserid=0, $touserid=0)
{
	global $db, $db_ds_dialog;
	$sql = $db->query("SELECT * FROM $db_ds_dialog WHERE (fromid =$fromuserid AND toid =$touserid) OR (fromid =$touserid AND toid =$fromuserid) LIMIT 1")->fetch();
	return ($sql['id'] > 0 ? $sql['id'] : 0);
}

function cot_create_chat($fromuserid=0,$touserid=0)
{
	global $db, $db_ds_dialog;
  $result = cot_chat_id($fromuserid, $touserid);
  if(!$result) {
    $create_chat = array();
    $create_chat['lastmsg'] = (int)$sys['now'];
    $create_chat['fromid'] = $fromuserid;
  	$create_chat['toid'] = $touserid;
    if (!empty($fromuserid) || !empty($fromuserid))
    {
    	$chatsql = $db->insert($db_ds_dialog, $create_chat);
    	$result = $db->lastInsertId();
    }
  }
	return $result;
}

function cot_ds_get_mdata($mtype = 0, $mtmpdata = '') {
  $mdata = array();
  if($mtype != 0 && !empty($mtmpdata)) {
    $mdata = json_decode($mtmpdata, 1);
    if(!is_array($mdata)) {
      $mdata = array();
    } else {
      if($mtype == 1) {
        if(empty($mdata['budget'])) $mdata['budget'] = '';
        $mdata['prd_duration'] = (!empty($mdata['prd_duration']) ? cot_declension($mdata['prd_duration'], 'день,дня,дней') : '');
      } elseif($mtype == 2) {

      } elseif($mtype == 3) {

      } elseif($mtype == 4) {
        if(empty($mdata['order_id'])) $mdata['order_id'] = '';
      }
    }
  }
  return $mdata;
}

function cot_ds_resend_msg($msgids = '') {
  global $db, $db_users, $db_ds_dialog,  $db_ds_msg, $cfg;
  $return = '';

  if(!empty($msgids)) {
    $msgids = json_decode($msgids,1);
    if(count($msgids) > 0) {
      $msgsql = $db->query("SELECT *, m.id as mid, d.id as did FROM $db_ds_msg as m LEFT JOIN $db_ds_dialog as d ON m.dialog=d.id
        WHERE (m.id=".implode(' OR m.id=', $msgids).")")->fetchAll();

      if(count($msgsql) > 0) {
        $t = new XTemplate(cot_tplfile(array('ds', 'newmsg')));

        foreach($msgsql as $resend_msg) {
          $mdata = cot_ds_get_mdata($resend_msg['mtype'], $resend_msg['mdata']);

          $t->assign(array(
      			'DS_RESEND_ID' => $resend_msg['mid'],
            'DS_RESEND_TEXT' => $resend_msg['text'],
            'DS_RESEND_RESEND' => cot_ds_resend_msg($resend_msg['resend']),
      			'DS_RESEND_DATE' => cot_date('d M, H:i', $resend_msg['date']),
            'DS_ROW_MTYPE' => $resend_msg['mtype'],
            'DS_ROW_MDATA' => $mdata,
      		));

      		/* === Hook - Part2 : Include === */
      		foreach (cot_getextplugins('ds.history.resend') as $pl)
      		{
      			include $pl;
      		}
      		/* ===== */

          $fromusr = ($resend_msg['fromid'] == $resend_msg['touser'] ? $resend_msg['toid'] : $resend_msg['fromid']);
          $t->assign(cot_generate_usertags($fromusr, 'DS_RESEND_USER_'));

          if(($resend_msg['fromid'] == 0 || $resend_msg['toid'] == 0) && $fromusr == 0) {
            $t->assign(array(
              'DS_RESEND_USER_NICKNAME' => (!empty($resend_msg['modername']) ? $resend_msg['modername'] : $cfg['ds']['supportinfo'][($resend_msg['fruser'] > 0 ? 'name' : 'nameauto')]),
              'DS_RESEND_USER_AVATAR_SRC' => $cfg['ds']['supportinfo']['avatar']
            ));
          }

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

        $t->parse('MAIN');
        $return = $t->text('MAIN');
      }
    }
  }

  return $return;
}