<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=payments.balance.history.loop
 * [END_COT_EXT]
 */

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

if(in_array($pay['pay_area'], array('ds_accept_mkorder', 'prj_accept_offer', 'market_payorder', 'market_payaddextras', 'market_accept_seller_payaddextras', 'market_arbitrage'))
  || (strrpos($pay['pay_code'], ':') !== false
      && (
          strrpos($pay['pay_code'], 'market_reftocust_emptyitem:') !== false
       || strrpos($pay['pay_code'], 'market_code:') !== false
       || strrpos($pay['pay_code'], 'market_code_done:') !== false
       || strrpos($pay['pay_code'], 'market_code_autodone:') !== false

       /* арбитраж */
       || strrpos($pay['pay_code'], 'market_code_arbitrage_payer:') !== false
       || strrpos($pay['pay_code'], 'market_code_arbt:') !== false
       || strrpos($pay['pay_code'], 'market_code_arbitrage_seller:') !== false
       || strrpos($pay['pay_code'], 'market_code_arbtdone:') !== false
       /* арбитраж */

       || $pay['pay_code'] == 'market_reftocust_emptycart'
      )
    )
  )
{
  //$pay['pay_desc'] = '';
  require_once cot_incfile('marketorders', 'plug');

  $pay['pay_label_hint'] = '';

  if($pay['pay_code'] == 'market_reftocust_emptycart') {
    $pay['pay_desc'] = 'Возврат средств, из за ошибки оплаты '.cot_sitename('padeg', 'r').' из корзины';
  } elseif(strrpos($pay['pay_code'], 'market_reftocust_emptyitem:') !== false) {
    $paycode = explode(':', $pay['pay_code']);

    $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Возврат средств по некорректному заказу "'.$pay['pay_desc'].'"' : 'Возврат средств по некорректному заказу');

    if(!$balance_history_loop_admin && $paycode[1] > 0) {
      $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_userid=".$usr['id']." AND order_id=".$paycode[1])->fetch();
      if($marketorder['order_id'] > 0) {
				$urlparams = empty($marketorder['item_alias']) ?
					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

        $pay['pay_desc'] = 'Возврат средств по некорректному заказу';
        $pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['item_title'].'</a>' : (!empty($marketorder['order_title']) ? ' '.$marketorder['order_title'] : ''));
      }
    }
  } elseif(strrpos($pay['pay_code'], 'market_code_done:') !== false || strrpos($pay['pay_code'], 'market_code_autodone:') !== false || strrpos($pay['pay_code'], 'market_code_arbtdone:') !== false) {
    $paycode = explode(':', $pay['pay_code']);

    $pay['pay_label_hint'] = 'Средства переведены на ваш счет';

    if($paycode[0] == 'market_code_arbt') {
      $pay['pay_label_hint'] .= ', по решению арбитража';
    }

    $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Получение оплаты за заказ "'.$pay['pay_desc'].'"' : 'Получение оплаты за заказ');

    if(!$balance_history_loop_admin && $paycode[1] > 0) {
      $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_seller=".$usr['id']." AND order_id=".$paycode[1])->fetch();

      if($marketorder['order_id'] > 0) {
        $payer = ($marketorder['order_userid'] > 0 ? $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'].' LIMIT 1')->fetch() : array());

        $pay['pay_desc'] = 'Получение оплаты';
        if($payer['user_id'] > 0) $pay['pay_desc'] .= ' от покупателя <a class="purse-history-link" href="'.cot_url('users', 'm=details&u='.$payer['user_name']).'">'.$payer['user_name'].'</a>';

        //$pay['pay_desc'] .= ' за заказ '.($marketorder['item_id'] > 0 ? '<a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['item_title'].'</a>' : (!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
        $pay['pay_desc'] .= ' за '.($marketorder['order_id'] > 0 ? '<a href="'.cot_url('plug', 'e=marketorders&m=order&id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказ #'.$marketorder['order_id'].'</a>' : 'заказ '.(!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
      }
    }
  } elseif(strrpos($pay['pay_code'], 'market_code:') !== false || strrpos($pay['pay_code'], 'market_code_arbt:') !== false) {
    $paycode = explode(':', $pay['pay_code']);

    if($paycode[0] == 'market_code_arbt') {
      $pay['pay_label_hint'] = 'По решению арбитража';
    }
    $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Возврат средств по заказу "'.$pay['pay_desc'].'"' : 'Возврат средств по заказу');

    if(!$balance_history_loop_admin && $paycode[1] > 0) {
      $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_userid=".$usr['id']." AND order_id=".$paycode[1])->fetch();
      if($marketorder['order_id'] > 0) {

        //$pay['pay_desc'] = 'Возврат средств по заказу';
        //$pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['item_title'].'</a>' : (!empty($marketorder['order_title']) ? ' '.$marketorder['order_title']: ''));
        $pay['pay_desc'] = 'Возврат средств';
        $pay['pay_desc'] .= ' по '.($marketorder['order_id'] > 0 ? '<a href="'.cot_url('plug', 'e=marketorders&m=order&id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказу #'.$marketorder['order_id'].'</a>' : 'заказу '.(!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
        $pay['pay_label_hint'] = $marketorders_status_codes[$marketorder['order_status_code']]['balance'];
      }
    }
  } elseif(strrpos($pay['pay_code'], 'market_code_arbitrage_payer:') !== false) {
    $paycode = explode(':', $pay['pay_code']);

    $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Частичный возврат средств по заказу "'.$pay['pay_desc'].'"' : 'Частичный возврат средств по заказу');

    if(!$balance_history_loop_admin && $paycode[1] > 0) {
      $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_userid=".$usr['id']." AND order_id=".$paycode[1])->fetch();
      if($marketorder['order_id'] > 0) {
				$urlparams = empty($marketorder['item_alias']) ?
					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

        //$pay['pay_desc'] = 'Частичный возврат средств по заказу';
        //$pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['item_title'].'</a>' : (!empty($marketorder['order_title']) ? ' '.$marketorder['order_title']: ''));
        $pay['pay_desc'] = 'Частичный возврат средств';
        $pay['pay_desc'] .= ' по '.($marketorder['order_id'] > 0 ? '<a href="'.cot_url('plug', 'e=marketorders&m=order&id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказу #'.$marketorder['order_id'].'</a>' : 'заказу '.(!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
        $pay['pay_label_hint'] = $marketorders_status_codes[$marketorder['order_status_code']]['balance'];
      }
    }
  } elseif(strrpos($pay['pay_code'], 'market_code_arbitrage_seller:') !== false) {
    $paycode = explode(':', $pay['pay_code']);

    $pay['pay_label_hint'] = 'Частичное получение оплаты за заказ, по решению арбитража';

    $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Частичное получение оплаты за заказ "'.$pay['pay_desc'].'"' : 'Частичное получение оплаты за заказ');

    if(!$balance_history_loop_admin && $paycode[1] > 0) {
      $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_seller=".$usr['id']." AND order_id=".$paycode[1])->fetch();

      if($marketorder['order_id'] > 0) {
        $payer = ($marketorder['order_userid'] > 0 ? $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'].' LIMIT 1')->fetch() : array());

        $pay['pay_desc'] = 'Частичное получение оплаты';
        if($payer['user_id'] > 0) $pay['pay_desc'] .= ' от покупателя <a class="purse-history-link" href="'.cot_url('users', 'm=details&u='.$payer['user_name']).'">'.$payer['user_name'].'</a>';

        //$pay['pay_desc'] .= ' за заказ '.($marketorder['order_id'] > 0 ? '<a href="'.cot_url('plug', 'e=marketorders&m=order&id='.$marketorder['order_id'], '', true).'" class="purse-history-link">'.$marketorder['order_title'].'</a>' : (!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
        $pay['pay_desc'] .= ' за '.($marketorder['order_id'] > 0 ? '<a href="'.cot_url('plug', 'e=marketorders&m=order&id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказ #'.$marketorder['order_id'].'</a>' : 'заказ '.(!empty($marketorder['order_title']) ? $marketorder['order_title'] : ''));
      }
    }
  } else {
  	switch ($pay['pay_area'])
  	{
  		case 'ds_accept_mkorder':
        require_once cot_incfile('ds', 'module');
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Оплата заказа "Удалено"' : 'Оплата заказа');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 0) {
          $dsmsg = $db->query("SELECT * FROM $db_ds_msg WHERE id=".$pay['pay_code'].' AND touser='.$usr['id'].' AND (mtype=2 OR mtype=3) LIMIT 1')->fetch();
          $mdata = cot_ds_get_mdata($dsmsg['mtype'], $dsmsg['mdata']);
          if($mdata['orderId'] > 0) {
            $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
        			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
        			WHERE order_userid=".$usr['id']." AND order_id=".$mdata['orderId'])->fetch();
            if($marketorder['order_id'] > 0) {
      				$urlparams = empty($marketorder['item_alias']) ?
      					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
      					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
      				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

              $pay['pay_desc'] = 'Оплата <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказа #'.$marketorder['order_id'].'</a>';
              $pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' по '.cot_sitename('padeg', 'd').' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['order_title'].'</a>' : (!empty($marketorder['order_title']) ? ' по '.cot_sitename('padeg_individ', 'd').' "'.$marketorder['order_title'].'"' : ''));
            }
          }
        }
  			break;
  		case 'prj_accept_offer':
        require_once cot_incfile('projects', 'module');
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Оплата заказа "Удалено"' : 'Оплата заказа');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 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=".$pay['pay_code'].' AND item_userid='.$usr['id'].' LIMIT 1')->fetch();

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

          if($mdata['orderId'] > 0) {
            $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
        			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
        			WHERE order_userid=".$usr['id']." AND order_id=".$mdata['orderId'])->fetch();
            if($marketorder['order_id'] > 0) {
      				$urlparams = empty($marketorder['item_alias']) ?
      					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
      					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
      				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

              $pay['pay_desc'] = 'Оплата <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказа #'.$marketorder['order_id'].'</a>';
              $pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' по '.cot_sitename('padeg', 'd').' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['order_title'].'</a>' : (!empty($marketorder['order_title']) ? ' по '.cot_sitename('padeg_individ', 'd').' "'.$marketorder['order_title'].'"' : ''));
            }
          }
        }
  			break;
  		case 'market_payorder':
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Оплата заказа "Удалено"' : 'Оплата заказа');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 0) {
          $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
      			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
      			WHERE order_userid=".$usr['id']." AND order_id=".$pay['pay_code'])->fetch();
          if($marketorder['order_id'] > 0) {
    				$urlparams = empty($marketorder['item_alias']) ?
    					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
    					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
    				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

            $pay['pay_desc'] = 'Оплата <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказа #'.$marketorder['order_id'].'</a>';
            $pay['pay_desc'] .= ($marketorder['item_id'] > 0 ? ' по '.cot_sitename('padeg', 'd').' <a href="'.cot_url('market', $urlparams, '', true).'" class="purse-history-link">'.$marketorder['item_title'].'</a>' : (!empty($marketorder['order_title']) ? ' по '.cot_sitename('padeg', 'd').' '.$marketorder['order_title']: ''));
          }
        }
  			break;
      case 'market_payaddextras':
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Покупка дополнительных опций в заказе "Удалено"' : 'Покупка дополнительных опций в заказе');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 0) {
          $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
      			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
      			WHERE order_userid=".$usr['id']." AND order_id=".$pay['pay_code'])->fetch();
          if($marketorder['order_id'] > 0) {
    				$urlparams = empty($marketorder['item_alias']) ?
    					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
    					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
    				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

            $pay['pay_desc'] = 'Покупка дополнительных опций в <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказе #'.$marketorder['order_id'].'</a>';
          }
        }
  			break;
      case 'market_accept_seller_payaddextras':
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Покупка дополнительных опций в заказе "Удалено"' : 'Покупка дополнительных опций в заказе');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 0) {
          $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
      			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
            LEFT JOIN $db_market_track AS t ON t.t_oid=o.order_id
      			WHERE t_id=".$pay['pay_code'])->fetch();
          if($marketorder['order_id'] > 0) {
    				$urlparams = empty($marketorder['item_alias']) ?
    					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
    					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
    				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

            $pay['pay_desc'] = 'Покупка дополнительных опций в <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказе #'.$marketorder['order_id'].'</a>';
          }
        }
  			break;
      case 'market_arbitrage':
        $pay['pay_desc'] = (!$balance_history_loop_admin ? 'Резервирование средств по заказу "Удалено"' : 'Резервирование средств по заказу');

        if(!$balance_history_loop_admin && $pay['pay_code'] > 0) {
          $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
      			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
      			WHERE order_userid=".$usr['id']." AND order_id=".$pay['pay_code'])->fetch();
          if($marketorder['order_id'] > 0) {
    				$urlparams = empty($marketorder['item_alias']) ?
    					array('c' => $marketorder['item_cat'], 'id' => $marketorder['item_id']) :
    					array('c' => $marketorder['item_cat'], 'al' => $marketorder['item_alias']);
    				$result['redirectUrl'] = cot_url('market', $urlparams, '', true);

            $pay['pay_desc'] = 'Резервирование средств по заказу <a href="'.cot_url('marketorders', 'id='.$marketorder['order_id'], '', true).'" class="purse-history-link">заказе #'.$marketorder['order_id'].'</a>';
          }
        }
  			break;
  	}
  }

	$t->assign(array(
		'HIST_ROW_DESC' => $pay['pay_desc'],
    'HIST_ROW_LABEL_HINT' => $pay['pay_label_hint'],
	));
}