<?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.sales.first');
foreach ($extp as $pl)
{
	include $pl;
}
/* ===== */

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

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

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

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

$t = new XTemplate($mskin);

$where['userid'] = "order_seller=" . $usr['id'];

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

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

if(empty($status) && $db->query("SELECT COUNT(*) FROM $db_market_orders AS o
	         WHERE o.order_status='start' AND o.order_seller=" . $usr['id'])->fetchColumn() > 0) {
  $status = 'start';
} elseif(!empty($status) && $db->query("SELECT COUNT(*) FROM $db_market_orders AS o
	         WHERE o.order_status='".$status."' AND o.order_seller=" . $usr['id'])->fetchColumn() == 0) {
  $status = 'all';
}

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_preorder'] = 'order_queue ASC, ';
		break;
}

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

  	case 'user':
      $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_preorder'].$showdate['field'].' '.($a == 'asc' ? 'ASC' : 'DESC');
}

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

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

while ($marketorder = $sql->fetch())
{
	$t->assign(cot_generate_markettags($marketorder, 'ORDER_ROW_PRD_'));
	$t->assign(cot_generate_usertags($marketorder['order_userid'], 'ORDER_ROW_CUSTOMER_'));
	
  $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_perf'] : '')
      );
  		break;
  	case 'paid':
      if($marketorder['order_accept'] > 0) {
        $label = array(
          'color' => 'green',
          'title' => 'На принятии',
          'hint' => 'Ждем уточнений от покупателя'
        );
      } else {
        $label = array(
          'color' => 'green',
          'title' => 'На принятии',
          'hint' => 'покупатель сделал заказ '.cot_sitename('phrases', 'vashei').', подтвердите заказ'
        );
      }
  		break;
  	case 'check':
      $label = array(
        'color' => 'orange',
        'title' => 'На проверке',
        'hint' => 'Заказ сдан на проверку покупателю. Ожидайте результата'
      );
  		break;
  	case 'queue':
      $queuecnt = cot_mk_queue_cnt($marketorder);
      if($queuecnt > 0) {
        $label = array(
          'color' => 'cyan',
          'title' => 'В очереди',
          'hint' => ''
        );
      } elseif($marketorder['order_queue'] > 0) {
        $label = array(
          'color' => 'dark_green',
          'title' => 'Ожидает',
          'hint' => 'Покупатель ожидает начало выполнения заказа, осталось '.cot_build_timegap(($sys['now']-(86400 - ($sys['now'] - $marketorder['order_queue']))))
        );
      } else {
        $label = array(
          'color' => 'dark_green',
          'title' => 'Ожидает',
          'hint' => ''
        );
      }
  		break;
  	case 'start':
      $label = array(
        'color' => 'cyan',
        'title' => 'В работе',
        'hint' => ''
      );
  		break;
    case 'done':
      $label = array(
        'color' => 'green',
        'title' => 'Выполнен',
        'hint' => ($marketorder['order_status_code'] == 'autodone' ? 'Заказ автоматически был подтвержден' : 'Выполнение заказа подтверждено покупателем')
      );
  		break;
  	case 'claim':
      $label = array(
        'color' => 'orange',
        'title' => 'Арбитраж',
        'hint' => 'Ожидаем результат модерации'
      );
  		break;
  }

  $msgcount = $db->query("SELECT COUNT(*) FROM $db_market_track WHERE t_oid=".$marketorder['order_id'].' AND t_touser='.$usr['id'].' AND t_status=0')->fetchColumn();

	/* === 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']),
		"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,
    "ORDER_ROW_MSGCNT" => $msgcount,
	));

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

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