<?php

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

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'];

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

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

$t = new XTemplate($mskin);


if($usr['id'] > 0) {
  $mcart = $db->query("SELECT * FROM $db_market_cart WHERE cart_userid=".$usr['id'].' AND cart_paid=0 AND (cart_status="incart" OR cart_status="inpay") ORDER BY cart_id DESC LIMIT 1')->fetch();
  if($mcart['cart_id'] > 0) {
    $citems = $db->query("SELECT * FROM $db_market_citems WHERE ci_userid=".$usr['id'].' AND ci_cid='.$mcart['cart_id'].' ORDER BY ci_id DESC')->fetchAll();
    foreach($citems as $ci) {
      $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$ci['ci_pid'].' AND item_state=0 LIMIT 1')->fetch();
      if($item['item_id'] > 0) {
        $item['photo_first'] = 'http://via.placeholder.com/90x60';
        foreach(array(1,2,3) as $i) {
          if(!empty($item['item_file_'.$i]) && file_exists($market_imgdir . $item['item_file_'.$i])) {
            $item['photo_first'] = $market_imgdir . $item['item_file_'.$i];
            break;
          }
        }
        $ci['extrascnt'] = 0;

        $ci['ci_catcostplans'] = (!empty($ci['ci_catcostplans']) ? json_decode($ci['ci_catcostplans'],1) : array());
        if($ci['ci_catcostplans']['package'] == 'single') {
          $ci['extrascnt'] = 0;
          foreach($ci['ci_catcostplans']['extras']['selected'] as $exts) {
            if($exts['count'] > 0) $ci['extrascnt']++;
          }
        }
				$urlparams = empty($item['item_alias']) ?
					array('c' => $item['item_cat'], 'id' => $item['item_id']) :
					array('c' => $item['item_cat'], 'al' => $item['item_alias']);

        $t->assign('CART', array(
          'id' => $ci['ci_id'],
          'title' => $item['item_title'],
          'item_url' => cot_url('market', $urlparams, '', true),
          'photo_first' => $item['photo_first'],
          'cnt_item' => $ci['ci_count'],
          'cnt_extras' => $ci['extrascnt'],
          'cost' => round($ci['ci_cost'], 0),
          'cost_format' => number_format(round($ci['ci_cost'], 0), 0, ' ', '')
        ));
        $t->parse('MAIN.CART_ROW');
      }
    }
  }
}
