<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=payments.billing.emptypid
 * [END_COT_EXT]
 */

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

if(empty($pid))
{
  if($from_type == 'cart' || $from_type == 'prd' || $from_type == 'mk_addextras' || $from_type == 'mk_accept_seller_addextras') {
    if($payment_id > 0 || cot_import('getcartid', 'G', 'INT')) {
      if($from_type == 'cart') {
        $cost = 0;
        $item = array();
        $citems = array();
        $mcart = $db->query("SELECT cart_id FROM $db_market_cart WHERE cart_userid=".$usr['id'].' AND cart_paid=0 '.($payment_id > 0 ? ' AND cart_status="incart" AND cart_id='.$payment_id : '').' LIMIT 1')->fetchColumn();

        if($mcart > 0) {
          $citems = $db->query("SELECT * FROM $db_market_citems WHERE ci_userid=".$usr['id'].' AND ci_cid='.$mcart)->fetchAll();
          foreach($citems as $citem) {
            $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$citem['ci_pid'].' AND item_state=0 LIMIT 1')->fetch();
            if($item['item_id'] > 0) $cost += $citem['ci_cost'];
          }

          $cost = round($cost, 0);
          if($cost > 0) {
            $ubalance = cot_payments_getuserbalance($usr['id']);
            if($cost > 0 && ($summ + $ubalance) >= $cost) {
              $lastorderid = 0;
              $itemcnt = 0;
              foreach($citems as $citem) {
                $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$citem['ci_pid'].' AND item_state=0 LIMIT 1')->fetch();
                if($item['item_id'] > 0) {
                  $db->delete($db_market_orders, "order_userid=".$usr['id']." AND order_status='new' AND order_paid=0 AND order_cid=".$citem['ci_id']);

                  $rorder = array();
                  $rorder['order_cid'] = $citem['ci_id'];
              		$rorder['order_pid'] = $item['item_id'];
                  $rorder['order_userid'] = $usr['id'];
              		$rorder['order_date'] = $sys['now'];
              		$rorder['order_status'] = 'new';
              		$rorder['order_title'] = $item['item_title'];
                  $rorder['order_text'] = $item['item_text'];
              		$rorder['order_seller'] = $item['item_userid'];
                  $rorder['order_count'] = $citem['ci_count'];
              		$rorder['order_cost'] = $citem['ci_cost'];
                  $rorder['order_catcostplans'] = $citem['ci_catcostplans'];

                  $db->insert($db_market_orders, $rorder);
                  $lastorderid = $db->lastInsertId();
                  $itemcnt++;
                }
              }
              $db->delete($db_payments, "pay_userid=".$usr['id']." AND pay_status='new' AND pay_area='market_paycart'");

              $db->update($db_market_cart, array('cart_status' => 'inpay'), 'cart_id='.$mcart);
              if(1 == 1)
              {
              	$options['code'] = $mcart;
              	$options['desc'] = '';

                //$itemcnt == 1 &&
              	if ($lastorderid > 0 && $db->fieldExists($db_payments, "pay_redirect"))
              	{
              		$options['redirect'] = $cfg['mainurl'].'/'.cot_url('plug', 'e=marketorders&m=order&id='.$lastorderid, '', true);
              	}

                /* === Hook === */
                foreach (cot_getextplugins('marketorders.paymentbilling.paycart.done') as $pl)
                {
                	include $pl;
                }
                /* ===== */

                $pidb = cot_payments_create_order('market_paycart', $cost, $options, $billservice);
                if($pidb > 0) {
            			$options['desc'] = $L['payments_balance_billing_desc'];
            			$options['code'] = $pidb;

                  unset($options['redirect']);

            			/* === Hook === */
            			foreach (cot_getextplugins('payments.balance.billing.options') as $pl)
            			{
            				include $pl;
            			}
            			/* ===== */

                  $pid = 0;
                  if($ubalance >= $cost) {
                    $pid = $pidb;
                  } else {
                    $pid = cot_payments_create_order('balance', $summ, $options, $billservice);
                  }
                	if($pid > 0) {
                     cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice, '', true));
                     exit;
                  }
                }
              }
            }
          }
        }
      } elseif($from_type == 'prd' && $payment_id > 0) {
        $item = array();
        $citem = array();
        $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) {
          $citem = $db->query("SELECT * FROM $db_market_citems WHERE ci_userid=".$usr['id'].' AND ci_cid='.$mcart.' AND ci_id='.$payment_id.' LIMIT 1')->fetch();
          if($citem['ci_pid'] > 0) {
            $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$citem['ci_pid'].' AND item_state=0 LIMIT 1')->fetch();
          }
        }
        if($item['item_id'] > 0) {
          $cost = 0;
          $indodji = ($citem['ci_cost_dodji'] > 0);
          $ubalance = cot_payments_getuserbalance($usr['id'], $indodji);

          if($indodji) {
            $citem['ci_cost'] = 0;
            $citem['ci_cost_dodji'] = round($citem['ci_cost_dodji'], 0);
            $cost = $citem['ci_cost_dodji'];
          } else {
            $citem['ci_cost'] = round($citem['ci_cost'], 0);
            $citem['ci_cost_dodji'] = 0;
            $cost = $citem['ci_cost'];
          }

          if(($indodji && $ubalance >= $cost) || (!$indodji && $citem['ci_cost'] > 0 && ($summ + $ubalance) >= $cost)) {
            $rorder = array();
            $rorder['order_cid'] = $citem['ci_id'];
        		$rorder['order_pid'] = $item['item_id'];
            $rorder['order_userid'] = $usr['id'];
        		$rorder['order_date'] = $sys['now'];
        		$rorder['order_status'] = 'new';
        		$rorder['order_title'] = $item['item_title'];
            $rorder['order_text'] = $item['item_text'];
        		$rorder['order_seller'] = $item['item_userid'];
            $rorder['order_count'] = $citem['ci_count'];
        		$rorder['order_cost'] = $citem['ci_cost'];
            $rorder['order_cost_dodji'] = $citem['ci_cost_dodji'];
            $rorder['order_catcostplans'] = $citem['ci_catcostplans'];

        		if($db->insert($db_market_orders, $rorder))
        		{
        			$orderid = $db->lastInsertId();

              $options['paydodji'] = ($indodji ? 1 : 0);
        			$options['code'] = $orderid;
        			$options['desc'] = $item['item_title'];

        			if ($db->fieldExists($db_payments, "pay_redirect"))
        			{
        				$options['redirect'] = $cfg['mainurl'].'/'.cot_url('plug', 'e=marketorders&m=order&id='.$orderid, '', true);
        			}

        			/* === Hook === */
        			foreach (cot_getextplugins('marketorders.paymentbilling.payorder.done') as $pl)
        			{
        				include $pl;
        			}
        			/* ===== */

              $pidb = cot_payments_create_order('market_payorder', $cost, $options, $billservice);
        			if($pidb > 0) {

                $options['paydodji'] = ($indodji ? 1 : 0);
          			$options['desc'] = $L['payments_balance_billing_desc'];
          			$options['code'] = $pidb;

                unset($options['redirect']);

          			/* === Hook === */
          			foreach (cot_getextplugins('payments.balance.billing.options') as $pl)
          			{
          				include $pl;
          			}
          			/* ===== */

                $pid = 0;
                if($ubalance >= $cost) {
                  $pid = $pidb;
                } elseif(!$indodji) {
                  $pid = cot_payments_create_order('balance', $summ, $options, $billservice);
                }
              	if($pid > 0) {
                   cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice, '', true));
                   exit;
                } else {
                   cot_redirect(cot_url('payments', 'm=error&msg=2', '', true));
                   exit;
                }
              }
            }
          }
        }
      } elseif($payment_id > 0 && ($from_type == 'mk_addextras' || $from_type == 'mk_accept_seller_addextras')) {
        $options = array();
        $options['desc'] = $L['payments_balance_billing_desc'];
        $options['code'] = $payment_id;

        $pid = cot_payments_create_order('balance', $summ, $options, $billservice);

        if($pid > 0) {
          cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice, '', true));
          exit;
        }
      }
    }
    echo 'error'; exit;
  } elseif($from_type == 'ds_accept_mkorder') {
    $options = array();
    $options['desc'] = $L['payments_balance_billing_desc'];
    $options['code'] = $payment_id;

    $pid = cot_payments_create_order('balance', $summ, $options, $billservice);

    if($pid > 0) {
      cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice, '', true));
      exit;
    }
  } elseif($from_type == 'prj_accept_offer') {
    $options = array();
    $options['desc'] = $L['payments_balance_billing_desc'];
    $options['code'] = $payment_id;

    $pid = cot_payments_create_order('balance', $summ, $options, $billservice);

    if($pid > 0) {
      cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice, '', true));
      exit;
    }
  }
}