<?php
/* ====================
[BEGIN_COT_EXT]
Hooks=ajax
[END_COT_EXT]
==================== */

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

require_once cot_incfile('market', 'module');
require_once cot_incfile('marketorders', 'plug');

cot_block($usr['id']);
$is_admin = false;
if(($usr['maingrp'] == 5 || $usr['maingrp'] == 9) && cot_import('is_admin_get','P','INT')) {
  $is_admin = true;
}

$a = cot_import('a','G','ALP');
$id = cot_import('id','G','INT');

cot_sendheaders();

$return = array(
  'result' => 'error',
  'status' => 'error',
  'response' => '',
  'type' => '', // report_update
  'trackId' => 0,
  'message' => ''
);
$return_json = true;
$redirect = cot_import('redirect', 'P', 'INT');

$orderId = cot_import('orderId', 'P', 'INT');
$action = cot_import('action', 'P', 'TXT');
$is_ajax = cot_import('is_ajax', 'P', 'INT');

if($usr['id'] > 0 && $orderId > 0) {
  $ord = $db->query("SELECT * FROM $db_market_orders WHERE order_id=".$orderId.(!$is_admin ? ' AND (order_seller='.$usr['id'].' OR order_userid='.$usr['id'].')' : '').' LIMIT 1')->fetch();

  $urrid = $usr['id'];

  if($ord['order_id'] > 0) {
    if($is_admin) {
      if($action == 'admin_arbitrage_result' && $ord['order_status'] == 'claim') {
        $ord_upd = array(
          'order_claim' => 0
        );
        $arbit_result = array(
          'msg' => cot_import('radm_message', 'P', 'TXT'),
          'payreturn' => array(
            'to_payer' => 0,
            'to_seller' => 0
          )
        );

        $arbit = array(
          'status' => cot_import('radm_rad_status', 'P', 'TXT'),

          'return_start' => cot_import('radm_rad_return_start', 'P', 'TXT'),
          'return_start_to_payer' => (float)cot_import('radm_val_return_start_to_payer', 'P', 'NUM'),
          'return_start_to_payer_dodji' => (float)cot_import('radm_val_return_start_to_payer_dodji', 'P', 'NUM'),

          'return_cancel' => cot_import('radm_rad_return_cancel', 'P', 'TXT'),
          'return_cancel_to_payer' => (float)cot_import('radm_val_return_cancel_to_payer', 'P', 'NUM'),
          'return_cancel_to_seller' => (float)cot_import('radm_val_return_cancel_to_seller', 'P', 'NUM'),
          'return_cancel_to_payer_dodji' => (float)cot_import('radm_val_return_cancel_to_payer_dodji', 'P', 'NUM'),
          'return_cancel_to_seller_dodji' => (float)cot_import('radm_val_return_cancel_to_seller_dodji', 'P', 'NUM'),

          'return_done' => cot_import('radm_rad_return_done', 'P', 'TXT'),
          'return_done_to_payer' => (float)cot_import('radm_val_return_done_to_payer', 'P', 'NUM'),
          'return_done_to_seller' => (float)cot_import('radm_val_return_done_to_seller', 'P', 'NUM'),
          'return_done_to_payer_dodji' => (float)cot_import('radm_val_return_done_to_payer_dodji', 'P', 'NUM'),
          'return_done_to_seller_dodji' => (float)cot_import('radm_val_return_done_to_seller_dodji', 'P', 'NUM'),

          'chg_lowrating' => cot_import('radm_chg_lowrating', 'P', 'INT'),
          'val_lowrating' => cot_import('radm_val_lowrating', 'P', 'NUM'),

          'del_reviews' => cot_import('radm_del_reviews', 'P', 'INT'),
        );

        foreach(array('status', 'chg_lowrating', 'val_lowrating', 'del_reviews') as $ii) {
          $arbit_result[$ii] = $arbit[$ii];
        }

        $payreturn = array(
          'to_payer' => 0,
          'to_seller' => 0,
          'to_payer_dodji' => 0,
          'to_seller_dodji' => 0,
        );

        if($arbit['status'] == 'start') {
          if($arbit['return_start'] == 'to_payer' && $arbit['return_start_to_payer'] > 0) {
            $payreturn['to_payer'] = $arbit['return_start_to_payer'];
            if($payreturn['to_payer'] < $ord['order_cost']) {
              $ord_upd['order_cost'] = $ord['order_cost'] - $payreturn['to_payer'];
            } else {
              $payreturn['to_payer'] = 0;
            }
          }
          if($arbit['return_start'] == 'to_payer' && $arbit['return_start_to_payer_dodji'] > 0) {
            $payreturn['to_payer_dodji'] = $arbit['return_start_to_payer_dodji'];
            if($payreturn['to_payer_dodji'] < $ord['order_cost_dodji']) {
              $ord_upd['order_cost_dodji'] = $ord['order_cost_dodji'] - $payreturn['to_payer_dodji'];
            } else {
              $payreturn['to_payer_dodji'] = 0;
            }
          }
          $ord_upd['order_cancel_perf'] = 0;
          $ord_upd['order_start'] = $sys['now'];
          $ord_upd['order_status'] = 'start';
          $ord_upd['order_status_code'] = '';
        }
        elseif($arbit['status'] == 'cancel' || $arbit['status'] == 'done') {
          $ord_upd['order_status_code'] = 'arbit_result_';

          $arbit_paytype = array(
            'type' => $arbit['return_'.$arbit['status']],
            'to_payer' => $arbit['return_'.$arbit['status'].'_to_payer'],
            'to_seller' => $arbit['return_'.$arbit['status'].'_to_seller'],
          );

          if($arbit['status'] == 'done') {
            if($arbit_paytype['to_seller'] > $ord['order_cost']) $arbit_paytype['to_seller'] = $ord['order_cost'];
            if($arbit_paytype['to_seller_dodji'] > $ord['order_cost_dodji']) $arbit_paytype['to_seller_dodji'] = $ord['order_cost_dodji'];
            $ord_upd['order_done'] = $sys['now'];
            $ord_upd['order_status'] = 'done';
            $ord_upd['order_status_code'] .= 'done_';
          } else {
            if($arbit_paytype['to_payer'] > $ord['order_cost']) $arbit_paytype['to_payer'] = $ord['order_cost'];
            if($arbit_paytype['to_payer_dodji'] > $ord['order_cost_dodji']) $arbit_paytype['to_payer_dodji'] = $ord['order_cost_dodji'];
            $ord_upd['order_cancel'] = $sys['now'];
            $ord_upd['order_status'] = 'cancel';
            $ord_upd['order_status_code'] .= 'cancel_';
          }

          $ord_upd['order_status_code'] .= $arbit_paytype['type'];

          if($arbit_paytype['type'] == 'to_split') {
            $payreturn = array(
              'to_payer' => $arbit_paytype['to_payer'],
              'to_seller' => $ord['order_cost'] - $arbit_paytype['to_payer'],
              'to_payer_dodji' => $arbit_paytype['to_payer_dodji'],
              'to_seller_dodji' => $ord['order_cost_dodji'] - $arbit_paytype['to_payer_dodji'],
            );
          } else {
            $payreturn = array(
              'to_payer' => ($arbit_paytype['type'] == 'to_payer' ? $arbit_paytype['to_payer'] : 0),
              'to_seller' => ($arbit_paytype['type'] == 'to_seller' ? $arbit_paytype['to_seller'] : 0),
              'to_payer_dodji' => ($arbit_paytype['type'] == 'to_payer' ? $arbit_paytype['to_payer_dodji'] : 0),
              'to_seller_dodji' => ($arbit_paytype['type'] == 'to_seller' ? $arbit_paytype['to_seller_dodji'] : 0),
            );
          }
        }

        if($payreturn['to_payer'] > 0 || $payreturn['to_seller'] > 0 || $payreturn['to_payer_dodji'] > 0 || $payreturn['to_seller_dodji'] > 0) {
          if($payreturn['to_payer'] > 0) {
            $payinfo = array();
          	$payinfo['pay_userid'] = $ord['order_userid'];
          	$payinfo['pay_area'] = 'balance';
          	$payinfo['pay_code'] = ($payreturn['to_payer'] == $ord['order_cost'] ? 'market_code_arbt:'.$ord['order_id'] : 'market_code_arbitrage_payer:'.$ord['order_id']);
          	$payinfo['pay_summ'] = $payreturn['to_payer'];
            $payinfo['pay_dodji'] = 0;
            $payinfo['pay_paydodji'] = 0;
          	$payinfo['pay_cdate'] = $sys['now'];
          	$payinfo['pay_pdate'] = $sys['now'];
          	$payinfo['pay_adate'] = $sys['now'];
          	$payinfo['pay_status'] = 'done';
          	$payinfo['pay_desc'] = $ord['order_title'];

          	$db->insert($db_payments, $payinfo);
          }
          if($payreturn['to_payer_dodji'] > 0) {
            $payinfo = array();
          	$payinfo['pay_userid'] = $ord['order_userid'];
          	$payinfo['pay_area'] = 'balance';
          	$payinfo['pay_code'] = ($payreturn['to_payer_dodji'] == $ord['order_cost_dodji'] ? 'market_code_arbt:'.$ord['order_id'] : 'market_code_arbitrage_payer:'.$ord['order_id']);
          	$payinfo['pay_summ'] = 0;
            $payinfo['pay_dodji'] = $payreturn['to_payer_dodji'];
            $payinfo['pay_paydodji'] = 1;
          	$payinfo['pay_cdate'] = $sys['now'];
          	$payinfo['pay_pdate'] = $sys['now'];
          	$payinfo['pay_adate'] = $sys['now'];
          	$payinfo['pay_status'] = 'done';
          	$payinfo['pay_desc'] = $ord['order_title'];

          	$db->insert($db_payments, $payinfo);
          }
          if($payreturn['to_seller'] > 0) {
            $payinfo = array();
          	$payinfo['pay_userid'] = $ord['order_seller'];
          	$payinfo['pay_area'] = 'balance';
          	$payinfo['pay_code'] = ($payreturn['to_payer'] == $ord['order_cost'] ? 'market_code_arbtdone:'.$ord['order_id'] : 'market_code_arbitrage_seller:'.$ord['order_id']);
          	$payinfo['pay_summ'] = $payreturn['to_seller'];
            $payinfo['pay_dodji'] = 0;
            $payinfo['pay_paydodji'] = 0;
          	$payinfo['pay_cdate'] = $sys['now'];
          	$payinfo['pay_pdate'] = $sys['now'];
          	$payinfo['pay_adate'] = $sys['now'];
          	$payinfo['pay_status'] = 'done';
          	$payinfo['pay_desc'] = $ord['order_title'];

          	$db->insert($db_payments, $payinfo);
          }
          if($payreturn['to_seller_dodji'] > 0) {
            $payinfo = array();
          	$payinfo['pay_userid'] = $ord['order_seller'];
          	$payinfo['pay_area'] = 'balance';
          	$payinfo['pay_code'] = ($payreturn['to_payer_dodji'] == $ord['order_cost_dodji'] ? 'market_code_arbtdone:'.$ord['order_id'] : 'market_code_arbitrage_seller:'.$ord['order_id']);
          	$payinfo['pay_summ'] = 0;
            $payinfo['pay_dodji'] = $payreturn['to_seller_dodji'];
            $payinfo['pay_paydodji'] = 1;
          	$payinfo['pay_cdate'] = $sys['now'];
          	$payinfo['pay_pdate'] = $sys['now'];
          	$payinfo['pay_adate'] = $sys['now'];
          	$payinfo['pay_status'] = 'done';
          	$payinfo['pay_desc'] = $ord['order_title'];

          	$db->insert($db_payments, $payinfo);
          }
          $arbit_result['payreturn'] = $payreturn;
        }

        if($arbit['chg_lowrating']) {
          $ord_upd['order_lowrating'] = $arbit['val_lowrating'];
        }

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

        $db->update($db_market_orders, $ord_upd, 'order_id='.$ord['order_id']);

        $tid_to = cot_mk_addtrack($ord['order_id'], 'arbitrage_result', 0, $ord['order_userid'], $arbit_result);
        $tid = cot_mk_addtrack($ord['order_id'], 'arbitrage_result', 0, $ord['order_seller'], $arbit_result, 0, $tid_to);
      }
    }

    if($ord['order_seller'] == $urrid && $action == 'seller_check_order' && $ord['order_status'] == 'start') {
      $message = cot_import('message', 'P', 'HTM');
      $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');
      $redirect = 0;

      $ord['order_worktime'] += $sys['now'] - $ord['order_start'];

      $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_check_order', 0, $ord['order_userid'], array('msg' => $message, 'accept' => 0));
      $tid = cot_mk_addtrack($ord['order_id'], 'seller_check_order', 0, $urrid, array('msg' => $message, 'accept' => 0), 1, $tid_to);

      $db->update($db_market_orders, array('order_worktime' => $ord['order_worktime'], 'order_check' => $sys['now'], 'order_status' => 'check'), 'order_id='.$ord['order_id']);

      $return['status'] = 'success';
      $return['type'] = 'report_update';

      $extramessage = '';

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

      $return['message'] = '<div id="track-id-'.$tid.'" class="step-block-order_item out" data-track-id="'.$tid.'">
              <div class="f14 color-gray mt3 t-align-r">'.cot_date('d M, H:i', $sys['now']).'</div>
              <div class="t-align-c">
                <i class="ico-green-box"></i>
                <h3 class="track-green pt10 font-OpenSansSemi">Заказ сдан на проверку</h3>'
                .(!empty($message) ?
                '<div class="f15 mt15 t-align-l ml80 mb15 breakwords m-ml0">
                  <i>'.$message.'</i>
                </div>' : '')
                .(!empty($extramessage) ?
                '<div class="f15 mt15 t-align-l ml80 mb15 breakwords m-ml0">
                  '.$extramessage.'
                </div>' : '').'
                <hr class="gray">
                <div class="f12 color-gray v-align-m ml10 t-align-l">Покупатель примет заказ или вернет его на доработку. Если в течение 3 дней покупатель не примет решение, заказ будет принят автоматически.</div>
              </div>
            </div>';

      $return['message'] .= '<script>$(\'.track-order-state\').html(\'На проверке\');$(\'.track-order-state-history\').append(\'<hr class="gray" data-trackstatehist="'.$tid.'"><div class="clearfix" data-trackstatehist="'.$tid.'"><div class="pull-left track-history-date">'.cot_date('d M, H:i', $sys['now']).'</div><div class="pull-right track-history-desc">Сдан на проверку</div></div>\');</script>';
      $return['message'] .= '<script>$(\'#countbox, [data-orderdeadline]\').hide();</script>';

      $return['message'] = cot_html_removelines($return['message']);

      cot_mk_reset_analytics($ord['order_seller']);
    } elseif(($ord['order_seller'] == $urrid && cot_import('suggestextrassubmited', 'P', 'BOL'))
      && $ord['order_status'] != 'cancel' && $ord['order_status'] != 'done' && $ord['order_status'] != 'claim'
    ) {
      require_once cot_incfile('catcostplans', 'plug');

      $message = cot_import('message', 'P', 'HTM');
      $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');
      $redirect = 1;

      $gextras = cot_import('gextras', 'P', 'ARR');

      $gextras_custom_tmp = array(
        'names' => cot_import('customExtraName', 'P', 'ARR'),
        'prices' => cot_import('customExtraPrice', 'P', 'ARR'),
        'times' => cot_import('customExtraTime', 'P', 'ARR')
      );

      $gextras_custom = array();
      foreach($gextras_custom_tmp['names'] as $i => $name) {
        if(!empty($name)) $gextras_custom[] = array(
          'name' => $name,
          'price' => $gextras_custom_tmp['prices'][$i],
          'time' => $gextras_custom_tmp['times'][$i]
        );
      }

      $return['result'] = 'error';
      $return['error'] = 'notcanaddextras';
      $return['difference'] = 0;

      if(count($gextras) > 0 || count($gextras_custom) > 0) {
        $costplan = (!empty($ord['order_catcostplans']) ? json_decode($ord['order_catcostplans'],1) : array(
          'package' => 'single',
          'extras' => array(
            'single' => array(
              'title' => '',
              'time' => 1,
              'count' => 1,
              'price' => $ord['order_cost']
            )
          )
        ));

        if($costplan['package'] == 'single') {
          $totalcost = 0;
          $totaltime = 0;
          $costplan['extras']['addextras'] = array();
          $costplan['extras']['addextras_custom'] = array();

          $jj=0;
          foreach($costplan['extras']['selected'] as $select) {
            if(in_array($select['id'], $gextras)) {
              $cpext = array(
                'id' => $select['id'],
                'name' => $select['name'],
                'time' => $select['duration'],
                'count' => cot_import('extra_count'.$select['id'], 'P', 'INT'),
                'priceId' => $select['priceId'],
                'payerPrice' => 0,
                'totalPrice' => 0,
                'totalTime' => 0,
              );

              if($cpext['count'] > 10) $cpext['count'] = 10;
              if($cpext['count'] > 0) {
                $cpext['totalTime'] = $select['duration']*$cpext['count'];

                $cpext['payerPrice'] = $select['payerPrice'];
                if($select['priceId'] > 0 && $costplans_prices[$select['priceId']] > 0) {
                  $cpext['payerPrice'] = $costplans_prices[$select['priceId']];
                }
                $cpext['totalPrice'] = round($cpext['payerPrice'] * $cpext['count']);
                $totalcost += $cpext['totalPrice'];
                $totaltime += $cpext['totalTime'];

                $costplan['extras']['addextras'][] = $cpext;
              }
            }
            $jj++;
          }

          foreach($gextras_custom as $select) {
            if(!$select['price'] || $select['price'] < 0) $select['price'] = 1;
            if($select['price'] > 10) $select['price'] = 10;
            $cpext = array(
              'id' => $jj,
              'name' => $select['name'],
              'time' => $select['time'],
              'count' => 1,
              'priceId' => $select['price'],
              'payerPrice' => 0,
              'totalPrice' => 0,
              'totalTime' => $select['time'],
            );

            if($costplans_prices[$select['price']] > 0) {
              $cpext['payerPrice'] = $costplans_prices[$select['price']];
            }

            $cpext['totalPrice'] = $cpext['payerPrice'];
            $totalcost += $cpext['totalPrice'];
            $totaltime += $cpext['totalTime'];

            $costplan['extras']['addextras_custom'][] = $cpext;

            $jj++;
          }

          $costplan['extras']['addextras_cnt'] = count($costplan['extras']['addextras']);
          $costplan['extras']['addextras_custom_cnt'] = count($costplan['extras']['addextras_custom']);

          if(($costplan['extras']['addextras_cnt'] > 0 || $costplan['extras']['addextras_custom_cnt'] > 0) && $totalcost > 0) {
            $pay_json = array(
              'selected' => $costplan['extras']['addextras'],
              'selected_custom' => $costplan['extras']['addextras_custom'],
              'totalcost' => $totalcost,
              'totaltime' => $totaltime,
              'payed' => 0,
              'msg' => $message,
            );

            $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_addextras', 0, $ord['order_userid'], $pay_json, 0);
            $tid = cot_mk_addtrack($ord['order_id'], 'seller_addextras', 0, $ord['order_seller'], $pay_json, 1, $tid_to);
          }
        }
      }
    }
    elseif(($action == 'text' || ($ord['order_userid'] == $urrid && $action == 'instruction')))
    {
      $message = cot_import('message', 'P', 'HTM');
      $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');

      if(!empty($message)) {
        $touid = ($ord['order_userid'] == $urrid ? $ord['order_seller'] : $ord['order_userid']);

        $tid_to = cot_mk_addtrack($ord['order_id'], 'market_msg', $urrid, $touid, array('msg' => $message, 'type' => ($action == 'instruction' ? 'instruction' : 'text')));
        $tid = cot_mk_addtrack($ord['order_id'], 'market_msg', $urrid, $urrid, array('msg' => $message, 'type' => ($action == 'instruction' ? 'instruction' : 'text')), 1, $tid_to);

        $return['status'] = 'success';
        $return['type'] = 'report_update';

        $extramessage = '';

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

        $message = cot_mk_msg_html($message);

        $return['message'] = '<div id="track-id-'.$tid.'" class="step-block-order_item text_message out editable unread" data-track-id="'.$tid.'">
                  <div class="block-circle block-circle_gray pull-left">
                    <img class="rounded" width="50" src="'.($usr['profile']['user_avatar'] ? $usr['profile']['user_avatar'] : 'themes/itbirja/files/avatar/big/noprofilepicture.gif').'" alt="">
                  </div>
                  <div class="font-OpenSans ml80">
                    <div class="f14 color-gray mt3 floatright">'.cot_date('d M, H:i', $sys['now']).'</div>
                    <div class="f16 pt10 font-OpenSans online-status">
                      <i class="icon ico-online"></i>
                      <span class="username f16">'.$usr['name'].'</span>
                    </div>
                  </div>
                  <div class="clear"></div>
                  <div class="font-OpenSans ml80 m-ml0 m-mt10">
                    <div class="f15 breakwords">'.$message.'</div>
                    '.$extramessage.'
                  </div>
                </div>';

        if(!$ord['order_sendinstr'] && $ord['order_userid'] == $urrid && $action == 'instruction') {
          $queuecnt = cot_mk_queue_cnt($ord);
          $queuettl = 'На согласовании';

          $ord['order_sendinstr'] = $sys['now'];
          $db->update($db_market_orders, array('order_sendinstr' => $ord['order_sendinstr']), 'order_id='.$ord['order_id']);

          if($ord['order_accept'] > 0) {
            $ord['order_queue'] = ($queuecnt > 0 ? 0 : $sys['now']);
            $ord['order_status'] = 'queue';
            $db->update($db_market_orders, array('order_queue' => $ord['order_queue'], 'order_status' => 'queue'), 'order_id='.$ord['order_id']);
          }

          if($ord['order_accept'] > 0) {
            $queuettl = 'Принят продавцом';
          } elseif($queuecnt > 0) {
            $queuettl = 'В очереди';
          }

          $queuemsg = cot_mk_queue_text($ord, $queuecnt);

          $return['message'] .= '<div class="step-block-order_item out unread" data-track-id="0">
            <div class="f14 color-gray mt3 t-align-r">'.cot_date('d M, H:i', $sys['now']).'</div>
            <div class="t-align-c">
                <i class="ico-more-info"></i>
                <h3 class="pt10 font-OpenSansSemi mb10">Вы предоставили нужные данные продавцу</h3>
                <hr class="gray">
                <div class="db f12 color-gray v-align-m ml10 mt15">'.$queuemsg.'</div>
                <script>
                  if ($(\'.instruction-js\').length > 0) {
                    $(".js-send-message-action").val(\'text\');
                    $(\'.instruction-js\').remove();
                    $(\'.fox_attention\').remove();
                  }
                </script>
            </div>
          </div>';

          $return['message'] .= '<script>$(\'.track-order-state\').html(\''.$queuettl.'\');$(\'.track-order-state-history\').append(\'<hr class="gray" data-trackstatehist="'.$tid.'"><div class="clearfix" data-trackstatehist="'.$tid.'"><div class="pull-left track-history-date">'.cot_date('d M, H:i', $sys['now']).'</div><div class="pull-right track-history-desc">Предоставлены данные</div></div>\');</script>';
        }

        $return['message'] = cot_html_removelines($return['message']);
      }
    } elseif($action == 'edit') {
      $return_json = false;

      $return = '<div class="step-block-order_item text_message out editable unread" data-track-id="0">
                   <div class="block-circle block-circle_gray pull-left">
                     <img class="rounded" width="50" src="'.($usr['profile']['user_avatar'] ? $usr['profile']['user_avatar'] : 'themes/itbirja/files/avatar/big/noprofilepicture.gif').'" alt="">
                   </div>
                   <div class="font-OpenSans ml80">
                     <div class="f14 color-gray mt3 floatright">'.cot_date('d M, H:i', $sys['now']).'</div>
                     <div class="f16 pt10 font-OpenSans online-status">
                       <i class="icon ico-online"></i>
                       <span class="username f16">'.$usr['name'].'</span>
                     </div>
                   </div>
                   <div class="clear"></div>
                   <div class="font-OpenSans ml80 m-ml0 m-mt10">
                     <div class="f15 breakwords"><span class="color-gray">Данное сообщение нельзя изменить</span></div>
                   </div>
                 </div>';

      $trackId = cot_import('trackId', 'P', 'INT');
      if($trackId > 0 && ($is_admin || (!$ord['order_claim'] && !$ord['order_done']))) {
        $message = cot_import('message', 'P', 'HTM');
        $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');

        $udata = $usr['profile'];

        if($is_admin) {
          $tmsg = $db->query("SELECT * FROM $db_market_track WHERE t_id=".$trackId.' AND t_oid='.$ord['order_id'].' LIMIT 1')->fetch();
          if($tmsg['t_id'] > 0 && $tmsg['t_fruser'] > 0) {
            $udata = $db->query("SELECT * FROM $db_users WHERE user_id=".$tmsg['t_fruser'].' LIMIT 1')->fetchAll();
          }
        } else {
          $tmsg = $db->query("SELECT * FROM $db_market_track WHERE t_id=".$trackId.' AND t_oid='.$ord['order_id'].' AND t_fruser='.$urrid.' LIMIT 1')->fetch();
        }

        if($tmsg['t_id'] > 0) {
          $tmsgsub = ($tmsg['t_subid'] > 0 ? $db->query("SELECT * FROM $db_market_track WHERE t_id=".$tmsg['t_subid'].' AND t_oid='.$ord['order_id'].(!$is_admin ? ' AND t_status=0' : '').' LIMIT 1')->fetch() : array());

          if($tmsgsub['t_id'] > 0) {
            $mktdata = json_decode($tmsg['t_json'], 1);
            if(!empty($message)) {
              $mktdata['msg'] = $message;
              $mktdata = json_encode($mktdata);
              $db->update($db_market_track, array('t_json' => $mktdata, 't_update' => $sys['now']), 't_id='.$tmsg['t_id'].' OR t_id='.$tmsgsub['t_id']);
            } else {
              $message = $mktdata['msg'];
            }

            $extramessage = '';

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

            $message = cot_mk_msg_html($message);

            $return = '<div id="track-id-'.$tmsg['t_id'].'" class="step-block-order_item text_message out editable unread" data-track-id="'.$tmsg['t_id'].'">
                      <div class="block-circle block-circle_gray pull-left">
                        <img class="rounded" width="50" src="'.($udata['user_avatar'] ? $udata['user_avatar'] : 'themes/itbirja/files/avatar/big/noprofilepicture.gif').'" alt="">
                      </div>
                      <div class="font-OpenSans ml80">
                        <div class="f14 color-gray mt3 floatright">'.cot_date('d M, H:i', $sys['now']).'</div>
                        <div class="f16 pt10 font-OpenSans online-status">
                          <i class="icon ico-online"></i>
                          <span class="username f16">'.$usr['name'].'</span>
                        </div>
                      </div>
                      <div class="clear"></div>
                      <div class="font-OpenSans ml80 m-ml0 m-mt10">
                        <div class="f15 breakwords">'.$message.'</div>
                        '.$extramessage.'
                      </div>
                    </div>';
          }
        }
      }
    } elseif($action == 'remove') {
      $return['success'] = 0;

      $itemId = cot_import('itemId', 'P', 'INT');
      if($itemId > 0 && ($is_admin || (!$ord['order_claim'] && !$ord['order_done']))) {
        if($is_admin) {
          $tmsg = $db->query("SELECT * FROM $db_market_track WHERE t_id=".$itemId.' AND t_oid='.$ord['order_id'].' LIMIT 1')->fetch();
        } else {
          $tmsg = $db->query("SELECT * FROM $db_market_track WHERE t_id=".$itemId.' AND t_oid='.$ord['order_id'].' AND t_fruser='.$urrid.' LIMIT 1')->fetch();
        }

        if($tmsg['t_id'] > 0) {
          $tmsgsub = ($tmsg['t_subid'] > 0 ? $db->query("SELECT * FROM $db_market_track WHERE t_id=".$tmsg['t_subid'].' AND t_oid='.$ord['order_id'].(!$is_admin ? ' AND t_status=0' : '').' LIMIT 1')->fetch() : array());

          if($tmsgsub['t_id'] > 0)
          {
         		/* === Hook === */
         		foreach (cot_getextplugins('marketorders.ajax.removemsg') as $pl)
         		{
         			include $pl;
         		}
        		/* ===== */

            $db->delete($db_market_track, 't_id='.$tmsg['t_id']);
            $db->delete($db_market_track, 't_id='.$tmsgsub['t_id']);

            $return['success'] = 1;
          }
        }
      }
    } elseif($action == 'cancelorder') {
      $message = cot_import('message', 'P', 'HTM');
      $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');

      $typeuser = ($ord['order_seller'] == $urrid ? 'seller' : 'payer');

      if(cot_mk_cancel_reasons($ord, $typeuser, '', true)) {
        $reason = cot_import('reason', 'P', 'TXT');
        $reasonchk = (!empty($reason) ? cot_mk_cancel_reasons($ord, $typeuser, $reason) : false);
        $minusrating = false;

        if(!$ord['order_start'] && !is_array($reasonchk) || count($reasonchk) == 0) {
          $reason = $typeuser.'_no_reason';
          $reasonchk = cot_mk_cancel_reasons($ord, $typeuser, $reason);
        }

        if(is_array($reasonchk)) {
          if($typeuser == 'seller') {
            if(empty($ord['order_status_code']) || !in_array($ord['order_status_code'], array_keys(cot_mk_cancel_reasons($ord, 'seller')))) {
              $reasonchk['lowrating'] = 0;
              $db->update($db_market_orders, array('order_cancel_perf' => $sys['now'], 'order_status_code' => $reason), 'order_id='.$ord['order_id']);
            }
          } else {
            if($ord['order_cost'] > 0) {
              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_userid'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code:'.$ord['order_id'];
            	$payinfo['pay_summ'] = $ord['order_cost'];
              $payinfo['pay_dodji'] = 0;
              $payinfo['pay_paydodji'] = 0;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }
            if($ord['order_cost_dodji'] > 0) {
              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_userid'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code:'.$ord['order_id'];
            	$payinfo['pay_summ'] = 0;
              $payinfo['pay_dodji'] = $ord['order_cost_dodji'];
              $payinfo['pay_paydodji'] = 1;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }

            $db->update($db_market_orders, array('order_cancel' => $sys['now'], 'order_status' => 'cancel', 'order_status_code' => $reason), 'order_id='.$ord['order_id']);

            cot_mk_queue_next($ord['order_seller']);
          }

          $db->update($db_market_orders, array('order_lowrating' => $reasonchk['lowrating']), 'order_id='.$ord['order_id']);

          $tid_to = cot_mk_addtrack($ord['order_id'], $reason, 0, $ord['order_userid'], array('msg' => $message, 'lowrating' => $reasonchk['lowrating'], 'can_arbitrage' => (($typeuser == 'seller' || !$ord['order_start']) ? 0 : 1)), ($ord['order_userid'] == $urrid ? 1 : 0));
          $tid = cot_mk_addtrack($ord['order_id'], $reason, 0, $ord['order_seller'], array('msg' => $message, 'lowrating' => $reasonchk['lowrating'], 'can_arbitrage' => (($typeuser == 'seller' || !$ord['order_start']) ? 0 : 1)), ($ord['order_seller'] == $urrid ? 1 : 0), $tid_to);

          cot_mk_reset_analytics($ord['order_seller']);
        }
      }
    } elseif($action == 'seller_accept_order') {
      if($ord['order_seller'] == $urrid && !$ord['order_done'] && !$ord['order_claim'] && !$ord['order_cancel'] && !$ord['order_cancel_perf']) {
        $db->update($db_market_orders, array('order_cancel_perf' => 0, 'order_status_code' => '', 'order_accept' => $sys['now']), 'order_id='.$ord['order_id']);

        if($ord['order_sendinstr'] > 0) {
          $db->update($db_market_orders, array('order_status' => 'queue', 'order_queue' => (cot_mk_queue_cnt($ord) > 0 ? 0 : $sys['now'])), 'order_id='.$ord['order_id']);
        }

        $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_userid'], array(), 0);
        $tid = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_seller'], array(), 1, $tid_to);

        cot_mk_reset_analytics($ord['order_seller']);
      }
    } elseif($action == 'seller_check_order') {
      if($ord['order_seller'] == $urrid && $ord['order_start'] > 0 && !$ord['order_check'] && !$ord['order_done'] && !$ord['order_claim'] && !$ord['order_cancel']) {
        $db->update($db_market_orders, array('order_cancel_perf' => 0, 'order_status_code' => '', 'order_status' => 'check', 'order_check' => $sys['now']), 'order_id='.$ord['order_id']);

        $message = cot_import('message', 'P', 'HTM');
        $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');

        $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_userid'], array('msg' => $message), 0);
        $tid = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_seller'], array('msg' => $message), 1, $tid_to);

        cot_mk_reset_analytics($ord['order_seller']);
      }
    } elseif($action == 'cancelaccept') {
      $trackId = cot_import('trackId', 'P', 'INT');
      $accept = cot_import('accept', 'P', 'INT');

      if($trackId > 0 && $ord['order_userid'] == $urrid) {
        $tid = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND t_id='.$trackId.' LIMIT 1')->fetch();

        if($tid['t_id'] > 0) {
          $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND '.($tid['t_subid'] > 0 ? 't_id='.$tid['t_subid'] : 't_subid='.$tid['t_id']).' LIMIT 1')->fetch();//t_subid

          $reason = $ord['order_status_code'];
          if(empty($reason) || $reason == 'seller_no_reason') $reason = 'payer_and_perf_sogl';

          if($accept == 1) {
            if($ord['order_cost'] > 0) {
              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_userid'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code:'.$ord['order_id'];
            	$payinfo['pay_summ'] = $ord['order_cost'];
              $payinfo['pay_dodji'] = 0;
              $payinfo['pay_paydodji'] = 0;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }
            if($ord['order_cost_dodji'] > 0) {
              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_userid'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code:'.$ord['order_id'];
            	$payinfo['pay_summ'] = 0;
              $payinfo['pay_dodji'] = $ord['order_cost_dodji'];
              $payinfo['pay_paydodji'] = 1;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }

            $db->update($db_market_orders, array('order_cancel' => $sys['now'], 'order_status' => 'cancel', 'order_cancel_perf' => 0, 'order_status_code' => $reason), 'order_id='.$ord['order_id']);

            cot_mk_queue_next($ord['order_seller']);
            cot_mk_reset_analytics($ord['order_seller']);
          } else {
            $db->update($db_market_orders, array('order_cancel_perf' => 0, 'order_status_code' => ''), 'order_id='.$ord['order_id']);
          }

          $db->update($db_market_orders, array('order_lowrating' => $marketorders_cancel_reasons[$reason]['lowrating']), 'order_id='.$ord['order_id']);

          $mktdata = json_decode($tid['t_json'], 1);
          $db->update($db_market_track, array('t_update' => $sys['now'], 't_code' => ($accept == 1 ? 'payer_and_perf_sogl' : $tid['t_code']), 't_status' => ($tid['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode(array('msg' => $mktdata['msg'], 'lowrating' => $marketorders_cancel_reasons[$reason]['lowrating'], 'cancel_accept' => ($accept == 1 ? 1 : 2)))), 't_id='.$tid['t_id']);
          if($tid_to['t_id'] > 0) {
            $db->update($db_market_track, array('t_update' => $sys['now'], 't_code' => ($accept == 1 ? 'payer_and_perf_sogl' : $tid['t_code']), 't_status' => ($tid_to['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode(array('msg' => $mktdata['msg'], 'lowrating' => $marketorders_cancel_reasons[$reason]['lowrating'], 'cancel_accept' => ($accept == 1 ? 1 : 2)))), 't_id='.$tid_to['t_id']);
          }
        }
      }
    } elseif($action == 'checkaccept') {
      $trackId = cot_import('trackId', 'P', 'INT');
      $accept = cot_import('accept', 'P', 'INT');

      if($trackId > 0 && $ord['order_userid'] == $urrid && $ord['order_status'] == 'check') {
        $tid = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND t_id='.$trackId.' LIMIT 1')->fetch();

        if($tid['t_id'] > 0) {
          $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND '.($tid['t_subid'] > 0 ? 't_id='.$tid['t_subid'] : 't_subid='.$tid['t_id']).' LIMIT 1')->fetch();//t_subid

          if($accept == 1) {
            if($ord['order_cost'] > 0) {
              $summ = $ord['order_cost'] - $ord['order_cost']*($ord['order_tax']/100);

              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_seller'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code_done:'.$ord['order_id'];
            	$payinfo['pay_summ'] = $summ;
              $payinfo['pay_dodji'] = 0;
              $payinfo['pay_paydodji'] = 0;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }

            if($ord['order_cost_dodji'] > 0) {
              $summdodji = $ord['order_cost_dodji'] - $ord['order_cost_dodji']*($ord['order_tax_dodji']/100);

              $payinfo = array();
            	$payinfo['pay_userid'] = $ord['order_seller'];
            	$payinfo['pay_area'] = 'balance';
            	$payinfo['pay_code'] = 'market_code_done:'.$ord['order_id'];
            	$payinfo['pay_summ'] = 0;
              $payinfo['pay_dodji'] = $summdodji;
              $payinfo['pay_paydodji'] = 1;
            	$payinfo['pay_cdate'] = $sys['now'];
            	$payinfo['pay_pdate'] = $sys['now'];
            	$payinfo['pay_adate'] = $sys['now'];
            	$payinfo['pay_status'] = 'done';
            	$payinfo['pay_desc'] = $ord['order_title'];

            	$db->insert($db_payments, $payinfo);
            }

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

            $db->update($db_market_orders, array('order_done' => $sys['now'], 'order_status' => 'done', 'order_check' => 0), 'order_id='.$ord['order_id']);

            cot_mk_queue_next($ord['order_seller']);
            cot_mk_reset_analytics($ord['order_seller']);
          } else {
            $db->update($db_market_orders, array('order_start' => $sys['now'], 'order_status' => 'start', 'order_check' => 0), 'order_id='.$ord['order_id']);
          }

          $ntid_to = cot_mk_addtrack($ord['order_id'], ($accept == 1 ? 'payer_done_order' : 'payer_reorder'), 0, $ord['order_seller'], array('can_arbitrage' => ($accept == 1 ? 0 : 1)));
          $ntid = cot_mk_addtrack($ord['order_id'], ($accept == 1 ? 'payer_done_order' : 'payer_reorder'), 0, $urrid, array('can_arbitrage' => ($accept == 1 ? 0 : 1)), 1, $ntid_to);

          $mktdata = json_decode($tid['t_json'], 1);
          $mktdata['accept'] = ($accept ? $sys['now'] : -1);

          $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($mktdata)), 't_id='.$tid['t_id']);
          if($tid_to['t_id'] > 0) {
            $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid_to['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($mktdata)), 't_id='.$tid_to['t_id']);
          }
        }
      }
    } elseif($action == 'seller_start_order') {
      if($ord['order_seller'] == $urrid && in_array($ord['order_status'], array('paid', 'queue'))) {// && $ord['order_sendinstr'] > 0) {

        if(!$ord['order_accept']) {
          $db->update($db_market_orders, array('order_cancel_perf' => 0, 'order_status_code' => '', 'order_accept' => $sys['now']), 'order_id='.$ord['order_id']);

          if($ord['order_sendinstr'] > 0) {
            $db->update($db_market_orders, array('order_status' => 'queue', 'order_queue' => (cot_mk_queue_cnt($ord) > 0 ? 0 : $sys['now'])), 'order_id='.$ord['order_id']);
          }

          $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_userid'], array(), 0);
          $tid = cot_mk_addtrack($ord['order_id'], 'seller_accept_order', 0, $ord['order_seller'], array(), 1, $tid_to);
        }

        $db->update($db_market_orders, array('order_start' => $sys['now'], 'order_status' => 'start'), 'order_id='.$ord['order_id']);

        $tid_to = cot_mk_addtrack($ord['order_id'], 'seller_start_order', 0, $ord['order_seller'], array(), 1);
        $tid = cot_mk_addtrack($ord['order_id'], 'seller_start_order', 0, $ord['order_userid'], array(), 0, $tid_to);

        cot_mk_reset_analytics($ord['order_seller']);
      }
    } elseif($action == 'addextras') {
      $gextras = cot_import('gextras', 'P', 'ARR');

      $return['result'] = 'error';
      $return['error'] = 'notcanaddextras';
      $return['difference'] = 0;

      if(count($gextras) > 0 && $ord['order_userid'] == $urrid && $ord['order_status'] != 'cancel' && $ord['order_status'] != 'done' && $ord['order_status'] != 'claim') {
        $costplan = (!empty($ord['order_catcostplans']) ? json_decode($ord['order_catcostplans'],1) : array(
          'package' => 'single',
          'extras' => array(
            'single' => array(
              'title' => '',
              'time' => 1,
              'count' => 1,
              'price' => $ord['order_cost']
            )
          )
        ));

        if($costplan['package'] == 'single') {
          $totalcost = 0;
          $totaltime = 0;
          $costplan['extras']['addextras'] = array();

          foreach($costplan['extras']['selected'] as $select) {
            if(in_array($select['id'], $gextras)) {
              $cpext = array(
                'id' => $select['id'],
                'name' => $select['name'],
                'time' => $select['duration'],
                'count' => cot_import('extra_count'.$select['id'], 'P', 'INT'),
                'priceId' => $select['priceId'],
                'payerPrice' => 0,
                'totalPrice' => 0,
                'totalTime' => 0,
              );

              if($cpext['count'] > 10) $cpext['count'] = 10;
              if($cpext['count'] > 0) {
                $cpext['totalTime'] = $select['duration']*$cpext['count'];

                $cpext['payerPrice'] = $select['payerPrice'];
                if($select['priceId'] > 0 && $costplans_prices[$select['priceId']] > 0) {
                  $cpext['payerPrice'] = $costplans_prices[$select['priceId']];
                }
                $cpext['totalPrice'] = round($cpext['payerPrice'] * $cpext['count']);
                $totalcost += $cpext['totalPrice'];
                $totaltime += $cpext['totalTime'];

                $costplan['extras']['addextras'][] = $cpext;
              }
            }
          }
          $costplan['extras']['addextras_cnt'] = count($costplan['extras']['addextras']);

          if($costplan['extras']['addextras_cnt'] > 0 && $totalcost > 0) {
            $return['payjson'] = array(
              'selected' => $costplan['extras']['addextras'],
              'totalcost' => $totalcost,
              'totaltime' => $totaltime,
            );

            $options = array();
            $options['code'] = $ord['order_id'];
            $options['desc'] = '';

            if($db->fieldExists($db_payments, "pay_redirect"))
            {
            	$options['redirect'] = $cfg['mainurl'].'/'.cot_url('plug', 'e=marketorders&m=order&id='.$ord['order_id'], '', true);
            }
            if($db->fieldExists($db_payments, "pay_json"))
            {
            	$options['json'] = json_encode($return['payjson']);
            }
            $options['desc'] = $ord['order_title'];

            $ubalance = cot_payments_getuserbalance($urrid);
            $pidb = cot_payments_create_order('market_payaddextras', $totalcost, $options);
            if($pidb > 0) {
              if($ubalance >= $totalcost) {
                $return['result'] = 'success';
                $return['error'] = '';
                $return['redirectUrl'] = cot_url('payments', 'm=billing&pid=' . $pidb , '', true);
              } else {
                $return['error'] = 'funds';
                $return['newform_type'] = 'mk_addextras';
                $return['difference'] = $totalcost-$ubalance;
                $return['payment_id'] = $pidb;
              }
            }
          }
        }
      }
    } elseif($action == 'accept_seller_addextras') {
      $accept = cot_import('accept', 'P', 'INT');
      $trackId = cot_import('trackId', 'P', 'INT');

      $return['result'] = 'error';
      $return['error'] = 'notcanaddextras';
      $return['difference'] = 0;

      $tid = array('t_id' => 0);
      $track_json = array();

      if($trackId > 0) {
        $tid = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND t_id='.$trackId.' LIMIT 1')->fetch();
        if($tid['t_id'] > 0) {
          $track_json = (!empty($tid['t_json']) ? json_decode($tid['t_json'], 1) : array());

          if($track_json['payed'] != 0 || (count($track_json['selected']) == 0 && count($track_json['selected_custom']) == 0)) $tid = array('t_id' => 0);
        }
      }

      if($tid['t_id'] > 0 && $ord['order_userid'] == $urrid && $ord['order_status'] != 'cancel' && $ord['order_status'] != 'done' && $ord['order_status'] != 'claim') {
        $costplan = (!empty($ord['order_catcostplans']) ? json_decode($ord['order_catcostplans'],1) : array(
          'package' => 'single',
          'extras' => array(
            'single' => array(
              'title' => '',
              'time' => 1,
              'count' => 1,
              'price' => $ord['order_cost']
            )
          )
        ));

        if($costplan['package'] == 'single') {
          if($accept) {
            $options = array();
            $options['code'] = $tid['t_id'];
            $options['desc'] = '';

            if($db->fieldExists($db_payments, "pay_redirect"))
            {
            	$options['redirect'] = $cfg['mainurl'].'/'.cot_url('plug', 'e=marketorders&m=order&id='.$ord['order_id'], '', true);
            }
            if($db->fieldExists($db_payments, "pay_json"))
            {
            	$options['json'] = json_encode($track_json);
            }
            $options['desc'] = $ord['order_title'];

            $ubalance = cot_payments_getuserbalance($urrid);
            $pidb = cot_payments_create_order('market_accept_seller_payaddextras', $track_json['totalcost'], $options);
            if($pidb > 0) {
              if($ubalance >= $track_json['totalcost']) {
                $return['result'] = 'success';
                $return['error'] = '';
                $return['redirectUrl'] = cot_url('payments', 'm=billing&pid=' . $pidb , '', true);
              } else {
                $return['error'] = 'funds';
                $return['newform_type'] = 'mk_accept_seller_addextras';
                $return['difference'] = $track_json['totalcost']-$ubalance;
                $return['payment_id'] = $pidb;
              }
            }
          } else {
            $track_json['payed'] = -1;

            $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($track_json)), 't_id='.$tid['t_id']);

            $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND '.($tid['t_subid'] > 0 ? 't_id='.$tid['t_subid'] : 't_subid='.$tid['t_id']).' LIMIT 1')->fetch();//t_subid
            if($tid_to['t_id'] > 0) {
              $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid_to['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($track_json)), 't_id='.$tid_to['t_id']);
            }
          }
        }
      }

      if(!$accept) $redirect = true;
    } elseif($action == 'phases_save' && in_array($ord['order_status'], array('start'))) {
      $return['success'] = true;

      $phases_old = (!empty($ord['order_steps']) ? json_decode($ord['order_steps'],1) : array());
      $phases_new = $phases_old;
      $phases = cot_import('phases', 'P', 'ARR');
      if(count($phases) > 0) {
        foreach($phases as $i => $phsname) {
          if(!is_array($phases_new[$i])) {
            $phases_new[$i] = array(
              'title' => '',
              'lprc' => 0,
              'lmsg' => '',
              'changes' => array()
            );
            $changes = array();
            for($ci = 0; $ci <= 100; $ci+=10) {
              $changes[$ci] = array(
                'v' => 0,
                't' => 0,
                'm' => ''
              );
            }
            $phases_new[$i]['changes'] = $changes;
          }
          $phases_new[$i]['title'] = (!empty($phsname) ? $phsname : 'Этап '.($i+1));

          /*
          $changes = array();
          for($ci = 0; $ci <= 100; $ci+=10) {
            $changes[$ci] = array(
              'v' => 0,
              'r' => 0,
              'm' => ''
            );
          }
          $phases_new[$i]['changes'] = $changes;
          */
        }

        if(count($phases_old) == 0) {
          $ptitles = array();
          foreach($phases_new as $phsname) {
            $ptitles[] = $phsname;
          }
          $tid_to = cot_mk_addtrack($ord['order_id'], 'add_phases', 0, $ord['order_seller'], $ptitles, 1);
          $tid = cot_mk_addtrack($ord['order_id'], 'add_phases', 0, $ord['order_userid'], $ptitles, 0, $tid_to);
        }

        $db->update($db_market_orders, array('order_steps' => json_encode($phases_new)), 'order_id='.$ord['order_id']);
        $db->update($db_market_track, array('t_update' => $sys['now']), "t_code='add_phases' AND t_oid=".$ord['order_id']);
        $db->update($db_market_track, array('t_status' => 0), "t_code='add_phases' AND t_oid=".$ord['order_id'].' AND t_touser='.$ord['order_userid']);
      }
    } elseif($action == 'inprogress_report' && in_array($ord['order_status'], array('start', 'check'))) {
      $redirect = true;

      $phases_old = (!empty($ord['order_steps']) ? json_decode($ord['order_steps'],1) : array());
      $phases_new = $phases_old;

      $data = array(
        'steps' => cot_import('steps', 'P', 'ARR'),
        'comment' => cot_import('comment', 'P', 'TXT')
      );

      $is_changes = array();

      if(count($phases_old) > 0) {
        foreach($phases_old as $i => $step) {
          if($data['steps'][$i] > 0 && in_array($data['steps'][$i], array(10,20,30,40,50,60,70,80,90,100)) && $data['steps'][$i] > $step['lprc']) {
            for($ci = 0; $ci < $data['steps'][$i]; $ci+=10) {
              $phases_new[$i]['changes'][$ci]['v'] = 1;
            }
            $phases_new[$i]['changes'][$data['steps'][$i]] = array(
              'v' => 1,
              'r' => 0,
              'm' => $data['comment']
            );

            $phases_new[$i]['lprc'] = $data['steps'][$i];
            if(!empty($data['comment'])) $phases_new[$i]['lmsg'] = $data['comment'];

            $is_changes[] = array(
              'step' => $i,
              'val' => $data['steps'][$i]
            );
          }
        }

        if(count($is_changes) > 0) {
          $tid_to = cot_mk_addtrack($ord['order_id'], 'report_phases', 0, $ord['order_seller'], array('changes' => $is_changes, 'msg' => $data['comment']), 1);
          $tid = cot_mk_addtrack($ord['order_id'], 'report_phases', 0, $ord['order_userid'], array('changes' => $is_changes, 'msg' => $data['comment']), 0, $tid_to);

          foreach($is_changes as $cngstep) {
            $phases_new[$cngstep['step']]['changes'][$cngstep['val']]['r'] = $tid;
          }
        }

        $db->update($db_market_orders, array('order_steps' => json_encode($phases_new)), 'order_id='.$ord['order_id']);
        $db->update($db_market_track, array('t_update' => $sys['now']), "t_code='add_phases' AND t_oid=".$ord['order_id']);
        $db->update($db_market_track, array('t_status' => 0), "t_code='add_phases' AND t_oid=".$ord['order_id'].' AND t_touser='.$ord['order_userid']);
      }
    } elseif($action == 'to_arbitrage') {
      $redirect = true;
      $message = cot_import('message', 'P', 'HTM');
      $message = strip_tags($message, '<p><strong><em><br><ol><ul><li>');
                         //&& $ord['order_accept'] > 0
      if(!empty($message) && !$ord['order_claim'] && !$ord['order_done']) {
        $frutype = 'seller';
        $touid = $ord['order_userid'];
        if($ord['order_userid'] == $urrid) {
          $touid = $ord['order_seller'];
          $frutype = 'payer';
        }

        //if($ord['order_start'] > 0) $ord['order_worktime'] += $sys['now'] - $ord['order_start'];

        $db->update($db_market_orders, array('order_claim' => $sys['now'], 'order_status' => 'claim', 'order_worktime' => $ord['order_worktime']), 'order_id='.$ord['order_id']);

        if($frutype == 'seller' && $ord['order_status'] == 'cancel' && in_array($ord['order_status_code'], array('payer_worker_cannot_execute_correct', 'payer_do_not_like_this_worker', 'payer_no_communication_with_worker', 'payer_other_no_guilt'))) {
          if($ord['order_cost'] > 0) {
            $payinfo = array();
            $payinfo['pay_userid'] = $ord['order_userid'];
            $payinfo['pay_area'] = 'market_arbitrage';
            $payinfo['pay_code'] = $ord['order_id'];
            $payinfo['pay_summ'] = $ord['order_cost'];
            $payinfo['pay_dodji'] = 0;
            $payinfo['pay_paydodji'] = 0;
            $payinfo['pay_cdate'] = $sys['now'];
            $payinfo['pay_pdate'] = $sys['now'];
            $payinfo['pay_adate'] = $sys['now'];
            $payinfo['pay_status'] = 'done';
            $payinfo['pay_desc'] = $ord['order_title'];

            $db->insert($db_payments, $payinfo);
            $payid = $db->lastInsertId();

            $payinfo = array();
            $payinfo['pay_userid'] = $ord['order_userid'];
            $payinfo['pay_area'] = 'balance';
            $payinfo['pay_code'] = $payid;
            $payinfo['pay_summ'] = -$ord['order_cost'];
            $payinfo['pay_dodji'] = 0;
            $payinfo['pay_paydodji'] = 0;
            $payinfo['pay_cdate'] = $sys['now'];
            $payinfo['pay_pdate'] = $sys['now'];
            $payinfo['pay_adate'] = $sys['now'];
            $payinfo['pay_status'] = 'done';
            $payinfo['pay_desc'] = '';

            $db->insert($db_payments, $payinfo);
            $payid_b = $db->lastInsertId();
          }

          if($ord['order_cost_dodji'] > 0) {
            $payinfo = array();
            $payinfo['pay_userid'] = $ord['order_userid'];
            $payinfo['pay_area'] = 'market_arbitrage';
            $payinfo['pay_code'] = $ord['order_id'];
            $payinfo['pay_summ'] = 0;
            $payinfo['pay_dodji'] = $ord['order_cost_dodji'];
            $payinfo['pay_paydodji'] = 1;
            $payinfo['pay_cdate'] = $sys['now'];
            $payinfo['pay_pdate'] = $sys['now'];
            $payinfo['pay_adate'] = $sys['now'];
            $payinfo['pay_status'] = 'done';
            $payinfo['pay_desc'] = $ord['order_title'];

            $db->insert($db_payments, $payinfo);
            $paydid = $db->lastInsertId();

            $payinfo = array();
            $payinfo['pay_userid'] = $ord['order_userid'];
            $payinfo['pay_area'] = 'balance';
            $payinfo['pay_code'] = $paydid;
            $payinfo['pay_summ'] = 0;
            $payinfo['pay_dodji'] = -$ord['order_cost_dodji'];
            $payinfo['pay_paydodji'] = 1;
            $payinfo['pay_cdate'] = $sys['now'];
            $payinfo['pay_pdate'] = $sys['now'];
            $payinfo['pay_adate'] = $sys['now'];
            $payinfo['pay_status'] = 'done';
            $payinfo['pay_desc'] = '';

            $db->insert($db_payments, $payinfo);
            $paydid_b = $db->lastInsertId();
          }
        }

        $tid_to = cot_mk_addtrack($ord['order_id'], $frutype.'_to_arbitrage', 0, $touid, array('msg' => $message, 'type' => 'arbitrage'));
        $tid = cot_mk_addtrack($ord['order_id'], $frutype.'_to_arbitrage', 0, $urrid, array('msg' => $message, 'type' => 'arbitrage'), 1, $tid_to);

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

        $trackId = cot_import('trackId', 'P', 'INT');
        if($trackId > 0 && $ord['order_userid'] == $urrid) {
          $tid = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND t_id='.$trackId.' LIMIT 1')->fetch();

          if($tid['t_id'] > 0) {
            $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND '.($tid['t_subid'] > 0 ? 't_id='.$tid['t_subid'] : 't_subid='.$tid['t_id']).' LIMIT 1')->fetch();//t_subid

            $mktdata = (!empty($tid['t_json']) ? json_decode($tid['t_json'], 1) : array());
            $mktdata['can_arbitrage'] = 0;

            $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($mktdata)), 't_id='.$tid['t_id']);
            if($tid_to['t_id'] > 0) {
              $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => ($tid_to['t_touser'] == $urrid ? 1 : 0), 't_json' => json_encode($mktdata)), 't_id='.$tid_to['t_id']);
            }
          }
        }
      }
    } elseif($action == 'worker_portfolio') {
      $redirect = true;
      if($ord['order_done'] > 0) {
        require_once cot_incfile('uploads');

        $file = $_FILES['prd-photo'];
        $extradata = cot_import('prd-photo-size', 'P', 'TXT');
        $extradata = (!empty($extradata) ? json_decode($extradata,1) : array());

  			if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
  			{
  				$gd_supported = array('jpg', 'jpeg', 'png', 'gif');
  				$var = explode(".", $file['name']);
  				$file_ext = strtolower(array_pop($var));
  				$fcheck = cot_file_check($file['tmp_name'], $file['name'], $file_ext);
  				if (in_array($file_ext, $gd_supported) && $fcheck == 1)
  				{
            if(!empty($ord['order_folio']) && file_exists($ord['order_folio'])) unlink($ord['order_folio']);

  					$file['name'] = cot_safename($file['name'], true);

  					$filename_full = $ord['order_id'] . '_folio_'.$sys['now'].'.'.$file_ext;
  					$filepath = 'datas/market/' . $filename_full;

  					move_uploaded_file($file['tmp_name'], $filepath);

  					cot_imageresize($filepath, $filepath, 650, 433, '', '', 100, true, $extradata);
  					@chmod($filepath, $cfg['file_perms']);

            $ord['order_folio'] = $filepath;

            $db->update($db_market_orders, array('order_folio' => $ord['order_folio']), 'order_id='.$ord['order_id']);
  				}
  			}
      }
    } elseif($action == 'worker_portfolio_delete') {
      $redirect = true;
      if($ord['order_done'] > 0) {
        if(!empty($ord['order_folio']) && file_exists($ord['order_folio'])) unlink($ord['order_folio']);
        $db->update($db_market_orders, array('order_folio' => ''), 'order_id='.$ord['order_id']);
      }
    }

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

if($action == 'ds_mk_msgtype_buy' && cot_module_active('ds')) {
  require_once cot_incfile('ds', 'module');

  $return['result'] = 'error';
  $return['error'] = 'msgnotfound';
  $return['difference'] = 0;

  $mdgId = cot_import('msgId', 'P', 'INT');
  if($mdgId > 0 && $usr['id'] > 0) {
    $dsmsg = $db->query("SELECT * FROM $db_ds_msg WHERE id=".$mdgId.' AND touser='.$usr['id'].' AND (mtype=2 OR mtype=3) LIMIT 1')->fetch();

    if($dsmsg['id'] > 0) {
      $accept = cot_import('accept', 'P', 'INT');
      $mdata = cot_ds_get_mdata($dsmsg['mtype'], $dsmsg['mdata']);

      $return['error'] = 'msgalreadyhaveorder';
      if(!$mdata['orderId']) {
        if($accept) {
          $totalprice = (float)$mdata['price'];

          $options = array();
          $options['code'] = $dsmsg['id'];
          $options['desc'] = '';

          if($db->fieldExists($db_payments, "pay_redirect"))
          {
          	$options['redirect'] = $cfg['mainurl'].'/'.cot_url('ds', 'm=dialog&id='.$dsmsg['dialog'] . '&mk_msg=' . $dsmsg['id'] . '&msg=' . $dsmsg['id'], '', true);
          }
          if($db->fieldExists($db_payments, "pay_json"))
          {
          	$options['json'] = json_encode($mdata);
          }
          $options['desc'] = $mdata['name'];

          $ubalance = cot_payments_getuserbalance($usr['id']);
          $pidb = cot_payments_create_order('ds_accept_mkorder', $totalprice, $options);
          if($pidb > 0) {
            if($ubalance >= $totalprice) {
              $return['result'] = 'success';
              $return['error'] = '';
              $return['redirectUrl'] = cot_url('payments', 'm=billing&pid=' . $pidb , '', true);
            } else {
              $return['error'] = 'funds';
              $return['newform_type'] = 'ds_accept_mkorder';
              $return['difference'] = $totalprice-$ubalance;
              $return['payment_id'] = $pidb;
            }
          }
        } else {
          $mdata['decline'] = 1;
          $db->update($db_ds_msg, array('mdata' => json_encode($mdata)), 'id='.$dsmsg['id']);

          $return['result'] = 'success';
          $return['error'] = '';
        }
      }
    }
  }
  echo json_encode($return);
  exit;
}

if($action == 'prj_offer_buy' && cot_module_active('projects')) {
  require_once cot_incfile('projects', 'module');

  $return['result'] = 'error';
  $return['error'] = 'offernotfound';
  $return['difference'] = 0;

  $orderId = cot_import('orderId', 'P', 'INT');
  if($orderId > 0 && $usr['id'] > 0) {
    $prjoffer = $db->query("SELECT * FROM $db_projects_offers as o LEFT JOIN $db_projects as p ON p.item_id=o.offer_pid
      WHERE offer_id=".$orderId.' AND item_userid='.$usr['id'].' LIMIT 1')->fetch();

    if($prjoffer['offer_id'] > 0) {
      $mdata = (!empty($prjoffer['offer_json']) ? json_decode($prjoffer['offer_json'], 1) : array());
      if(!is_array($mdata)) $mdata = array();

      $return['error'] = 'offeralreadypay';
      if(!$mdata['orderId']) {
        $totalprice = (float)$mdata['price'];

        $options = array();
        $options['code'] = $prjoffer['offer_id'];
        $options['desc'] = '';

        if($db->fieldExists($db_payments, "pay_redirect"))
        {
        	$options['redirect'] = $cfg['mainurl'].'/'.cot_url('projects', 'id='.$prjoffer['item_id'], '', true);
        }
        if($db->fieldExists($db_payments, "pay_json"))
        {
        	$options['json'] = json_encode($mdata);
        }
        $options['desc'] = $mdata['name'];

        $ubalance = cot_payments_getuserbalance($usr['id']);
        $pidb = cot_payments_create_order('prj_accept_offer', $totalprice, $options);
        if($pidb > 0) {
          if($ubalance >= $totalprice) {
            $return['result'] = 'success';
            $return['error'] = '';
            $return['redirectUrl'] = cot_url('payments', 'm=billing&pid=' . $pidb , '', true);
          } else {
            $return['error'] = 'funds';
            $return['newform_type'] = 'prj_accept_offer';
            $return['difference'] = $totalprice-$ubalance;
            $return['payment_id'] = $pidb;
          }
        }
      }
    }
  }
  echo json_encode($return);
  exit;
}

if($redirect || (!$is_ajax && !COT_AJAX)) {
  cot_redirect(cot_url('plug', 'e=marketorders&m=order&id=' . $orderId . ($is_admin ? '&is_admin=1' : ''), '', true));
} else {
  echo ($return_json ? json_encode($return) : $return);
}