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

$return['id'] = 0;
$return['cartid'] = 0;
$return['item'] = array();
$return['success'] = false;

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

  $indodji = cot_import('indodji', 'G', 'INT');
  $indodji = ($indodji == 1);
  $prddata = array(
    'EPID' => cot_import('EPID', 'P', 'INT'),
    'prdcnt' => cot_import('prdcnt', 'P', 'INT'),
    'extrascnt' => 0,
    'gextras' => cot_import('gextras', 'P', 'ARR'),
    'cost' => 0,
    'cost_dodji' => 0,
    'package' => cot_import('packageType', 'P', 'TXT')
  );
  if(!$prddata['prdcnt']) $prddata['prdcnt'] = 1;
  if(!$prddata['EPID']) $prddata['EPID'] = cot_import('prdId', 'P', 'INT');

  if($prddata['EPID'] > 0) {
    $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$prddata['EPID'].' AND item_userid!='.$usr['id'].' AND item_state=0 LIMIT 1')->fetch();

    if($item['item_id'] > 0) {
      $item['photo_first'] = 'http://via.placeholder.com/90x60';
      $item['photo_first_crop'] = '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];

            $item['photo_first_crop'] = $market_imgdir_crop . $item['item_file_'.$i];
            if(file_exists($item['photo_first_crop'])) {
              $item['photo_first_crop'] = $item['photo_first_crop'];
            } else {
              $item['photo_first_crop'] = $item['photo_first'];
            }
            break;
        }
      }

      $citem = array(
        'ci_cid' => 0,
        'ci_pid' => $item['item_id'],
        'ci_userid' => $usr['id'],
        'ci_count' => $prddata['prdcnt'],
        'ci_cost' => 0,
        'ci_cost_dodji' => 0,
        'ci_itemcost' => $item['item_cost'],
        'ci_itemcost_dodji' => $item['item_cost_dodji'],
        'ci_catcostplans' => array()
      );
      $citem['ci_catcostplans']['item_cache'] = $item;

      if(!$indodji) {
        $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") LIMIT 1')->fetch();
        if(!$mcart['cart_id']) {
          $mcart = array(
            'cart_userid' => $usr['id'],
            'cart_paid' => 0,
            'cart_status' => 'incart'
          );
          $db->insert($db_market_cart, $mcart);
          $mcart['cart_id'] = $db->lastInsertId();
        } elseif($mcart['cart_status'] == 'inpay') {
          $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' => 'incart'), "cart_id=".$mcart['cart_id']);

          $ciarr = $db->query("SELECT * FROM $db_market_citems WHERE ci_userid=".$usr['id'].' AND ci_cid='.$mcart['cart_id'])->fetchAll();
          foreach($ciarr as $ci) {
            $db->delete($db_market_orders, "order_userid=".$usr['id']." AND order_status='new' AND order_paid=0 AND order_cid=".$ci['ci_id']);
          }
        }

        $citem['ci_cid'] = $mcart['cart_id'];
      }

      require_once cot_incfile('catcostplans', 'plug');
      $bundles = (!empty($item['item_catcostplans']) ? json_decode($item['item_catcostplans'], 1) : array());

      $costtoshow = 0;
      if($bundles['bundle_type'] == 'package') {
        if(!in_array($prddata['package'], array('standard', 'medium', 'premium'))) $prddata['package'] = 'standard';

        $citem['ci_catcostplans']['package'] = $prddata['package'];

        $citem['ci_catcostplans']['extras'] = array(
          'info' => array(
            'title' => '',
            'time' => 1,
            'price' => 0,
          ),
          'selected' => array(
            'category' => array(),
            'custom' => array()
          ),
          'customBundleExtras' => array()
        );

        if(count($bundles['epackages']) > 0) {
          foreach($bundles['epackages'] as $epack) {
            $citem['ci_catcostplans']['customBundleExtras'][] = array(
              'id' => $epack['id'],
              'prd_id' => $item['item_id'],
              'name' => $epack['name'],
              'min_value' => '1',
              'max_value' => '1',
              'hint' => $epack['hint'],
              'type' => $epack['type'],
              'can_lower' => 1
            );
          }
        }

        if(count($bundles['bundles']) > 0) {
          $bund = $bundles['bundles'][$prddata['package']];

          if(count($bund['category']) > 0) {
            foreach($bund['category'] as $brow) {
              $citem['ci_catcostplans']['extras']['selected']['category'][] = array(
                'value' => $brow['val'],
                'item_id' => $brow['id'],
              );
            }
          }
          if(count($bund['custom_val']) > 0) {
            foreach($bund['custom_val'] as $oid => $browval) {
              $citem['ci_catcostplans']['extras']['selected']['custom'][] = array(
                'value' => $browval,
                'item_id' => $oid,
              );
            }
          }

          $citem['ci_catcostplans']['extras']['info'] = array(
            'title' => '',
            'price' => $bund['price'],
            'price_dodji' => $bund['price_dodji'],
            'time' => $bund['duration'],
            'count' => 1
          );

          $citem['ci_itemcost'] = (!$indodji ? $bund['price'] : 0);
          $citem['ci_itemcost_dodji'] = ($indodji ? $bund['price_dodji'] : 0);
        }
      } else {
        $citem['ci_catcostplans']['package'] = 'single';

        $citem['ci_catcostplans']['extras'] = array(
          'single' => array(
            'title' => $bundles['bundles']['category']['title'],
            'time' => $bundles['bundles']['category']['time'],
            'price' => $bundles['bundles']['category']['price'],
            'price_dodji' => $bundles['bundles']['category']['price_dodji'],
            'count' => $prddata['prdcnt'],
          ),
          'selected' => array()
        );
        if(!$indodji && $bundles['bundles']['category']['price'] > 0) $citem['ci_itemcost'] = $bundles['bundles']['category']['price'];
        if($indodji && $bundles['bundles']['category']['price_dodji'] > 0) $citem['ci_itemcost_dodji'] = $bundles['bundles']['category']['price_dodji'];

        global $costplans_prices;

        $costplans_prices_flip = array_flip($costplans_prices);

        if(count($bundles['bundles']['custom']) > 0) foreach($bundles['bundles']['custom'] as $iopt => $cust) {
          $priceId = 0;
          $cost = $cust['price'];
          if($cost > 0 && $cost < 100) {
            $priceId = $cost;
            $cost = $costplans_prices[$priceId];
          }

          $cnt = cot_import('extra_count'.$iopt, 'P', 'INT');
          $cnt = (in_array($iopt, $prddata['gextras']) ? ($cnt > 0 ? $cnt : 1) : 0);
          if(($indodji && !($cust['price_dodji'] > 0)) || (!$indodji && !($cost > 0))) $cnt = 0;

          $citem['ci_catcostplans']['extras']['selected'][] = array(
            'id' => $cust['id'],
            'name' => $cust['name'],
            'payerPrice' => $cost,
            'payerPriceDodji' => $cust['price_dodji'],
            'duration' => $cust['duration'],
            'priceId' => $priceId,
            'count' => $cnt
          );
          if($cnt > 0) {
            $costtoshow += ($indodji ? $cust['price_dodji'] : $cost)*$cnt;
            $prddata['extrascnt']++;
          }
        }
      }

      if($indodji) {
        $costtoshow += $citem['ci_itemcost_dodji']*$citem['ci_count'];
        $citem['ci_cost_dodji'] = $costtoshow;
      } else {
        $costtoshow += $citem['ci_itemcost']*$citem['ci_count'];
        $citem['ci_cost'] = $costtoshow;
      }

      $citem['ci_catcostplans'] = json_encode($citem['ci_catcostplans']);

      $ci_id = 0;
      if(!$indodji) {
        $ciexists = $db->query("SELECT ci_id FROM $db_market_citems WHERE ci_cid=".$citem['ci_cid'].' AND ci_pid='.$citem['ci_pid'].' AND ci_userid='.$citem['ci_userid'].' LIMIT 1')->fetchColumn();
        if($ciexists > 0) {
          require_once cot_incfile('payments', 'module');
          $db->delete($db_payments, "pay_userid=".$usr['id']." AND pay_status='new' AND pay_area='market_payorder'");
          $db->delete($db_market_orders, "order_userid=".$usr['id']." AND order_status='new' AND order_paid=0 AND order_cid=".$ciexists);

          $db->update($db_market_citems, $citem, 'ci_id='.$ciexists);
          $ci_id = $ciexists;
        } else {
          $db->insert($db_market_citems, $citem);
          $ci_id = $db->lastInsertId();
        }
      }

      $citem['ci_catcostplans'] = json_decode($citem['ci_catcostplans'], 1);
      $return['citem'] = $citem;
      $citem['ci_catcostplans'] = json_encode($citem['ci_catcostplans']);

      if($ci_id > 0 || $indodji) {
        $return['item'] = array(
          'title' => $item['item_title'],
          'photo_first' => $item['photo_first'],
          'photo_first_crop' => $item['photo_first_crop'],
          'cnt_item' => $prddata['prdcnt'],
          'cnt_extras' => $prddata['extrascnt'],
          'cost' => (!$indodji ? round($costtoshow, 0) : 0),
          'cost_format' => (!$indodji ? number_format(round($costtoshow, 0), 0, ' ', '') : 0),
          'cost_dodji' => ($indodji ? round($costtoshow, 0) : 0),
          'cost_dodji_format' => ($indodji ? number_format(round($costtoshow, 0), 0, ' ', '') : 0),
          'ciexists' => ($ciexists > 0 ? 1 : 0)
        );

        $return['cartid'] = $citem['ci_cid'];
        $return['id'] = $ci_id;
        $return['success'] = true;
      }
    }
  }
}

?>