<?php

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

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

if(COT_AJAX) {
  $return = array(
    'status' => 'error',
    'redirect' => '',
    'response' => 'Произошла ошибка при отправке сообщения'
  );

  list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('ds', 'a');
  if($usr['auth_write']) {

    $id = cot_import('to', 'P', 'INT');

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

    $sendsucces = false;
    $chatid = 0;

    if (!empty($id))
    {
      if ($id != $usr['id'])
      {
        $touser = $db->query("SELECT * FROM $db_users WHERE user_id = $id LIMIT 1");
        if ($touser->rowCount()!=0)
        {
          $touser = $touser->fetch();
          $chatid = cot_chat_id((int)$usr['id'], $id);

          if(empty($chatid) || $chatid == 0) $chatid = cot_create_chat((int)$usr['id'], $id);
        }
      }
    }

    if ($chatid > 0)
    {
    	$newpmtext = cot_import('message_body', 'P', 'TXT');

      $submg = cot_import('submg', 'P', 'INT');

      $mtype = 0;
      $mdata = '';

      if($submg != 1) {
        $mtype = 1;
        $mdata = array(
          'budget' => cot_import('budget', 'P', 'NUM'),
          'prd_duration' => cot_import('prd_duration', 'P', 'INT'),
        );
        $mdata = json_encode($mdata);
      }

      if($usr['ban']['banned'] && $usr['ban']['block']['ds']) {
  		  $return['response'] = 'Личные сообщения заблокированы';
        $chatid = 0;
      }

    	if (mb_strlen($newpmtext) < 2)
    	{
        $return['response'] = 'Слижком короткое сообщение';
        $chatid = 0;
    	}

      $needfastanswer = 0;

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

      if(!$needfastanswer && in_array($mtype, array(1, 5))) $needfastanswer = 1;

      if ($chatid > 0)
    	{
    	 	$pm['dialog'] = (int)$chatid;

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

        $pm['mtype'] = $mtype;
        $pm['mdata'] = $mdata;

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

        $fornewpm = $db->query("SELECT * FROM $db_ds_dialog WHERE id = $chatid LIMIT 1")->fetch();
        $state = ($fornewpm['fromid'] == $usr['id']) ? array('tostatus' => '1') : array('fromstatus' => '1');
        $state['lastmsg'] = (int)$sys['now'];

        if($needfastanswer) {
          $dstate = cot_ds_dstate($chatid);
          $dstate['waitanswer24hour'][] = array(
            'mid' => $pm['id'],
            'uid' => $usr['id'],
            'date' => $sys['now'],
            'lowrtg' => 0
          );
          $state['dstate'] = json_encode($dstate);
        } else {
          $dstate = cot_ds_dstate($chatid, array(), $pm['id'], $usr['id']);
        }
        $pmsql = $db->update($db_ds_dialog, $state, "id = ".(int)$chatid."");

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

        $return['status'] = 'success';
        $return['redirect'] = cot_url('ds', 'm=dialog&id='.$pm['dialog']);
    	}
    }
  }

  echo json_encode($return);
} else {
  $to = cot_import('to', 'G', 'INT');
  $a = cot_import('a','G','TXT');

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

  if (!empty($to))
  {
    if ($to != $usr['id'])
    {
     $touser = $db->query("SELECT * FROM $db_users WHERE user_id = $to LIMIT 1");
     if ($touser->rowCount()!=0)
     {
      $touser = $touser->fetch();
      $chatid = cot_chat_id((int)$usr['id'],$to);

      if(COT_AJAX)
      {
        if(!$chatid)
        {
          $chatid = cot_create_chat((int)$usr['id'],$to);
        }
        //cot_redirect(cot_url('ds', 'm=dialog&chat='.$chatid, '', true));
      }
     }
     else
     {
      cot_die();
     }
    }
    else
    {
     cot_redirect(cot_url('ds'));
    }
  }

  $title_params = array(
  	'DS' => $L['Private_Messages'],
  	'SEND_NEW' => $L['ds_sendnew']
  );
  $out['subtitle'] = cot_title('{SEND_NEW} - {DS}', $title_params);
  $out['head'] .= $R['code_noindex'];

  $pretext = '';
  $sendurl = cot_url('ds', 'm=send&a=send&to='.$to);

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

  require_once $cfg['system_dir'] . '/header.php';
  $t = new XTemplate(cot_tplfile(array('ds', 'send')));

  cot_display_messages($t);

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

  $t->assign(array(
  	'DSSEND_TITLE' => cot_breadcrumbs($title, $cfg['homebreadcrumb']),
  	'DSSEND_FORM_SEND' => $sendurl,
  	'DSSEND_FORM_TEXT' => cot_textarea('newpmtext', $newpmtext, 8, 56, '', 'input_textarea_editor') . $text_editor_code,
    'DSSEND_FORM_PRETEXT' => $pretext,
  ));

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

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

  $t->parse('MAIN');
  $t->out('MAIN');

  require_once $cfg['system_dir'] . '/footer.php';
}