<?php
/*
  www.oscGold.com (C) Kamelia-Net Jacek Krysiak
  modul oscGold wer 4.0
*/

  require('includes/application_top.php');

// if the customer is not logged on, redirect them to the login page
  if (!tep_session_is_registered('customer_id')) {
    $navigation->set_snapshot(array('mode' => 'SSL', 'page' => FILENAME_CHECKOUT));
    tep_redirect(tep_href_link(FILENAME_LOGIN, 'act=register', 'SSL'));
  }

// if there is nothing in the customers cart, redirect them to the shopping cart page
  if ($cart->count_contents() < 1) {
    tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
  }

// avoid hack attempts during the checkout procedure by checking the internal cartID
  if (isset($cart->cartID) && tep_session_is_registered('cartID')) {
    if ($cart->cartID != $cartID) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT, 'act=register', 'SSL'));
    }
  }

// if no shipping method has been selected, redirect the customer to the shipping method selection page
  if (!tep_session_is_registered('shipping')) {
    tep_redirect(tep_href_link(FILENAME_CHECKOUT, '', 'SSL'));
  }

  if (!tep_session_is_registered('payment')) tep_session_register('payment');
  if (isset($HTTP_POST_VARS['payment'])) $payment = $HTTP_POST_VARS['payment'];

  if (!tep_session_is_registered('comments')) tep_session_register('comments');
  if (tep_not_null($HTTP_POST_VARS['comments'])) {
    $comments = tep_db_prepare_input($HTTP_POST_VARS['comments']);
  }

  if (!tep_session_is_registered('paragon')) tep_session_register('paragon');
  if (tep_not_null($HTTP_POST_VARS['paragon'])) {
    $paragon = tep_db_prepare_input($HTTP_POST_VARS['paragon']);
  }

  if ($module_darmo == true) {
	if (!tep_session_is_registered('giftx')) tep_session_register('giftx');
	if (!tep_session_is_registered('giftx_id')) tep_session_register('giftx_id');
	if (isset($HTTP_POST_VARS['giftx']) && tep_not_null($HTTP_POST_VARS['giftx'])) {
	    //
		$tab_gift = explode('||*||',tep_db_prepare_input($HTTP_POST_VARS['giftx']));
	    $giftx = $tab_gift[0]; $giftx_id = $tab_gift[1];
	  } else {
	    $giftx = ''; $giftx_id = '';
	}
  }

  //kgt - discount coupons
  if (!tep_session_is_registered('coupon')) tep_session_register('coupon');
  //this needs to be set before the order object is created, but we must process it after
  $coupon = tep_db_prepare_input($HTTP_POST_VARS['coupon']);
  //end kgt - discount coupons

  $total_weight = $cart->show_weight();
  $total_count = $cart->count_contents();

// load the selected payment module
  require(DIR_WS_CLASSES . 'payment.php');
  $payment_modules = new payment($payment);

  require(DIR_WS_CLASSES . 'order.php');
  $order = new order;

// load the selcted giftwrap module
  require(DIR_WS_CLASSES . "gift.php");
  $giftwrap_modules = new gift;
  // process the selected giftwrap method
  if ( isset($HTTP_POST_VARS['action']) && ($HTTP_POST_VARS['action'] == 'process') ) {
    if (!tep_session_is_registered('giftwrap_info')) tep_session_register('giftwrap_info');
    if (tep_count_giftwrap_modules() > 0) {
      if ( (isset($HTTP_POST_VARS['giftwrap'])) && (strpos($HTTP_POST_VARS['giftwrap'], '_')) ) {
        $giftwrap_info = $HTTP_POST_VARS['giftwrap'];

        list($module, $method) = explode('_', $giftwrap_info);
        if (is_object($$module)) {
          $quote1 = $giftwrap_modules->quote1($method, $module);
          if (isset($quote1['error'])) {
            tep_session_unregister('giftwrap');
          } else {
            if ( (isset($quote1[0]['methods'][0]['title'])) && (isset($quote1[0]['methods'][0]['cost'])) ) {
              $giftwrap_info = array('id' => $giftwrap_info,
                                     'title' => $quote1[0]['methods'][0]['title'],
                                     'cost' => $quote1[0]['methods'][0]['cost']);
              $order->info['giftwrap_method'] = $quote1[0]['methods'][0]['title'];
              $order->info['giftwrap_cost'] = $quote1[0]['methods'][0]['cost'];
            }
          }
        } else {
          tep_session_unregister('giftwrap_info');
        }
      }
    } else {
      $giftwrap_info = false;
    }
  }

  //BOF Minimalne zamowienie
  $query = tep_db_query("select g.customers_groups_min_amount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . $customer_id . "'");
  $query_result = tep_db_fetch_array($query);
  $customers_groups_min_amount = $query_result['customers_groups_min_amount'];
  if ($order->info['subtotal'] < $customers_groups_min_amount) {
   tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'NONSSL'));
  }
  //EOF Minimalne zamowienie

  $payment_modules->update_status();

  ##### Points/Rewards Module V2.1rc2a check for error BOF #######
  if ((USE_POINTS_SYSTEM == 'true') && (USE_REDEEM_SYSTEM == 'true')) {
	  if (tep_not_null(USE_REFERRAL_SYSTEM)) {
		  if (isset($_POST['customer_referred']) && tep_not_null($_POST['customer_referred'])) {
		    $customer_referral = false;
		    $check_mail = trim($_POST['customer_referred']);
		    $valid_referral_query = tep_db_query("select customers_id from " . TABLE_CUSTOMERS . " where customers_email_address = '" . $check_mail . "' limit 1");
		    $valid_referral = tep_db_fetch_array($valid_referral_query);
		    if ((int)tep_db_num_rows($valid_referral_query) > 0) {
			  if (!tep_session_is_registered('customer_referral')) tep_session_register('customer_referral');
			  $customer_referral = $valid_referral['customers_id'];
		    }
			//$customer_referral = $valid_referral['customers_id'];
			//if (!tep_session_is_registered('customer_referral')) tep_session_register('customer_referral');
		  }
	  }
	  $customer_shopping_points_spending = $_POST['customer_shopping_points_spending'];
	  if (!tep_session_is_registered('customer_shopping_points_spending')) tep_session_register('customer_shopping_points_spending');
  }
  if ( ( is_array($payment_modules->modules) && (sizeof($payment_modules->modules) > 1) && !is_object($$payment) ) || (is_object($$payment) && ($$payment->enabled == false)) ) {
  //if ( ( is_array($payment_modules->modules) && (sizeof($payment_modules->modules) > 1) && !is_object($$payment) ) && (!$customer_shopping_points_spending) || (is_object($$payment) && ($$payment->enabled == false)) ) {
	  tep_redirect(tep_href_link(FILENAME_CHECKOUT, 'error_checkout=' . urlencode(ERROR_NO_PAYMENT_MODULE_SELECTED), 'SSL'));
  }
  ########  Points/Rewards Module V2.1rc2a EOF #################*/

  if (is_array($payment_modules->modules)) {
    $payment_modules->pre_confirmation_check();
  }

  //kgt - discount coupons
  if( tep_not_null( $coupon ) && is_object( $order->coupon ) ) { //if they have entered something in the coupon field
	  $order->coupon->verify_code();
	  if( !$order->coupon->is_errors() ) { //if we have passed all tests (no error message), make sure we still meet free shipping requirements, if any
		  if( $order->coupon->is_recalc_shipping() ) tep_redirect( tep_href_link( FILENAME_CHECKOUT, 'error_checkout=' . urlencode( ENTRY_DISCOUNT_COUPON_SHIPPING_CALC_ERROR ), 'SSL' ) ); //redirect to the shipping page to reselect the shipping method
	  } else {
		  if( tep_session_is_registered('coupon') ) tep_session_unregister('coupon'); //remove the coupon from the session
		  tep_redirect( tep_href_link( FILENAME_CHECKOUT, 'error_checkout=' . urlencode( implode( ' ', $order->coupon->get_messages() ) ), 'SSL' ) ); //redirect to the payment page
	  }
	} else { //if the coupon field is empty, unregister the coupon from the session
	  if( tep_session_is_registered('coupon') ) { //we had a coupon entered before, so we need to unregister it
      tep_session_unregister('coupon');
      //now check to see if we need to recalculate shipping:
      require_once( DIR_WS_CLASSES.'discount_coupon.php' );
      if( discount_coupon::is_recalc_shipping() ) tep_redirect( tep_href_link( FILENAME_CHECKOUT, 'error_checkout=' . urlencode( ENTRY_DISCOUNT_COUPON_SHIPPING_CALC_ERROR ), 'SSL' ) ); //redirect to the shipping page to reselect the shipping method
    }
	}
	//end kgt - discount coupons

// load the selected shipping module
  require(DIR_WS_CLASSES . 'shipping.php');
  $shipping_modules = new shipping($shipping);

// process the selected shipping method
  if ( isset($HTTP_POST_VARS['action']) && ($HTTP_POST_VARS['action'] == 'process') ) {
    if (!tep_session_is_registered('comments')) tep_session_register('comments');
    if (tep_not_null($HTTP_POST_VARS['comments'])) {
      $comments = tep_db_prepare_input($HTTP_POST_VARS['comments']);
    }
    if (!tep_session_is_registered('shipping')) tep_session_register('shipping');

    if ( (tep_count_shipping_modules() > 0) ) {
      if ( (isset($HTTP_POST_VARS['shipping'])) && (strpos($HTTP_POST_VARS['shipping'], '_')) ) {
        $shipping = $HTTP_POST_VARS['shipping'];

        list($module, $method) = explode('_', $shipping);
        // dodatkowe dla wielu pozycji
        if (strpos($method,';') > 0) {
            $bnm = explode(';',$method);
            $method = $bnm[0];
            $pozycia = (int)$bnm[1]-1;
           } else {
            $pozycia = 0;
        }
        //
        if ( is_object($$module) ) {
          $quote = $shipping_modules->quote($method, $module);
          if (isset($quote['error'])) {
            tep_session_unregister('shipping');
          } else {
            if ( (isset($quote[0]['methods'][$pozycia]['title'])) && (isset($quote[0]['methods'][$pozycia]['cost'])) ) {
              $shipping = array('id' => $shipping,
                                'title' => $quote[0]['module'] . ' (' . $quote[0]['methods'][$pozycia]['title'] . ')',
                                'cost' => $quote[0]['methods'][$pozycia]['cost']);
            }
          }
        } else {
          tep_session_unregister('shipping');
        }
      }
    } else {
      $shipping = false;
      tep_redirect(tep_href_link('checkout.php', '', 'SSL'));
    }
  }



  require(DIR_WS_CLASSES . 'order_total.php');
  $order_total_modules = new order_total;
  $order_total_modules->process();

// Stock Check
  $any_out_of_stock = false;
//++++ QT Pro: Begin Changed code
    $check_stock='';
    for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
      if (isset($order->products[$i]['attributes']) && is_array($order->products[$i]['attributes'])) {
        $attributes=array();
        foreach ($order->products[$i]['attributes'] as $attribute) {
          $attributes[$attribute['option_id']]=$attribute['value_id'];
        }
        $check_stock[$i] = tep_check_stock($order->products[$i]['id'], $order->products[$i]['qty'], $attributes);
      } else {
        $check_stock[$i] = tep_check_stock($order->products[$i]['id'], $order->products[$i]['qty']);
      }
      if ($check_stock[$i]) {
        $any_out_of_stock = true;
      }
//++++ QT Pro: End Changed Code

// Out of Stock
    if ( (STOCK_ALLOW_CHECKOUT != 'true') && ($any_out_of_stock == true) ) {
      tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
    }
  }

  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CHECKOUT_CONFIRMATION);

  $breadcrumb->add(NAVBAR_TITLE_1, tep_href_link(FILENAME_CHECKOUT, '', 'SSL'));
  $breadcrumb->add(NAVBAR_TITLE_2);

  $content = CONTENT_CHECKOUT_CONFIRMATION;

  include (bts_select('main', $content_template)); // BTSv1.5

  require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
