<?php

/**
 * marketorders plugin
 *
 * @package marketorders
 * @version 1.0.0
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru
 * @license BSD
 */

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

$id = cot_import('id', 'G', 'INT');
$key = cot_import('key', 'G', 'TXT');
$is_admin = (($usr['maingrp'] == 5 || $usr['maingrp'] == 9) && cot_import('is_admin', 'G', 'INT') == 1) ? true : false;

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('plug', 'marketorders');
cot_block($usr['auth_read']);
$usr['isadmin'] = $is_admin;

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

if ($id > 0)
{
	$sql = $db->query("SELECT * FROM $db_market_orders  AS o
		LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
		WHERE order_status!='new' AND order_id=".$id." LIMIT 1");
}

if (!$id || !$sql || $sql->rowCount() == 0)
{
	cot_die_message(404, TRUE);
}
$marketorder = $sql->fetch();

cot_block($usr['isadmin'] || $usr['id'] == $marketorder['order_userid'] || $usr['id'] == $marketorder['order_seller'] || $usr['id'] == 0);

/* === Hook === */
$extp = cot_getextplugins('marketorders.order.first');
foreach ($extp as $pl)
{
	include $pl;
}
/* ===== */

$out['subtitle'] = ($is_admin ? 'Администрирование заказа #' : 'Статус заказа #').$marketorder['order_id'];
$out['head'] .= $R['code_noindex'];

$mskin = cot_tplfile(array('marketorders', 'order', ($is_admin ? 'admin' : ($marketorder['order_seller'] == $usr['id'] ? 'seller' : 'payer')), $structure['market'][$marketorder['item_cat']]['tpl']), 'plug');

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

$t = new XTemplate($mskin);

$t->assign(array(
	"BREADCRUMBS" => $catpath,
));

// Error and message handling
cot_display_messages($t);

if($marketorder['order_pid'] > 0) {
  $t->assign(cot_generate_markettags($marketorder['order_pid'], 'ORDER_PRD_', $cfg['market']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));
} else {
  $t->assign(array(
    'ORDER_PRD_ID' => 0
  ));
}

$utags = array(
  'seller' => cot_generate_usertags($marketorder['order_seller'], 'ORDER_SELLER_'),
  'payer' => cot_generate_usertags($marketorder['order_userid'], 'ORDER_CUSTOMER_')
);
$t->assign($utags['seller']);
$t->assign($utags['payer']);

$costplan = (!empty($marketorder['order_catcostplans']) ? json_decode($marketorder['order_catcostplans'],1) : array(
  'package' => 'single',
  'extras' => array(
    'single' => array(
      'title' => '',
      'time' => 1,
      'count' => 1,
      'price' => $marketorder['order_cost']
    )
  )
));

$costplan['itog'] = array(
  'time' => 0,
  'price' => $marketorder['order_cost']
);

$item_cache = $costplan['item_cache'];
unset($costplan['item_cache']);
if(!$marketorder['item_id'] && is_array($item_cache)) {
  //$marketorder = array_merge($marketorder, $item_cache);
}

if($costplan['package'] == 'single') {
  require_once cot_incfile('catcostplans', 'plug');

  $costplan['info'] = $costplan['extras']['single'];
  if($costplan['info']['time'] > 0) {
    $costplan['itog']['time'] = $costplan['info']['time']*($costplan['info']['count'] > 0 ? $costplan['info']['count'] : 1);
  } else {
    $costplan['itog']['time'] = $costplan['info']['count']*0.5;
    $costplan['itog']['time'] = ($costplan['itog']['time'] > 0 ? round($costplan['itog']['time'], 0) : 1);
  }

  $costplan['extras']['selected_notinorder'] = array();

  foreach($costplan['extras']['selected'] as $select) {
    $cpext = array(
      'id' => $select['id'],
      'name' => $select['name'],
      'hint' => '',
      'type' => 'bool',
      'can_lower' => 0,
      'count' => $select['count'],
      'time' => $select['duration'],
      'time_format' => ($select['duration'] > 0 ? cot_declension($select['duration'], 'день,дня,дней') : '-'),
      'cost' => $select['payerPrice'],
      'cost_seller' => cot_mk_cost_crt($select['payerPrice'], 'seller', $marketorder['order_tax']),
      'cost_dodji' => $select['payerPriceDodji'],
      'cost_dodji_seller' => cot_mk_cost_crt($select['payerPriceDodji'], 'seller', $marketorder['order_tax']),
    );

    $costplan['itog']['time'] += $select['duration']*$select['count'];
    $cpext['opt_type'] = 'category';
    $cpext['select'] = 1;

    if($select['count'] > 0) {
      $t->assign("CP_ROW", $cpext);
      $t->parse('MAIN.ORDER_CP_ROW');
      $t->parse('MAIN.CP_JSON');
    }
    if($marketorder['order_status'] != 'cancel' && $marketorder['order_status'] != 'done' && $marketorder['order_status'] != 'claim') {
      $cost = $select['payerPrice'];

      if($select['priceId'] > 0 && $costplans_prices[$select['priceId']] > 0) {
        $cost = $costplans_prices[$select['priceId']];
      }

      $priceselect = '';
      for($i=1;$i<=10;$i++) {
        $priceselect .= '<option value="'.$i.'">'.$i.' ('.number_format(round($cost * $i), 0, '', ' ').' Р)</option>';
      }
      $cpext['priceselect'] = $priceselect;

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

      $t->assign("CP_ROW", $cpext);
      $t->parse('MAIN.CP_NINORD.ORDER_CP_NINORD_ROW');
    }
  }

  if(is_array($costplan['extras']['selected_custom']) && count($costplan['extras']['selected_custom']) > 0) foreach($costplan['extras']['selected_custom'] as $select) {
    $cpext = array(
      'id' => $select['id'],
      'name' => $select['name'],
      'hint' => '',
      'type' => 'bool',
      'can_lower' => 0,
      'count' => $select['count'],
      'time' => $select['time'],
      'time_format' => ($select['time'] > 0 ? cot_declension($select['time'], 'день,дня,дней') : '-'),
      'cost' => $select['payerPrice'],
      'cost_seller' => cot_mk_cost_crt($select['payerPrice'], 'seller', $marketorder['order_tax']),
      'cost_dodji' => $select['payerPriceDodji'],
      'cost_dodji_seller' => cot_mk_cost_crt($select['payerPriceDodji'], 'seller', $marketorder['order_tax']),
    );

    $costplan['itog']['time'] += $select['time']*$select['count'];
    $cpext['opt_type'] = 'custom_addextra';
    $cpext['select'] = 1;

    if($select['count'] > 0) {
      $t->assign("CP_ROW", $cpext);
      $t->parse('MAIN.ORDER_CP_ROW');
    }
  }

  $costplan['extras']['selected_notinorder_cnt'] = count($costplan['extras']['selected_notinorder']);
  if($marketorder['order_status'] != 'cancel' && $marketorder['order_status'] != 'done' && $marketorder['order_status'] != 'claim' && $marketorder['order_status'] != 'check') {
    if($usr['id'] == $marketorder['order_seller'] || $costplan['extras']['selected_notinorder_cnt'] > 0) {
      $t->assign("CP_NINORD_CNT", $costplan['extras']['selected_notinorder_cnt']);
      $t->parse('MAIN.CP_NINORD');
    }
  }
} else {
  $costplan['info'] = $costplan['extras']['info'];
  if($costplan['info']['time'] > 0) {
    $costplan['itog']['time'] = $costplan['info']['time']*($costplan['info']['count'] > 0 ? $costplan['info']['count'] : 1);
  } else {
    $costplan['itog']['time'] = $costplan['info']['count']*0.5;
    $costplan['itog']['time'] = ($costplan['itog']['time'] > 0 ? round($costplan['itog']['time'], 0) : 1);
  }

  $checkcat = ($marketorder['item_id'] > 0 ? (!empty($marketorder['item_catattr']) ? $marketorder['item_catattr'] : $marketorder['item_cat']) : (!empty($item_cache['item_catattr']) ? $item_cache['item_catattr'] : $item_cache['item_cat']));

  if(!empty($checkcat)) {
    $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='".$checkcat."' LIMIT 1")->fetch();

    if($catsql['structure_id'] > 0) {
      require_once cot_incfile('catcostplans', 'plug');

      $plan = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='market' AND p_catid=".$catsql['structure_id']." LIMIT 1")->fetch();
      $jj=0;
      while($jj < 5 && !$plan['p_id'] && $structure['market'][$catsql['structure_code']]['parent'] != $catsql['structure_code']) {
        $catsql = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='".$structure['market'][$catsql['structure_code']]['parent']."' LIMIT 1")->fetch();
        if($catsql['structure_id'] > 0) {
          $plan = $db->query("SELECT * FROM $db_catcostplans WHERE p_area='market' AND p_catid=".$catsql['structure_id']." LIMIT 1")->fetch();
        }
        $jj++;
      }

      if($plan['p_id'] > 0) {
        $options = $db->query("SELECT * FROM $db_catcostplans_attrs WHERE at_planid=".$plan['p_id']." ORDER BY at_id ASC")->fetchAll();

        if($plan['p_onlyprice'] == 1 && $structure['market'][$catsql['structure_code']]['parent'] != $catsql['structure_code']) {
          $parent = $db->query("SELECT * FROM $db_structure WHERE structure_area='market' AND structure_code='" . $structure['market'][$catsql['structure_code']]['parent'] . "' LIMIT 1")->fetch();
          if($parent['structure_id'] > 0 && $parent['structure_id'] != $catsql['structure_id']) $options = get_catcostplans_parent_attrs($parent, 'market', $plan['p_bl_attrs'], $options);
        }

        foreach($options as $otp) {
          foreach($costplan['extras']['selected']['category'] as $select) {
            if($otp['at_id'] == $select['item_id']) {
              $cpext = array(
                'id' => $otp['at_id'],
                'name' => $otp['at_title'],
                'hint' => $otp['at_hint'],
                'type' => ($otp['at_type'] ? 'text' : 'bool'),
                'can_lower' => $otp['at_can_lower'],
                'count' => 1,
                'time' => 0,
                'time_format' => '-',
                'cost' => 0,
              );

              $otp['opt_type'] = 'category';
              $otp['select'] = $select['value'];
              $t->assign("CP_ROW", $cpext);

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

  if(is_array($costplan['customBundleExtras'])) foreach($costplan['customBundleExtras'] as $cpext) {
    foreach($costplan['extras']['selected']['custom'] as $select) {
      if($cpext['id'] == $select['item_id']) {
        $cpext['opt_type'] = 'custom';
        $cpext['select'] = $select['value'];
        $cpext['count'] = 1;
        $cpext['time'] = 0;
        $cpext['time_format'] = '-';
        $cpext['cost'] = 0;

        $t->assign("CP_ROW", $cpext);

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

  if(is_array($costplan['extras']['selected_custom']) && count($costplan['extras']['selected_custom']) > 0) foreach($costplan['extras']['selected_custom'] as $select) {
    $cpext = array(
      'id' => $select['id'],
      'name' => $select['name'],
      'hint' => '',
      'type' => 'bool',
      'can_lower' => 0,
      'count' => $select['count'],
      'time' => $select['time'],
      'time_format' => ($select['time'] > 0 ? cot_declension($select['time'], 'день,дня,дней') : '-'),
      'cost' => $select['payerPrice'],
      'cost_seller' => cot_mk_cost_crt($select['payerPrice'], 'seller', $marketorder['order_tax']),
      'cost_dodji' => $select['payerPriceDodji'],
      'cost_dodji_seller' => cot_mk_cost_crt($select['payerPriceDodji'], 'seller', $marketorder['order_tax']),
    );

    $costplan['itog']['time'] += $select['time']*$select['count'];
    $cpext['opt_type'] = 'custom_addextra';
    $cpext['select'] = 1;

    if($select['count'] > 0) {
      $t->assign("CP_ROW", $cpext);
      $t->parse('MAIN.ORDER_CP_ROW');
    }
  }
}

if(!$costplan['itog']['time']) $costplan['itog']['time'] = 1;

if($marketorder['order_deadline'] != ($costplan['itog']['time']*86400)) {
  $marketorder['order_deadline'] = $costplan['itog']['time']*86400;
  $db->update($db_market_orders, array('order_deadline' => $marketorder['order_deadline']), 'order_id='.$marketorder['order_id']);
}

$orderstatus = array(
  'title' => 'На согласовании',
  'class' => '',
  'hint' => ($marketorder['order_seller'] == $usr['id'] ? '' : ''),
  'icon' => 'ico-prd-25'
);

$queuecnt = cot_mk_queue_cnt($marketorder);
$queuemsg = cot_mk_queue_text($marketorder, $queuecnt, ($marketorder['order_seller'] == $usr['id'] ? 'seller' : 'payer'));

switch($marketorder['order_status'])
{
	case 'paid':
    if($marketorder['order_accept'] > 0) {
		  $orderstatus['title'] = 'Принят продавцом';
      $orderstatus['hint'] = '';
    } else {
  		$orderstatus['title'] = 'На согласовании';
      $orderstatus['hint'] = '';
    }
		break;

	case 'done':
    $orderstatus['icon'] = 'ico-check-circle';
    $orderstatus['class'] = 'color-light-green';
		$orderstatus['title'] = 'Выполнен';
    if($marketorder['order_status_code'] == 'autodone') {
      $orderstatus['hint'] = 'Заказ принят автоматически';
    } else {
      $orderstatus['hint'] = ($marketorder['order_userid'] == $usr['id'] ? 'Вы проверили и приняли работу' : 'Покупатель проверил и принял работу');
    }
		break;

	case 'claim':
		$orderstatus['title'] = 'Арбитраж';
    $orderstatus['hint'] = 'Заказ проверяется модератором';
		break;

	case 'cancel':
		$orderstatus['title'] = 'Отменен';
    $orderstatus['hint'] = $marketorders_status_codes[$marketorder['order_status_code']]['track_'.($marketorder['order_userid'] == $usr['id'] ? 'cust' : 'perf')];
		break;

	case 'queue':
    if($marketorder['order_accept'] > 0) {
      if($queuecnt > 0) {
    		$orderstatus['title'] = 'В очереди';
        $orderstatus['hint'] = '';
      } else {
		    $orderstatus['title'] = 'Принят продавцом';
        $orderstatus['hint'] = '';
      }
    } elseif($queuecnt > 0) {
  		$orderstatus['title'] = 'В очереди';
      $orderstatus['hint'] = '';
    }
		break;

	case 'start':
    $orderstatus['title'] = 'В работе';
    if($marketorder['order_seller'] != $usr['id']) $orderstatus['hint'] = 'Продавец приступил к работе над заказом';
		break;

	case 'check':
		$orderstatus['title'] = 'На проверке';
    $orderstatus['hint'] = ($marketorder['order_userid'] == $usr['id'] ? 'Вы отправили работу на проверку' : 'Продавец отправил работу на проверку');
		break;
}

$cancelResons = cot_mk_cancel_reasons($marketorder, ($marketorder['order_seller'] == $usr['id'] ? 'seller' : 'payer'));

$deadline = array(
  'time' => 0,
  'date' => 0,
  'ago' => '',
  'hint' => '',
  'hasCountbox' => 'false'
);
if(!$marketorder['order_cancel'] && !$marketorder['order_cancel_perf'] && $marketorder['order_status'] != 'check' && $marketorder['order_status'] != 'done') {
  if($marketorder['order_sendinstr'] > 0 && !$marketorder['order_accept']) {
    $deadline['time'] = 86400 - ($sys['now'] - $marketorder['order_sendinstr']);
    $deadline['hint'] = 'Оставшееся время на принятие заказа продавцом';
  } elseif($marketorder['order_sendinstr'] > 0 && $marketorder['order_accept'] > 0 && $marketorder['order_queue'] > 0 && !$marketorder['order_start']) {
    $deadline['time'] = 86400 - ($sys['now'] - $marketorder['order_queue']);
    $deadline['hint'] = 'Оставшееся время начала работы по заказу';
  } elseif($marketorder['order_start'] > 0) {
    if($marketorder['order_check'] > 0) {
      $deadline['hint'] = 'Время выполнения заказа';
      $deadline['time'] = $marketorder['order_check'] - $marketorder['order_start'];
    } else {
      $deadline['time'] = $marketorder['order_deadline'] - ($sys['now'] - $marketorder['order_start']);
      if($marketorder['order_worktime'] > 0) $deadline['time'] -= $marketorder['order_worktime'];
      if($deadline['time'] < 0) $deadline['time'] = 0;
      $deadline['hint'] = 'Оставшееся время выполнения заказа';
      $deadline['hasCountbox'] = 'true';
    }
  }
}
if($deadline['time'] > 0) {
  $deadline['date'] += $deadline['time'] + $sys['now'];
  $deadline['ago'] = cot_build_timegap($sys['now']-$deadline['time']);
}

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

$t->assign(array(
  "MK_COST_CTR_SIMPLE" => cot_mk_cost_crt(500, 'seller', $marketorder['order_tax']),
	"ORDER_ID" => $marketorder['order_id'],
  "ORDER_ITEM_ID" => $marketorder['item_id'],
	"ORDER_COUNT" => $marketorder['order_count'],
	"ORDER_COST" => $marketorder['order_cost'],
  "ORDER_COST_DODJI" => $marketorder['order_cost_dodji'],
	"ORDER_TITLE" => $marketorder['order_title'],
	"ORDER_TEXT" => $marketorder['order_text'],
	"ORDER_EMAIL" => $marketorder['order_email'],
  "ORDER_PAID" => $marketorder['order_paid'],
  "ORDER_ACCEPT" => $marketorder['order_accept'],
  "ORDER_START" => $marketorder['order_start'],
	"ORDER_DONE" => $marketorder['order_done'],
  "ORDER_CANCEL" => $marketorder['order_cancel'],
  "ORDER_CANCEL_PERF" => $marketorder['order_cancel_perf'],
  "ORDER_SENDINSTR" => $marketorder['order_sendinstr'],
	"ORDER_STATUS" => $marketorder['order_status'],
  //"ORDER_FOLIO" => ((!empty($marketorder['order_folio']) && file_exists($marketorder['order_folio'])) ? $marketorder['order_folio'] : ''),
  "ORDER_COSTPLAN" => $costplan,
  "ORDER_STATUSARR" => $orderstatus,
	"ORDER_LOCALSTATUS" => $L['marketorders_status_'.$marketorder['order_status']],
	"ORDER_DEADLINE" => $deadline,
  "ORDER_CUEUECNT" => $queuecnt,
  "ORDER_STEPS" => $order_steps,
  "ORDER_STEPS_LOCK" => false, //todo
  "ORDER_LOWRATING" => $marketorder['order_lowrating'],
  "ORDER_DATA_CANSELRESONS" => $cancelResons,
  "ORDER_DATA_CANCANCEL_PAYER" => cot_mk_cancel_reasons($marketorder, 'payer', '', true),
  "ORDER_DATA_CANCANCEL_SELLER" => cot_mk_cancel_reasons($marketorder, 'seller', '', true),
  "ORDER_DATA_CANSTART_SELLER" => ((in_array($marketorder['order_status'], array('paid', 'queue')) && $marketorder['order_accept'] > 0) ? 1 : 0),
  "ORDER_DATA_CANCHECK_SELLER" => (($marketorder['order_status'] == 'start' && !$marketorder['order_cancel_perf']) ? 1 : 0),
  "ORDER_DATA_CANADDSTEPS_SELLER" => ($deadline['time'] > 0 && $deadline['time'] > 86400 && (in_array($marketorder['order_status'], array('start')) && count($order_steps) == 0) ? 1 : 0),
  "ORDER_DATA_CANEDITSTEPS_SELLER" => ((in_array($marketorder['order_status'], array('start')) && count($order_steps) > 0) ? 1 : 0),
  "ORDER_DATA_CANSETSTEPS_SELLER" => ((in_array($marketorder['order_status'], array('start', 'check')) && count($order_steps) > 0) ? 1 : 0),
  "ORDER_DATA_ADMIN_ALERTREZRVSUMM" => (!empty($marketorder['order_status_code']) && in_array($marketorder['order_status_code'], array('payer_worker_cannot_execute_correct', 'payer_do_not_like_this_worker', 'payer_no_communication_with_worker', 'payer_other_no_guilt')) ? 1 : 0)
));

$market_files = array();

$extpl1 = cot_getextplugins('marketorders.order.track.loop');
$track_loop = cot_incfile('marketorders', 'plug', 'track_loop');

$fmsg = false;
$mktrack = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$marketorder['order_id'].' AND t_touser='.($marketorder['order_seller'] == $usr['id'] ? $marketorder['order_seller'] : $marketorder['order_userid']).' ORDER BY t_date ASC')->fetchAll();

$mktrack_limit = 10;
$mktrack_cnt = count($mktrack);
$jj = 0;
foreach($mktrack as $mkt) {
  $jj++;
  include $track_loop;
}

$t->assign(array(
	"MKTRACK_CNT" => $jj,
));

if($is_admin) {
  $pay_codes = array(
    'ds_accept_mkorder' => array(),
    'prj_accept_offer' => array(),
  );

  require_once cot_incfile('ds', 'module');
  $paysql = $db->query("SELECT p.pay_id, m.mtype, m.mdata FROM $db_ds_msg as m
    LEFT JOIN $db_payments as p ON m.id=p.pay_code
      WHERE p.pay_userid=".$marketorder['order_userid']." AND p.pay_status='done'
            AND m.fruser=".$marketorder['order_seller'].' AND m.touser='.$marketorder['order_userid'].' AND (m.mtype=2 OR m.mtype=3) ORDER BY m.date DESC')->fetchAll();
  foreach($paysql as $val) {
    $mdata = cot_ds_get_mdata($val['mtype'], $val['mdata']);
    if($mdata['orderId'] > 0 && $mdata['orderId'] == $marketorder['order_id']) {
      $pay_codes['ds_accept_mkorder'][] = $val['pay_id'];
    }
  }

  require_once cot_incfile('projects', 'module');
  $paysql = $db->query("SELECT p.pay_id, o.offer_json FROM $db_projects_offers as o
    LEFT JOIN $db_payments as p ON o.offer_id=p.pay_code
      WHERE p.pay_userid=".$marketorder['order_userid']." AND p.pay_status='done'
            AND o.offer_userid=".$marketorder['order_seller'].' ORDER BY o.offer_date DESC')->fetchAll();

  foreach($paysql as $val) {
    $mdata = (!empty($val['offer_json']) ? json_decode($val['offer_json'], 1) : array());
    if(!is_array($mdata)) $mdata = array();

    if($mdata['orderId'] > 0 && $mdata['orderId'] == $marketorder['order_id']) {
      $pay_codes['prj_accept_offer'][] = $val['pay_id'];
    }
  }

  $pays = $db->query("SELECT * FROM $db_payments
		  WHERE (pay_userid=" . $marketorder['order_userid'] . " OR pay_userid=" . $marketorder['order_seller'] . ") AND pay_status='done'
      AND (
          (pay_code='market_reftocust_emptyitem:".$marketorder['order_id']."' OR pay_code='market_code:".$marketorder['order_id']."')
       OR (pay_code='market_code_done:".$marketorder['order_id']."' OR pay_code='market_code_autodone:".$marketorder['order_id']."')
       OR ((pay_area='market_payorder' OR pay_area='market_payaddextras' OR pay_area='market_accept_seller_payaddextras' OR pay_area='market_arbitrage') AND pay_code='".$marketorder['order_id']."')
       OR (pay_code='market_code_arbitrage_payer:".$marketorder['order_id']."' OR pay_code='market_code_arbt:".$marketorder['order_id']."' OR pay_code='market_code_arbitrage_seller:".$marketorder['order_id']."' OR pay_code='market_code_arbtdone:".$marketorder['order_id']."')
       ".(count($pay_codes['ds_accept_mkorder']) > 0 ? "OR (pay_area='ds_accept_mkorder' AND (pay_id='".implode("' OR pay_id='", $pay_codes['ds_accept_mkorder'])."'))" : '')."
       ".(count($pay_codes['prj_accept_offer']) > 0 ? "OR (pay_area='prj_accept_offer' AND (pay_id='".implode("' OR pay_id='", $pay_codes['prj_accept_offer'])."'))" : '')."
      )
		  ORDER BY pay_pdate ASC")->fetchAll();

	/* === Hook === */
	$extp = cot_getextplugins('payments.balance.history.loop');
	/* ===== */

  $balance_history_loop_admin = true;

  $pjj=0;
	foreach ($pays as $pay)
	{
    $pjj++;
    $t->assign(cot_generate_usertags($pay['pay_userid'], 'HIST_ROW_OWNER_'));
    $t->assign(cot_generate_paytags($pay, 'HIST_ROW_'));

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

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

  if($pjj > 0) $t->parse('MAIN.ORDPAYS_BLOCK');
}

$t->assign(array(
	"ORDER_ALL_FILES" => $market_files,
));

/*
		// Отменяем заказ, возвращаем оплату покупателю
		if($a == 'acceptclaim')
		{
			$rorder['order_cancel'] = $sys['now'];
			$rorder['order_status'] = 'cancel';

			if($db->update($db_market_orders, $rorder, 'order_id='.$id))
			{
				if($marketorder['order_userid'] > 0)
				{
					$payinfo['pay_userid'] = $marketorder['order_userid'];
					$payinfo['pay_area'] = 'balance';
					$payinfo['pay_code'] = 'market:'.$marketorder['order_id'];
					$payinfo['pay_summ'] = $marketorder['order_cost'];
					$payinfo['pay_cdate'] = $sys['now'];
					$payinfo['pay_pdate'] = $sys['now'];
					$payinfo['pay_adate'] = $sys['now'];
					$payinfo['pay_status'] = 'done';
					$payinfo['pay_desc'] = cot_rc($L['marketorders_claim_payments_customer_desc'], 
						array(
							'product_title' => $marketorder['item_title'],
							'order_id' => $marketorder['order_id']
						)
					);

					$db->insert($db_payments, $payinfo);
				}
				
				$seller = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_seller'])->fetch();
				
				if($marketorder['order_userid'] > 0)
				{
					$customer = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'])->fetch();
				}
				else
				{
					$customer['user_name'] = $marketorder['order_email'];
					$customer['user_email'] = $marketorder['order_email'];
				}
				
				// Уведопляем продавца об отмене заказа
				$rsubject = cot_rc($L['marketorders_acceptclaim_mail_toseller_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
				$rbody = cot_rc($L['marketorders_acceptclaim_mail_toseller_body'], array(
					'product_id' => $marketorder['item_id'],
					'product_title' => $marketorder['item_title'],
					'order_id' => $marketorder['order_id'],	
					'sitename' => $cfg['maintitle'],
					'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
				));
				cot_mail ($seller['user_email'], $rsubject, $rbody);

				// Уведопляем покупателя об отмене заказа
				$rsubject = cot_rc($L['marketorders_acceptclaim_mail_tocustomer_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
				$rbody = cot_rc($L['marketorders_acceptclaim_mail_tocustomer_body'], array(
					'product_id' => $marketorder['item_id'],
					'product_title' => $marketorder['item_title'],
					'order_id' => $marketorder['order_id'],	
					'sitename' => $cfg['maintitle'],
					'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
				));

				cot_mail ($customer['user_email'], $rsubject, $rbody);

				cot_redirect(cot_url('marketorders', 'm=order&id=' . $id, '', true));
				exit;
			}
			
			cot_redirect(cot_url('marketorders', 'm=order&id=' . $id, '', true));
			exit;
		}
		
		// Отменяем жалобу
		if($a == 'cancelclaim')
		{
			$rorder['order_claim'] = 0;
			$rorder['order_status'] = 'paid';

			if($db->update($db_market_orders, $rorder, 'order_id='.$id))
			{
				$customer = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'])->fetch();
				
				// Уведопляем покупателя об отклонении жалобы
				$rsubject = cot_rc($L['marketorders_cancelclaim_mail_tocustomer_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
				$rbody = cot_rc($L['marketorders_cancelclaim_mail_tocustomer_body'], array(
					'product_title' => $marketorder['item_title'],
					'order_id' => $marketorder['order_id'],	
					'sitename' => $cfg['maintitle'],
					'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
				));

				cot_mail ($customer['user_email'], $rsubject, $rbody);
			}
			
			cot_redirect(cot_url('marketorders', 'm=order&id=' . $id, '', true));
			exit;
		}
		
		$t->parse('MAIN.CLAIM.ADMINCLAIM');
	}
	$t->parse('MAIN.CLAIM');
}
*/

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