<?php

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

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

cot_sendheaders();

$rmodertotype = cot_import('rmodertotype', 'P', 'TXT');

$rmodertouser = cot_import('rmodertouser', 'P', 'ARR');
$rmodertogroup = cot_import('rmodertogroup', 'P', 'ARR');

$rmodername = cot_import('rmodername', 'P', 'TXT');
$rmodertheme = cot_import('rmodertheme', 'P', 'TXT');
$rmodertext = cot_import('rmodertext', 'P', 'TXT');

$rmodernameshide = cot_import('rmodernameshide', 'P', 'INT');
$rmoderfromauto = cot_import('rmoderfromauto', 'P', 'INT');

if(in_array($usr['maingrp'], $cfg['ds']['supportinfo']['modergroups'])) {

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

  $pm = array(
    'dialog' => 0,
    'fruser' => (($rmoderfromauto == 1 && $usr['maingrp'] == 5) ? 0 : $usr['id']),
    'date' => (int)$sys['now'],
	  'text' => $rmodertext,
    'touser' => 0,
    'modername' => (($rmodernameshide == 1 && $usr['maingrp'] == 5) ? '' : $rmodername)
  );

  if($pm['fruser'] == 0) $pm['modername'] = '';

  if(!empty($rmodertheme)) {
    $pm['text'] = '<b>'.$rmodertheme.'</b> <br>'.$pm['text'];
  }

  if($rmodertotype == 'tousers' && count($rmodertouser) > 0) {
    foreach($rmodertouser as $urrid) {
      if($urrid > 0 && $db->query("SELECT COUNT(*) FROM $db_users WHERE user_id=".$urrid.' LIMIT 1')->fetchColumn() > 0) {
        $sendusers[] = $urrid;
      }
    }
  } elseif($rmodertotype == 'togroup' && count($rmodertogroup) > 0) {
    $sendgroups = array();
    foreach($rmodertogroup as $grp) {
      if($grp > 0) $sendgroups[] = $grp;
    }
    if(count($sendgroups) > 0) {
      $sendusers = $db->query("SELECT user_id FROM $db_users WHERE user_maingrp=".implode(' OR user_maingrp=', $sendgroups))->fetchAll(PDO::FETCH_COLUMN);
    }
  } elseif($rmodertotype == 'tonew') {
    $senduserstmp = $db->query("SELECT user_id FROM $db_users WHERE user_maingrp>3")->fetchAll(PDO::FETCH_COLUMN);
    foreach($senduserstmp as $urrid) {
      if(!cot_chat_id($urrid, 0)) $sendusers[] = $urrid;
    }
  }

  $dialogs = array();
  if(count($sendusers) > 0) {
    foreach($sendusers as $urrid) {
      $supportchat = cot_create_chat($urrid, 0);
      if($supportchat > 0) {
        $dialogs[$supportchat] = $urrid;
      }
    }
  }

  if(count($dialogs) > 0) {
    foreach($dialogs as $dialid => $urrid) {
      $pm['dialog'] = $dialid;
      $pm['touser'] = $urrid;
      $db->insert($db_ds_msg, $pm);

      $fornewpm = $db->query("SELECT * FROM $db_ds_dialog WHERE id = $dialid LIMIT 1")->fetch();
      $state = ($fornewpm['toid'] > 0) ? array('tostatus' => '1') : array('fromstatus' => '1');
      $state['lastmsg'] = (int)$sys['now'];
      $db->update($db_ds_dialog, $state, "id = ".(int)$dialid."");
    }
  }
}

cot_redirect(cot_url('ds', 'support=1'));