<?php
/**
 * [BEGIN_COT_EXT]
 * Hooks=api.track_stack.main
 * [END_COT_EXT]
 */

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

$IS_ACTIVE_DIALOG = cot_import('IS_ACTIVE_DIALOG', 'G', 'INT');
$IS_ACTIVE_DIALOG_CHECKMSG = cot_import('IS_ACTIVE_DIALOG_CHECKMSG', 'G', 'TXT');

require_once cot_incfile('ds', 'module');
global $cot_groups;

$return['push']['message'] = array(
  'notify' => array(),
  'msgs' => array(),
  'chk_msg' => array(),
  'dialogs' => array()
);

$supportchat = 0;
if(!in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) $supportchat = cot_create_chat($usr['id'], 0);

$moderWmoder = in_array($usr['maingrp'], $cfg['moder_group_ids']);
$IS_DIALOG = array();

$newdsmsg = $db->query("SELECT * FROM $db_ds_msg WHERE (touser=".$usr['id'].(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups']) ? ' OR touser=0' : '').') AND status=1 ORDER BY date DESC')->fetchAll();

$dialogs = array();

if($IS_ACTIVE_DIALOG > 0) {

  $IS_DIALOG = $db->query("SELECT * FROM $db_ds_dialog WHERE id=".$IS_ACTIVE_DIALOG." AND (toid='".$usr['id']."' OR fromid='".$usr['id']."'".(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups']) ? ' OR toid=0 OR fromid=0' : '').") LIMIT 1")->fetch();

  if($IS_DIALOG['id'] > 0) {
    $dialogs[$IS_DIALOG['id']] = $IS_DIALOG;

    $t = new XTemplate(cot_tplfile(array('ds', 'newmsg')));

    $fromid = $usr['id'];

    $issupportchat = (($IS_DIALOG['toid'] == 0 || $IS_DIALOG['fromid'] == 0) ? true : false);
    if($issupportchat) {
      if(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) $fromid = 0;
    }

    $opponent = ($IS_DIALOG['fromid'] == $fromid) ? $IS_DIALOG['toid'] : $IS_DIALOG['fromid'];

    $opparr = ($opponent > 0 ? $db->query("SELECT * FROM $db_users WHERE user_id = $opponent LIMIT 1")->fetch() : array('user_id' => 0));
    if(!$issupportchat && $moderWmoder) $moderWmoder = in_array($opparr['user_maingrp'], $cfg['moder_group_ids']);

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

    if($opponent == 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;
    }

    $t->assign($opptags);

    $chkids = array();
    if(!empty($IS_ACTIVE_DIALOG_CHECKMSG)) foreach(explode(',', $IS_ACTIVE_DIALOG_CHECKMSG) as $chkid) {
      if($chkid > 0) $chkids[] = $chkid;
    }
    if(count($chkids) > 0) {
      $chkids = $db->query("SELECT id FROM $db_ds_msg WHERE dialog=".$IS_ACTIVE_DIALOG.' AND (id='.implode(' OR id=', $chkids).') AND status=0')->fetchAll(PDO::FETCH_COLUMN);
      foreach($chkids as $chkid) {
        $return['push']['message']['chk_msg'][] = $chkid;
      }
    }
  } else {
    $IS_ACTIVE_DIALOG = 0;
  }
}

$extpl1 = cot_getextplugins('ds.api_track_stack.hist.loop');

$notygroup = array(
  'notify' => array(),
  'message' => array()
);

$newlastdate = 0;

foreach($newdsmsg as $nmsg) {
  $dialog = array();

  if(is_array($dialogs[$nmsg['dialog']])) {
    $dialog = $dialogs[$nmsg['dialog']];
  } else {
    $dialog = $db->query("SELECT * FROM $db_ds_dialog WHERE id=".$nmsg['dialog']." AND (toid='".$usr['id']."' OR fromid='".$usr['id']."'".(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups']) ? ' OR toid=0 OR fromid=0' : '').") LIMIT 1")->fetch();

    if($dialog['id'] > 0) {
      $dialogs[$dialog['id']] = $dialog;
    }
  }

  if($nmsg['date'] > $newlastdate) $newlastdate = $nmsg['date'];

  if($dialog['id'] > 0) {
    if($IS_ACTIVE_DIALOG > 0 && $IS_ACTIVE_DIALOG == $dialog['id']) {
      if($lastdate > 0 && $nmsg['date'] > $lastdate) {
        $return['push']['cntnew']['message']++;

        $mdata = cot_ds_get_mdata($nmsg['mtype'], $nmsg['mdata']);

        $pretext = '';
        if($nmsg['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($nmsg['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']));
        }

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

        $t->assign(array(
      	 'DS_ROW_ID' => $nmsg['id'],
         'DS_ROW_MODER_GROUP' => (($nmsg['touser'] == $usr['id'] && $moderWmoder) ? '['.$cot_groups[$opparr['user_maingrp']]['title'].']' : ''),
      	 'DS_ROW_DATE' => cot_date('H:i', $nmsg['date']),
      	 'DS_ROW_DATE_STAMP' => $nmsg['date'],
      	 'DS_ROW_TEXT' => $nmsg['text'],
      	 'DS_ROW_STATUS' => $nmsg['status'],
      	 'DS_ROW_RESEND' => cot_ds_resend_msg($nmsg['resend']),
         'DS_ROW_TOUSER' => ($nmsg['touser'] > 0 ? $nmsg['touser'] : $usr['id']),
         'DS_ROW_FRUSER' => $nmsg['fruser'],
         'DS_ROW_ISSOPPORTCHAT' => ($supportchat == $nmsg['dialog'] ? 1 : 0),
         'DS_ROW_MTYPE' => $nmsg['mtype'],
         'DS_ROW_MDATA' => $mdata,
         'DS_ROW_PRETEXT' => $pretext,
      	));

        if($opponent == 0) {
          $t->assign('DS_ROW_USER_NICKNAME', (!empty($nmsg['modername']) ? $nmsg['modername'] : $cfg['ds']['supportinfo'][($nmsg['fruser'] > 0 ? 'name' : 'nameauto')]));
        }

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

      	$t->parse('MAIN.INBOX');

        $return['push']['message']['msgs'][] = cot_html_removelines($t->text('MAIN.INBOX'));
      }
    } else {
      $notygroup['message'][$dialog['id']][] = array(
        'date' => $nmsg['date'],
        'nmsg' => $nmsg,
        'dialog' => $dialog
      );

      $return['push']['cnt']['message']++;
    }
  }
}

$t1 = new XTemplate(cot_tplfile(array('ds', 'list')));

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

foreach($notygroup['message'] as $tcode => $_arr) {
  $_arr_data['issupport'] = 0;
  $_arr_data['cnt'] = count($_arr);
  $_arr_data['dialog'] = $_arr[0]['dialog'];
  $_arr_data['dialog_url'] = cot_url('ds', 'm=dialog&id='.$tcode);
  $_arr_data['opponent'] = ($_arr_data['dialog']['fromid'] == $usr['id']) ? $_arr_data['dialog']['toid'] : $_arr_data['dialog']['fromid'];
  if($_arr_data['opponent'] > 0) {
    $_arr_data['fromuser_data'] = $db->query("SELECT user_name, user_avatar FROM $db_users WHERE user_id=".$_arr_data['opponent'])->fetch();
    if(($_arr_data['dialog']['toid'] == 0 || $_arr_data['dialog']['fromid'] == 0) && in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {
      $_arr_data['dialog_url'] = cot_url('ds', 'm=dialog&al=support&id='.$_arr_data['opponent']);
      $_arr_data['fromuser_data']['user_avatar'] = $cfg['ds']['supportinfo']['avatar'];
    }
    $_arr_data['fromuser_data']['online'] = (cot_plugin_active('whosonline') ? cot_userisonline($_arr_data['opponent']) : 1);
  } else {
    $_arr_data['issupport'] = 1;
    $_arr_data['dialog_url'] = cot_url('ds', 'm=dialog&al=support');
    $_arr_data['fromuser_data'] = array(
      'user_name' => $cfg['ds']['supportinfo']['name'],
      'user_avatar' => $cfg['ds']['supportinfo']['avatar']
    );

    $_arr_data['fromuser_data']['online'] = 1;
    if(cot_plugin_active('whosonline')) {
      $_arr_data['fromuser_data']['online'] = 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'])) {
          $_arr_data['fromuser_data']['online'] = 1;
          break;
        }
      }
    }
  }

  $cntmsgs = $_arr_data['cnt'];
  $istype = array();

  foreach($_arr as $m_arr) {
    if(!in_array($m_arr['nmsg']['mtype'], array(0, 4))) {
      if(!in_array($m_arr['nmsg']['mtype'], $istype)) {
        $pretext = $cfg['ds']['mtypes_notytitle'][$m_arr['nmsg']['mtype']];
        if($m_arr['nmsg']['mtype'] == 5) {
          $pretext = 'Сообщение по '.cot_sitename('padeg', 'd');
        } elseif($m_arr['nmsg']['mtype'] == 6) {
          $pretext = 'Сообщение по предложению';
        }

        $return['push']['message']['notify'][] = cot_html_removelines('<a class="inbox-message-link nowrap lined" href="'.$_arr_data['dialog_url'].'">
                                                <span class="userimage">
                                                    <img src="'.(!empty($_arr_data['fromuser_data']['user_avatar']) ? $_arr_data['fromuser_data']['user_avatar'] : 'themes/itbirja/files/avatar/medium/noprofilepicture.gif').'" class="rounded" alt="'.$_arr_data['fromuser_data']['user_name'].'" height="28" width="28">
                                                </span>
                                                <span class="inbox-message-user-name">'.$_arr_data['fromuser_data']['user_name'].' - '.$pretext.'</span>
                                            </a>');
      } else {
        //фиксим правильное кол-во уведомлений по сообщениям, т.к похожие не парсим
        $return['push']['cnt']['message']--;
      }
      $cntmsgs--;
    }
  }

  if($cntmsgs > 0) {
    $return['push']['message']['notify'][] = cot_html_removelines('<a class="inbox-message-link nowrap lined" href="'.$_arr_data['dialog_url'].'">
                                                <span class="userimage">
                                                    <img src="'.(!empty($_arr_data['fromuser_data']['user_avatar']) ? $_arr_data['fromuser_data']['user_avatar'] : 'themes/itbirja/files/avatar/medium/noprofilepicture.gif').'" class="rounded" alt="'.$_arr_data['fromuser_data']['user_name'].'" height="28" width="28">
                                                </span>
                                                <span class="inbox-message-user-name">'.$_arr_data['fromuser_data']['user_name'].' - '.cot_declension($_arr_data['cnt'], 'новое сообещние,новых сообщения,новых сообщений').'</span>
                                            </a>');
  }

  $issopportchat = false;
  $fromuser = $usr['id'];
  if(($_arr[0]['dialog']['toid'] == 0 || $_arr[0]['dialog']['fromid'] == 0) && in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {
    $issopportchat = true;
    $fromuser = 0;
  }

  $act_f = ($_arr[0]['dialog']['fromid'] == $fromuser) ? 'act_fid' : 'act_tid';
  $msgfilter = "(dialog = '".$_arr[0]['dialog']['id']."' AND $act_f!=0)";

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

  if($_arr[0]['nmsg']['text'][0] == '<' && $_arr[0]['nmsg']['text'][1] == 'b' && $_arr[0]['nmsg']['text'][2] == '>')
    $_arr[0]['nmsg']['text'] = preg_replace('/^(<b>(.*)<\/b>)(.*)/i', '$3', $_arr[0]['nmsg']['text']);

  $_arr[0]['nmsg']['text'] = explode('<br>', $_arr[0]['nmsg']['text']);
  $_arr[0]['nmsg']['text'][0] = trim($_arr[0]['nmsg']['text'][0]);
  $_arr[0]['nmsg']['text'] = (!empty($_arr[0]['nmsg']['text'][0]) ? $_arr[0]['nmsg']['text'][0] : $_arr[0]['nmsg']['text'][1]);

  $_arr[0]['nmsg']['text'] = strip_tags($_arr[0]['nmsg']['text']);

  if(empty($_arr[0]['nmsg']['text'])) {
    $_arr[0]['nmsg']['resend_arr'] = (!empty($_arr[0]['nmsg']['resend']) ? json_decode($_arr[0]['nmsg']['resend'],1) : array());
    if(count($_arr[0]['nmsg']['resend_arr']) > 0) {
      $_arr[0]['nmsg']['text'] = 'Пересылаемое сообщение';
    }
  }

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

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

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

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

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

  $mdata = cot_ds_get_mdata($_arr[0]['nmsg']['mtype'], $_arr[0]['nmsg']['mdata']);

  $pretext = $_arr[0]['nmsg']['text'];
  if($_arr[0]['nmsg']['mtype'] == 0) {
    $pretext = cot_string_truncate($pretext, 65, true, false, "...");
  } else {
    if($_arr[0]['nmsg']['mtype'] == 5) {
      $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][5], $mdata);
      $pretext = cot_string_truncate($pretext, 65, true, false, "...");
    } elseif($_arr[0]['nmsg']['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'][$_arr[0]['nmsg']['mtype']];
    }
  }

  $dstate_update = array();
  $dstate_needupdate = false;

  $waitfastanswer = 0;
  $dstate = cot_ds_dstate(0, $_arr[0]['dialog']);
  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;
    }
  }

  $t1->assign(array(
    'DS_DIALOG_ID' => $_arr[0]['dialog']['id'],
    'DS_TIME_AGO' => ($_arr[0]['nmsg']['date'] > 0 ? (cot_date('d.m.Y', $_arr[0]['nmsg']['date']) == cot_date('d.m.Y', $sys['now']) ? (($_arr[0]['nmsg']['date'] > ($sys['now'] - 3600)) ? cot_build_timeago($_arr[0]['nmsg']['date']) : 'сегодня в '.cot_date('H:i', $_arr[0]['nmsg']['date'])) : (cot_date('d.m.Y', $_arr[0]['nmsg']['date']) == cot_date('d.m.Y', $sys['now']-86400) ? 'вчера в '.cot_date('H:i', $_arr[0]['nmsg']['date']) : cot_date('d.m.y, H:i', $_arr[0]['nmsg']['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' => (($_arr[0]['nmsg']['touser'] != $fromuser && !$_arr[0]['nmsg']['status']) ? 0 : 1),  //прочитано или нет
  	'DS_TEXT' => $pretext,   //сокрашенный текст где 65 это колл-во символов после чего сокращяем
    'DS_OPPONENT' => $opponent,
    'DS_ISSOPPORTCHAT' => ($issopportchat ? 1 : 0),
    'DS_NEW_OF_LAST20DAY_MSG' => $waitfastanswer,
  ));

  $t1->parse('MAIN.DS_ROW');

  $return['push']['message']['dialogs'][] = array(
    'forsupportpage' => ((in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups']) && $issopportchat) ? 1 : 0),
    'dialog' => $_arr[0]['nmsg']['dialog'],
    'html' => $t1->text('MAIN.DS_ROW')
  );
}

//if($return['push']['cntnew']['message'] > 0) {
  //$return['push']['message']['msgs'] = array_reverse($return['push']['message']['msgs']);
//}
//if($return['push']['cntnew']['dialogs'] > 0) {
//  $return['push']['message']['dialogs'] = array_reverse($return['push']['message']['dialogs']);
//}

if($t) unset($t);

if($newlastdate > $return['lastdate']) $return['lastdate'] = $newlastdate;

?>