<?php
defined('COT_CODE') or die('Wrong URL');

$return['price'] = 0;
$return['reason'] = '';
$return['cartid'] = 0;

$return['success'] = false;

if($usr['id'] > 0 && cot_plugin_active('marketorders')) {
  require_once cot_incfile('marketorders', 'plug');

  $mcart = $db->query("SELECT cart_id FROM $db_market_cart WHERE cart_userid=".$usr['id'].' AND cart_paid=0 AND cart_status="incart" LIMIT 1')->fetchColumn();
  if($mcart > 0) {
    $return['cartid'] = $mcart;
    $citems = $db->query("SELECT * FROM $db_market_citems WHERE ci_userid=".$usr['id'].' AND ci_cid='.$mcart.' 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) {
        $return['success'] = true;
        $return['price'] += round($ci['ci_cost'], 0);
      }
    }
  }

  if($return['success'] && $return['price'] > 0) {
    $ubalance = cot_payments_getuserbalance($usr['id']);
    if($ubalance < $return['price']) {
      if($ubalance > 0) $return['price'] -= $ubalance;
      $return['success'] = false;
      $return['reason'] = 'purse';
    } else {
      $return['success'] = true;
    }
  }
}

?>