<?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');

$status = cot_import('status', 'G', 'ALP');
$a = cot_import('a', 'G', 'ALP');
$b = cot_import('b', 'G', 'ALP');

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

if($cfg['plugin']['marketorders']['ordersperpage'] > 0)
{
	list($pn, $d, $d_url) = cot_import_pagenav('d', $cfg['plugin']['marketorders']['ordersperpage']);
}

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

$out['subtitle'] = $L['marketorders_myadmin'];
$out['head'] .= $R['code_noindex'];

$list_url_path = array('m' => 'admin', 'status' => $status, 'a' => $a, 'b' => $b);

$mskin = cot_tplfile(array('marketorders', 'admin'), 'plug');

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

$t = new XTemplate($mskin);

//$where['userid'] = "o.order_userid!=" . $usr['id'] . " AND o.order_seller!=" . $usr['id'];

$showdate = array(
  'title' => 'Заказан',
  'field' => 'order_paid'
);

$where['order_status'] = "o.order_status!='new'";

switch($status)
{
	case 'paid':
    $where['order_status'] = "o.order_status='paid'";
    $showdate['title'] = 'Оплачен';
    $showdate['field'] = 'order_paid';
		break;

	case 'done':
		$where['order_status'] = "o.order_status='done'";
    $showdate['title'] = 'Завершен';
    $showdate['field'] = 'order_done';
		break;

	case 'claim':
		$where['order_status'] = "o.order_status='claim'";
    $showdate['title'] = 'Арбитраж';
    $showdate['field'] = 'order_claim';
		break;

	case 'cancel':
		$where['order_status'] = "o.order_status='cancel'";
    $showdate['title'] = 'Отменен';
    $showdate['field'] = 'order_cancel';
		break;

	case 'start':
		$where['order_status'] = "o.order_status='start'";
    $showdate['title'] = 'Начат';
    $showdate['field'] = 'order_start';
		break;

	case 'check':
		$where['order_status'] = "o.order_status='check'";
    $showdate['title'] = 'Дата сдачи';
    $showdate['field'] = 'order_check';
		break;

	case 'queue':
		$where['order_status'] = "o.order_status='queue'";
    //$showdate['title'] = 'Дата завершения работ';
    //$showdate['field'] = 'order_check';
		break;
}

if(!empty($b) && in_array($b, array('title', 'user', 'buyer', 'price', 'status'))) {
  switch($b)
  {
  	case 'title':
      $order['sort'] = 'o.order_title';
  		break;

  	case 'user':
      $order['sort'] = 'o.order_seller';
  		break;

    case 'buyer':
      $order['sort'] = 'o.order_userid';
  		break;

  	case 'price':
      $order['sort'] = 'o.order_cost';
  		break;

  	case 'status':
      $order['sort'] = 'o.order_status';
  		break;
  }
  if(!empty($order['sort'])) $order['sort'] .= ' '.($a == 'asc' ? 'ASC' : 'DESC');
} else {
  $order['date'] = $showdate['field'].' '.($a == 'asc' ? 'ASC' : 'DESC');
}

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

$where = ($where) ? 'WHERE ' . implode(' AND ', $where) : '';
$order = ($order) ? 'ORDER BY ' . implode(', ', $order) : '';
$query_limit = ($cfg['plugin']['marketorders']['ordersperpage'] > 0) ? "LIMIT $d, ".$cfg['plugin']['marketorders']['ordersperpage'] : '';

$totalitems = $db->query("SELECT COUNT(*) FROM $db_market_orders AS o
	LEFT JOIN $db_market AS m ON o.order_pid=m.item_id
	" . $where . "")->fetchColumn();

$sql = $db->query("SELECT * FROM $db_market_orders AS o
	LEFT JOIN $db_market AS m ON o.order_pid=m.item_id
	" . $where . "
	" . $order . "
	" . $query_limit . "");

$pagenav = cot_pagenav('marketorders', $list_url_path, $d, $totalitems, $cfg['plugin']['marketorders']['ordersperpage']);

$querytpl = "SELECT COUNT(*) FROM $db_market_orders AS o";//o.order_userid!=" . $usr['id'] . " AND o.order_seller!=" . $usr['id'];
$t->assign(array(
	"PAGENAV_COUNT" => $totalitems,
	"PAGENAV_PAGES" => $pagenav['main'],
	"PAGENAV_PREV" => $pagenav['prev'],
	"PAGENAV_NEXT" => $pagenav['next'],
  "NAV_CNT_ALL" => $db->query($querytpl ." WHERE o.order_status!='new'")->fetchColumn(),
  "NAV_CNT_PAID" => $db->query($querytpl ." WHERE o.order_status='paid'")->fetchColumn(),
  "NAV_CNT_CANCEL" => $db->query($querytpl ." WHERE o.order_status='cancel'")->fetchColumn(),
  "NAV_CNT_CLAIM" => $db->query($querytpl ." WHERE o.order_status='claim'")->fetchColumn(),
  "NAV_CNT_CHECK" => $db->query($querytpl ." WHERE o.order_status='check'")->fetchColumn(),
  "NAV_CNT_START" => $db->query($querytpl ." WHERE o.order_status='start'")->fetchColumn(),
  "NAV_CNT_DONE" => $db->query($querytpl ." WHERE o.order_status='done'")->fetchColumn(),
  "NAV_CNT_QUEUE" => $db->query($querytpl ." WHERE o.order_status='queue'")->fetchColumn(),
));

/* === Hook === */
$extp = cot_getextplugins('marketorders.admin.loop');
/* ===== */

while ($marketorder = $sql->fetch())
{
	$t->assign(cot_generate_markettags($marketorder, 'ORDER_ROW_PRD_'));
	$t->assign(cot_generate_usertags($marketorder['order_seller'], 'ORDER_ROW_SELLER_'));
  $t->assign(cot_generate_usertags($marketorder['order_userid'], 'ORDER_ROW_BUYER_'));

  $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;
  }

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

	$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'].'&is_admin=1'),
		"ORDER_ROW_COST" => $marketorder['order_cost'],
    "ORDER_ROW_COST_FORMAT" => cot_market_cost_format($marketorder['order_cost'], $marketorder['order_cost_dodji'], true),
		"ORDER_ROW_PAID" => $marketorder['order_paid'],
    "ORDER_ROW_SHOWDATE" => $marketorder[$showdate['field']],
		"ORDER_ROW_STATUS" => $marketorder['order_status'],
    "ORDER_ROW_LABEL" => $label
	));

	$t->parse("MAIN.ORDER_ROW");
}

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