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


// shopping points the customer currently has
  function tep_get_shopping_points($id = '', $check_session = true) {
	  global $customer_id;

	  if (is_numeric($id) == false) {
		  if (tep_session_is_registered('customer_id')) {
			  $id = $customer_id;
		  } else {
			  return 0;
		  }
	  }

	  if ($check_session == true) {
		  if ( (tep_session_is_registered('customer_id') == false) || ($id != $customer_id) ) {
			  return 0;
		  }
	  }

	  if (tep_not_null(POINTS_AUTO_EXPIRES)) {
		  $points_query = tep_db_query("select customers_shopping_points from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$id . "' and customers_points_expires > CURDATE() limit 1");
	  } else {
		  $points_query = tep_db_query("select customers_shopping_points from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$id . "' limit 1");
	  }

	  $points = tep_db_fetch_array($points_query);

	  return $points['customers_shopping_points'];
  }

// calculate the shopping points value for the customer
  function tep_calc_shopping_pvalue($points) {

	  return tep_round(((float)$points * (float)REDEEM_POINT_VALUE), 2);
  }

// calculate the products shopping points tax value if any
  function tep_display_points($products_price, $products_tax, $quantity = 1) {

	  if ((DISPLAY_PRICE_WITH_TAX == 'true') && (USE_POINTS_FOR_TAX == 'true')) {
		  $products_price_points_query = tep_add_tax($products_price, $products_tax) * $quantity;
	  } else {
		  $products_price_points_query = $products_price * $quantity;
	  }

	  return $products_price_points_query;
  }

// calculate the shopping points for any products price
  function tep_calc_products_price_points($products_price_points_query) {

	  $products_points_total = $products_price_points_query * POINTS_PER_AMOUNT_PURCHASE;

	  return $products_points_total;
  }

// calculate the shopping points value for any products price
  function tep_calc_price_pvalue($products_points_total) {

	  $products_points_value = tep_calc_shopping_pvalue($products_points_total);

	  return($products_points_value);
  }

// products restriction by model.
  function get_redemption_rules($order) {

	  if (tep_not_null(RESTRICTION_MODEL)||tep_not_null(RESTRICTION_PID)||tep_not_null(RESTRICTION_PATH)) {
		  if (tep_not_null(RESTRICTION_MODEL)) {
		  $zwroc = false;
          for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
	          //if (!(substr($order->products[$i]['model'], 0, 10) == RESTRICTION_MODEL)) {
			  if ($order->products[$i]['model'] == RESTRICTION_MODEL) {
		          $zwroc = true;
	          }
          }
		  return $zwroc;
		  }

          if (tep_not_null(RESTRICTION_PID))
		  for ($i=0; $i<sizeof($order->products); $i++) {
			  $p_ids = split("[,]", RESTRICTION_PID);
			  for ($ii = 0; $ii < count($p_ids); $ii++) {
				  // znajdowanie id jezeli są cechy
				  $nr_id = $order->products[$i]['id'];
				  $tabl = explode('{', $nr_id);
				  $id_produktu = $tabl[0];
				  //
				  if ($id_produktu == $p_ids[$ii]) {
					  return true;
				  }
			  }
		  }

		  if (tep_not_null(RESTRICTION_PATH))
		  for ($i=0; $i<sizeof($order->products); $i++) {
			  $cat_ids = split("[,]", RESTRICTION_PATH);
			  $sub_cat_ids = split("[_]", tep_get_product_path($order->products[$i]['id']));
			   for ($iii = 0; $iii < count($sub_cat_ids); $iii++) {
				   for ($ii = 0; $ii < count($cat_ids); $ii++) {
					   if ($sub_cat_ids[$iii] == $cat_ids[$ii]) {
						   return true;
					   }
				   }
			   }
		   }
		   return false;
	   } else {
		   return true;
	   }
  }

// check to see if to add pending points for specials.
  function get_award_discounted($order) {

	  if (USE_POINTS_FOR_SPECIALS == 'false') {
		  for ($i=0; $i<sizeof($order->products); $i++) {
			  if (tep_get_products_special_price($order->products[$i]['id']) >0) {
				  return true;
			  }
		  }
		  return false;
	  } else {
		  return true;
	  }
  }

// products pending points to add.
  function get_points_toadd($order) {

    $points_toadd = 0;
    if ($order->info['total'] > 0) {
      for ($i=0; $i<sizeof($order->products); $i++) {
        if (tep_get_products_special_price($order->products[$i]['id']) > 0 && USE_POINTS_FOR_SPECIALS == 'false') {
        } else {
          if (USE_POINTS_FOR_TAX == 'true') {
            $points_toadd = $points_toadd + (tep_add_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']);
          } else {
            $points_toadd = $points_toadd + ($order->products[$i]['final_price']*$order->products[$i]['qty']);
          }
        }
      }

      if (USE_POINTS_FOR_SHIPPING != 'false') {
        $points_toadd = $points_toadd + $order->info['shipping_cost'];
      }
      return $points_toadd;
    } else {
      return false;
    }
  }

// sets the customers Pending points
  function tep_add_pending_points($customer_id, $insert_id, $points_toadd, $points_comment, $points_type) {

	  $points_awarded = ($points_type != 'SP') ? $points_toadd : $points_toadd * POINTS_PER_AMOUNT_PURCHASE;
      $points_awarded = (int)$points_awarded;

	  $sql_data_array = array('customer_id' => (int)$customer_id,
							  'orders_id' => (int)$insert_id,
							  'points_pending' => $points_awarded,
							  'date_added' => 'now()',
							  'points_comment' => $points_comment,
							  'points_type' => $points_type,
							  'points_status' => 1);
	  tep_db_perform(TABLE_CUSTOMERS_POINTS_PENDING, $sql_data_array);

	  $sql = "optimize table " . TABLE_CUSTOMERS_POINTS_PENDING . "";
  }

// balance customer points account & record the customers redeemed_points
  function tep_redeemed_points($customer_id, $insert_id, $customer_shopping_points_spending) {

	  if ((tep_get_shopping_points($customer_id) - $customer_shopping_points_spending) > 0) {
		  tep_db_query("update " . TABLE_CUSTOMERS . " set customers_shopping_points = customers_shopping_points - '". $customer_shopping_points_spending ."' where customers_id = '". (int)$customer_id ."' limit 1");
	  } else {
		  tep_db_query("update " . TABLE_CUSTOMERS . " set customers_shopping_points = 0, customers_points_expires = null where customers_id = '". (int)$customer_id ."' limit 1");
	  }

	  if (DISPLAY_POINTS_REDEEMED == 'true') {
		  $sql_data_array = array('customer_id' => (int)$customer_id,
                                  'orders_id' => (int)$insert_id,
                                  'points_pending' => - $customer_shopping_points_spending,
                                  'date_added' => 'now()',
                                  'points_comment' => 'TEXT_DEFAULT_REDEEMED',
                                  'points_type' => 'SP',
                                  'points_status' => 4);
          tep_db_perform(TABLE_CUSTOMERS_POINTS_PENDING, $sql_data_array);

          $sql = "optimize table " . TABLE_CUSTOMERS_POINTS_PENDING . "";
      }
  }

// sets the new signup customers welcome points
  function tep_add_welcome_points($customer_id) {

	  $welcome_points = NEW_SIGNUP_POINT_AMOUNT;

	  if (tep_not_null(POINTS_AUTO_EXPIRES)) {
		  tep_db_query("update " . TABLE_CUSTOMERS . " set customers_shopping_points = customers_shopping_points + '" . $welcome_points . "', customers_points_expires = DATE_ADD(NOW(),INTERVAL '" . POINTS_AUTO_EXPIRES . "' MONTH) where customers_id = '" . (int)$customer_id . "' limit 1");
	  } else {
		  tep_db_query("update " . TABLE_CUSTOMERS . " set customers_shopping_points = customers_shopping_points + '" . $welcome_points . "' where customers_id = '" . (int)$customer_id . "' limit 1");
	  }
  }

// get the last update value for any key
  function tep_get_last_date($key) {

	  $key_date_query = tep_db_query("select last_modified from " . TABLE_CONFIGURATION . " where configuration_key = '". $key ."' limit 1");
      $key_date = tep_db_fetch_array($key_date_query);

      return tep_date_long($key_date['last_modified']);
  }

// products discounted restriction if enabled.
  function get_points_rules_discounted($order) {

	  if (REDEMPTION_DISCOUNTED == 'true') {
		  for ($i=0; $i<sizeof($order->products); $i++) {
			  if (tep_get_products_special_price($order->products[$i]['id']) >0) {
				  return false;
			  }
		  }
		  return true;
	  } else {
		  return true;
	  }
  }

  function get_redemption_awards($customer_shopping_points_spending) {
	  global $order;

	  if (USE_POINTS_FOR_REDEEMED == 'false') {
		  if (!tep_not_null($customer_shopping_points_spending)) {
			  return true;
		  }
		  return false;
	  } else {
		  return true;
	  }
  }

  function calculate_max_points($customer_shopping_points) {
	  global $currencies, $order;

	  $max_points = $order->info['subtotal']/REDEEM_POINT_VALUE;

	  if (REDEMPTION_DISCOUNTED == 'true') {
		  $special_points = 0;
		  for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
		      // dodawanie vatu do ceny
			  if (CZY_OBLICZAC_UPUST_DLA_PROMOCJI == true) {
				$cena_promocyjna = pokaz_upust(tep_get_products_special_price($order->products[$i]['id']),$order->products[$i]['id']);
				} else {
				$cena_promocyjna = tep_get_products_special_price($order->products[$i]['id']);
			  }
			  $special_price = tep_add_tax($cena_promocyjna,$order->products[$i]['tax']);
			  //
              if ($special_price > 0) {
                  $special_points = $special_points + (($special_price*$order->products[$i]['qty'])/REDEEM_POINT_VALUE);
                  $max_points = $max_points - (($special_price*$order->products[$i]['qty'])/REDEEM_POINT_VALUE);
              }
          }
      }

      if (tep_not_null(RESTRICTION_MODEL)) {
	      $model_points = 0;
	      for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
              if ($order->products[$i]['model'] != RESTRICTION_MODEL) {
	              //$model_price = $order->products[$i]['price'];
				  // dodawanie vatu do ceny
				  $cena_prod = $order->products[$i]['price'];
				  $model_price = tep_add_tax($cena_prod,$order->products[$i]['tax']);
				  //
                  $model_points = $model_points + (($model_price*$order->products[$i]['qty'])/REDEEM_POINT_VALUE);
                  $max_points = $max_points - (($model_price*$order->products[$i]['qty'])/REDEEM_POINT_VALUE);
              }
          }
      }

      if (tep_not_null(RESTRICTION_PID) && !tep_not_null(RESTRICTION_MODEL)) {
	      $pid_points = 0;
	      for ($i=0; $i<sizeof($order->products); $i++) {
		      $p_ids = split("[,]", RESTRICTION_PID);
		      for ($ii = 0; $ii < count($p_ids); $ii++) {
				  // znajdowanie id jezeli są cechy
				  $nr_id = $order->products[$i]['id'];
				  $tabl = explode('{', $nr_id);
				  $id_produktu = $tabl[0];
				  //
			      if ($id_produktu == $p_ids[$ii]) {
					  // dodawanie vatu do ceny
					  $cena_prod = $order->products[$i]['price'];
					  $prod_price = tep_add_tax($cena_prod,$order->products[$i]['tax']);
					  //
					  $path_points = $path_points + ($prod_price*$order->products[$i]['qty']);
					  $max_points =  $path_points/REDEEM_POINT_VALUE;
			      }
		      }
	      }
		  $path_points = $path_points + $order->info['shipping_cost'];
		  $max_points =  $path_points/REDEEM_POINT_VALUE;
      }

      if (tep_not_null(RESTRICTION_PATH) && !tep_not_null(RESTRICTION_PID) && !tep_not_null(RESTRICTION_MODEL)) {
	      $path_points = 0;
	      for ($i=0; $i<sizeof($order->products); $i++) {
		      $cat_ids = split("[,]", RESTRICTION_PATH);
		      $sub_cat_ids = split("[_]", tep_get_product_path($order->products[$i]['id']));
		      for ($iii = 0; $iii < count($sub_cat_ids); $iii++) {
			      for ($ii = 0; $ii < count($cat_ids); $ii++) {
				      if ($sub_cat_ids[$iii] == $cat_ids[$ii]) {
					      // dodawanie vatu do ceny
						  $cena_prod = $order->products[$i]['price'];
						  $prod_price = tep_add_tax($cena_prod,$order->products[$i]['tax']);
						  //
					      $path_points = $path_points + ($prod_price*$order->products[$i]['qty']);
					      $max_points =  $path_points/REDEEM_POINT_VALUE;
				      }
			      }
		      }
	      }
		  $path_points = $path_points + $order->info['shipping_cost'];
		  $max_points =  $path_points/REDEEM_POINT_VALUE;
      }

      if (tep_not_null(POINTS_MAX_VALUE)) {
         $max_points = $max_points > POINTS_MAX_VALUE ? POINTS_MAX_VALUE : $max_points;
      }
      $max_points = $customer_shopping_points > $max_points ? $max_points : $customer_shopping_points;

      return $max_points;
  }

  function points_selection() {
	  global $currencies, $order, $cart;

	  if (($customer_shopping_points = tep_get_shopping_points()) && $customer_shopping_points > 0) {
		  if (get_redemption_rules($order) && (get_points_rules_discounted($order) || get_cart_mixed($order))) {
			  if ($customer_shopping_points >= POINTS_LIMIT_VALUE) {
				  if ((POINTS_MIN_AMOUNT == '') || ($cart->show_total() >= POINTS_MIN_AMOUNT) ) {
					  if (tep_session_is_registered('customer_shopping_points_spending')) tep_session_unregister('customer_shopping_points_spending');

					  $max_points = calculate_max_points($customer_shopping_points);
					  if ((int)$order->info['subtotal'] > (int)tep_calc_shopping_pvalue($max_points)) {
						  $note = '<br><small>' . TEXT_REDEEM_SYSTEM_NOTE.'</small>';
					  }

					  $customer_shopping_points_spending = $max_points;
?>
  <tr>
    <td>
      <fieldset>
      <legend><?php echo TABLE_HEADING_REDEEM_SYSTEM; ?></legend>
			<table border="0" width="100%" cellspacing="0" cellpadding="2">
              <tr>
                <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
                <td class="main"><?php printf(TEXT_REDEEM_SYSTEM_START, $currencies->format(tep_calc_shopping_pvalue($customer_shopping_points)), $currencies->format($order->info['subtotal']). $note); ?></td>
                <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
                <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?>
                  <script type="text/javascript" language="javascript">
                  function punkty() {
                  var element = document.forms['checkout_address'].customer_shopping_points_spending;
                  if (element.checked == true) { element.checked = false; submitter = 0; } else { element.checked = true; submitter = 1;}}
                  </script>
                </td>
             </tr>
             <tr class="moduleRow" onmouseover="if (this.className!='moduleRowSelected') { this.className='moduleRowOver'; }" onmouseout="if (this.className!='moduleRowSelected') { this.className='moduleRow'; }" onclick="punkty()">
               <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
               <td class="main"><?php printf(TEXT_REDEEM_SYSTEM_SPENDING, number_format($max_points,POINTS_DECIMAL_PLACES), $currencies->format(tep_calc_shopping_pvalue($max_points))); ?></td>
               <td class="main" align="right"><?php echo tep_draw_checkbox_field('customer_shopping_points_spending', $customer_shopping_points_spending,'',' id="customer_shopping_points_spending" onclick="punkty();"'); ?><input type="hidden" name="points_kwota" value="<?php echo tep_calc_shopping_pvalue($customer_shopping_points_spending) ?>"><input type="hidden" name="suma" value="<?php echo $order->info['subtotal'] ?>"></td>
               <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
             </tr>
             <tr>
               <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
               <td class="main">
                  <script language="javascript" type="text/javascript">
                  function max_wart() {
                  wpisane = document.getElementById('customer_shopping_points_spending').value;
                  maksymalne = document.getElementById('points_max').value;
                  if (parseInt(wpisane) > parseInt(maksymalne)) {
                    okno('<?php echo REDEEM_SYSTEM_ERROR_POINTS_OVER; ?>');
                    document.getElementById('customer_shopping_points_spending').value =maksymalne;
                    document.getElementById('ile_punktow').value = maksymalne;
                  }
                  }
                  </script>
                  <input type="hidden" id="points_max" name="points_max" value="<?php echo $customer_shopping_points_spending ?>">
                  <?php echo TEXT_ILOSC_PKT; ?>&nbsp;&nbsp;
                  <?php echo tep_draw_input_field('ile_punktow', round($customer_shopping_points_spending),' id="ile_punktow" onchange="document.getElementById(\'customer_shopping_points_spending\').value = this.value; max_wart()"'); ?></td>
                <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
              </tr>
       </table>
       </fieldset>
    </td>
  </tr>
<?php
				  }
			  }
		  }
	  }
  }

  function referral_input() {
	  global $currencies, $order;

	  if (tep_not_null(USE_REFERRAL_SYSTEM)) {
?>
    <tr>
	 <td>
      <fieldset>
      <legend><?php echo TABLE_HEADING_REFERRAL; ?></legend>
          <table border="0" width="100%" cellspacing="5" cellpadding="2">
			<tr>
			  <td class="main"><?php echo TEXT_REFERRAL_REFERRED; ?></td>
			  <td class="main"><?php echo tep_draw_input_field('customer_referred', $customer_referred, ' size="30"'); ?><input type="hidden" name="mail_adres" value="<?php echo $order->customer['email_address'] ?>"></td>
			</tr>
		  </table>
	   </fieldset>
	 </td>
    </tr>
<?php
	  }
  }

// products discounted and normal products in cart?
  function get_cart_mixed($order) {

	  if (sizeof($order->products) >1) {
		  $special = false;
		  $normal = false;
		  for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
			  if (tep_get_products_special_price($order->products[$i]['id']) >0) {
				  $special = true;
			  } else {
				  $normal = true;
			  }
		  }

		  if ($special == true && $normal == true) {
			  return true;
		  } else {
			  return false;
		  }

		  return false;
	  }
  }

// podaje cene produktu po upustach
function pokaz_upust($cena,$products_id) {
global $customer_id;
//
$query_price_to_guest_result = ALLOW_GUEST_TO_SEE_PRICES;
if (($query_price_to_guest_result=='true') && !(tep_session_is_registered('customer_id'))) {
	$query_guest_discount_result = GUEST_DISCOUNT;
	$customer_discount = $query_guest_discount_result;
	if ($customer_discount >= 0) {
		$cena = $cena + $cena * abs($customer_discount) / 100;
	} else {
		$cena = $cena - $cena * abs($customer_discount) / 100;
	}
} elseif (tep_session_is_registered('customer_id')) {
	$query_A = tep_db_query("select m.manudiscount_discount from " . TABLE_MANUDISCOUNT .  " m, " . TABLE_PRODUCTS . " p where m.manudiscount_groups_id = 0 and m.manudiscount_customers_id = '" . $customer_id . "' and p.products_id = '" . $products_id . "' and p.manufacturers_id = m.manudiscount_manufacturers_id");
	$query_B = tep_db_query("select m.manudiscount_discount from " . TABLE_CUSTOMERS  . " c, " . TABLE_MANUDISCOUNT .  " m, " . TABLE_PRODUCTS . " p where m.manudiscount_groups_id = c.customers_groups_id  and m.manudiscount_customers_id = 0 and c.customers_id = '" . $customer_id . "' and p.products_id = '" . $products_id . "' and p.manufacturers_id = m.manudiscount_manufacturers_id");
	$query_C = tep_db_query("select m.manudiscount_discount from " . TABLE_MANUDISCOUNT .  " m, " . TABLE_PRODUCTS . " p where m.manudiscount_groups_id = 0 and m.manudiscount_customers_id = 0 and p.products_id = '" . $products_id . "' and p.manufacturers_id = m.manudiscount_manufacturers_id");
	if ($query_result = tep_db_fetch_array($query_A)) {
		$customer_discount = $query_result['manudiscount_discount'];
	} else if ($query_result = tep_db_fetch_array($query_B)) {
		$customer_discount = $query_result['manudiscount_discount'];
	} else if ($query_result = tep_db_fetch_array($query_C)) {
		$customer_discount = $query_result['manudiscount_discount'];
	} else {
		$query = tep_db_query("select g.customers_groups_discount 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_discount = $query_result['customers_groups_discount'];
		$query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
		$query_result = tep_db_fetch_array($query);
		$customer_discount = $query_result['customers_discount'];
		$customer_discount = $customer_discount + $customers_groups_discount;
	}
	if ($customer_discount >= 0) {
		$cena = $cena + $cena * abs($customer_discount) / 100;
	} else {
		$cena = $cena - $cena * abs($customer_discount) / 100;
	}
}
return $cena;
}
?>