<?php

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

$type = cot_import('type', 'G', 'TXT');

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

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

$out['subtitle'] = 'Уведомления';
$out['head'] .= $R['code_noindex'];

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

$return = cot_mk_track_stack(0, 0, true);

$istype = false;
if($type == 'nogroup' || in_array($type, array_keys($marketorders_notify_group_title))) {
  $t = new XTemplate(cot_tplfile(array('marketorders', 'notifications', 'orders'), 'plug'));

  $jj=0;

  if(is_array($return['notygroup']['notify'][$type])) {
    $_same_mkt_oid = array();
    foreach($return['notygroup']['notify'][$type] as $_arr) {
      if($_arr['mkt']['t_oid'] > 0) {
        $_same_mkt_oid[$_arr['mkt']['t_oid']]++;
      }
    }

    $_same_parse = array();
    foreach($return['notygroup']['notify'][$type] as $_arr) {
      $jj++;
      $to_parse = true;

      if($_arr['mkt']['t_oid'] > 0 && $_same_mkt_oid[$_arr['mkt']['t_oid']] > 1) {
        $to_parse = false;
        $_arr['same_mkt_oid'] = $_same_mkt_oid[$_arr['mkt']['t_oid']];
        if(!in_array($_arr['mkt']['t_oid'], $_same_parse)) {
          $to_parse = true;
          $_same_parse[] = $_arr['mkt']['t_oid'];
        }
      }
      $_arr['same_mkt_oid']--;

      if($to_parse) {
        $marketorder = ($_arr['mkt']['t_oid'] > 0 ? $db->query("SELECT * FROM $db_market_orders WHERE order_id=".$_arr['mkt']['t_oid'].' AND (order_userid='.$usr['id'].' OR order_seller='.$usr['id'].')'.' LIMIT 1')->fetch() : array('order_id' => 0));

        if($marketorder['order_id'] > 0) {
        	$t->assign(cot_generate_markettags($marketorder, 'ORDER_ROW_PRD_'));
        	$t->assign(cot_generate_usertags(($marketorder['order_userid'] == $usr['id'] ? $marketorder['order_seller'] : $marketorder['order_userid']), 'ORDER_ROW_OPPONENT_'));

          $label = array(
            'color' => '',
            'title' => '',
            'hint' => ''
          );

          switch($marketorder['order_status'])
          {
          	case 'cancel':
              $label = array(
                'color' => 'pink',
                'title' => 'Отменен',
                'hint' => (!empty($marketorder['order_status_code']) ? $marketorders_status_codes[$marketorder['order_status_code']]['label'] : '')
              );
          		break;
          	case 'paid':
              if($marketorder['order_accept'] > 0) {
                $label = array(
                  'color' => 'green',
                  'title' => 'Согласование',
                  'hint' => 'Покупатель принял ваш заказ'
                );
              } else {
                $label = array(
                  'color' => 'green',
                  'title' => 'Оплачен',
                  'hint' => 'Ожидаем подтверждение продавца'
                );
              }
          		break;
          	case 'check':
              $label = array(
                'color' => 'orange',
                'title' => 'На проверке',
                'hint' => 'Продавец завершил работу'
              );
          		break;
          	case 'start':
              $label = array(
                'color' => 'cyan',
                'title' => 'В работе',
                'hint' => 'Продавец приступил к работе над заказом'
              );
          		break;
          	case 'queue':
              $queuecnt = cot_mk_queue_cnt($marketorder);
              $label = array(
                'color' => 'cyan',
                'title' => 'В очереди',
                'hint' => ($queuecnt > 0 ? 'Продавец завершает работу над текущими заказами' : 'Ожидаем начало выполнения заказа')
              );
          		break;
          	case 'claim':
              $label = array(
                'color' => 'orange',
                'title' => 'Арбитраж',
                'hint' => 'Ожидаем результат модерации'
              );
              break;
          	case 'done':
              $label = array(
                'color' => 'green',
                'title' => 'Выполнен',
                'hint' => ($marketorder['order_status_code'] == 'autodone' ? 'Заказ автоматически был подтвержден' : 'Вы подтвердили выполнение заказа')
              );
          		break;
          }

        	$t->assign(array(
        		"ORDER_ROW_ID" => $marketorder['order_id'],
            "ORDER_ROW_TITLE" => $marketorder['order_title'],
            "ORDER_ROW_URL" => cot_url('plug','e=marketorders&m=order&id='.$marketorder['order_id']),
        		"ORDER_ROW_COST" => $marketorder['order_cost'],
        		"ORDER_ROW_PAID" => $marketorder['order_paid'],
            "ORDER_ROW_SHOWDATE" => $marketorder[$showdate['field']],
        		"ORDER_ROW_STATUS" => $marketorder['order_status'],
            "ORDER_ROW_LABEL" => $label,
        	));
        } else {
        	$t->assign(array(
        		"ORDER_ROW_ID" => 0,
        	));
        }

        $t->assign(array(
          'NOTIFY_DATA' => $_arr
        ));
        $t->parse('MAIN.NOTI_ROW');
      }
    }
  }
  if($jj > 0) {
    $istype = true;
    $out['subtitle'] = 'Уведомления - '.cot_rc($marketorders_notify_group_title[$type], array(
      'cnt' => $jj
    ));
  }
}

if(!$istype) {
  $t = new XTemplate(cot_tplfile(array('marketorders', 'notifications'), 'plug'));
  $jj=0;

  if(is_array($return['notygroup']['notify_notgroup']) && count($return['notygroup']['notify_notgroup']) > 0) {
    $_same_mkt_oid = array();
    foreach($return['notygroup']['notify_notgroup'] as $_arr) {

      if($_arr['mkt']['t_oid'] > 0) {
        $_same_mkt_oid[$_arr['mkt']['t_oid']]++;
      }
    }

    $_same_parse = array();
    foreach($return['notygroup']['notify_notgroup'] as $_arr) {
      $jj++;
      $to_parse = true;

      if($_arr['mkt']['t_oid'] > 0 && $_same_mkt_oid[$_arr['mkt']['t_oid']] > 1) {
        $to_parse = false;
        $_arr['same_mkt_oid'] = $_same_mkt_oid[$_arr['mkt']['t_oid']];
        if(!in_array($_arr['mkt']['t_oid'], $_same_parse)) {
          $to_parse = true;
          $_same_parse[] = $_arr['mkt']['t_oid'];
        }
      }
      $_arr['same_mkt_oid']--;

      if($to_parse) {
        $t->assign(array(
          'NOTIFY_DATA' => $_arr
        ));
        $t->parse('MAIN.NOTI_ROW');
      }
    }
  }
  $out['subtitle'] = 'Все уведомления ('.$jj.')';
}

$t->assign(array(
  'NOTY_CNT' => $jj,
  'NOTY_ISTYPE' => ($istype ? 1 : 0),
  'NOTY_TITLE' => $out['subtitle']
));

//echo '<pre>'.print_r($return,1).'</pre>';