<?php
/*
  $Id: ot_coupon.php,v 1.8 2003/02/01 19:47:08 wilt Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2002 osCommerce

  Released under the GNU General Public License
*/

  class ot_coupon {
    var $title, $output;

    function ot_coupon() {

      $this->code = 'ot_coupon';
      $this->title = MODULE_ORDER_TOTAL_COUPON_TITLE;
      $this->description = MODULE_ORDER_TOTAL_COUPON_DESCRIPTION;
      $this->user_prompt = ''; 
      $this->enabled = MODULE_ORDER_TOTAL_COUPON_STATUS;
      $this->sort_order = MODULE_ORDER_TOTAL_COUPON_SORT_ORDER;
      $this->include_shipping = MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING;
      $this->include_tax = MODULE_ORDER_TOTAL_COUPON_INC_TAX;
      $this->calculate_tax = MODULE_ORDER_TOTAL_COUPON_CALC_TAX;
      $this->credit_class = true;
      $this->output = array();

    }

  function process() {
    global $order, $currencies;
    $order_total=$this->get_order_total();
    $od_amount = $this->calculate_credit($order_total);
    $this->deduction = $od_amount;
    if ($this->calculate_tax == 'true') {
      $tod_amount = $this->calculate_tax_deduction($order_total, $this->deduction);

    }
    if ($od_amount > 0) {
      $order->info['total'] = $order->info['total'] - $od_amount;
      $this->output[] = array('title' => $this->title . ':' . $this->coupon_code .':',
                     'text' => '<b>' . $currencies->format($od_amount) . '</b>',
                     'value' => $od_amount);
    }
  }
    
  function selection_test() {
    return false;
  }
    
     
  function pre_confirmation_check($order_total) {
    global $customer_id;
    return $this->calculate_credit($order_total);
    }

  function use_credit_amount() {
    $output_string = ' <tr class="moduleRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" >' . "\n" .
                      '<td width="10">' .  tep_draw_separator('pixel_trans.gif', '10', '1') .'</td>' .                             
                      '    <td class="main"><b>' . $this->title . '</b>';
    if ($this->include_shipping == 'false') $output_string .= SHIPPING_NOT_INCLUDED;
    if ($this->include_tax == 'false') $output_string .= TAX_NOT_INCLUDED;
    $output_string .= '</td>' . "\n" .  '    <td align="right" class="main">';
    if ($this->selection_test()) {
      $output_string .= '<b>' . $this->checkbox . '</b>' . '</td>' . "\n";
    }
    $output_string .= '<td width="10">' .  tep_draw_separator('pixel_trans.gif', '10', '1') .'</td>'; 
    $output_string .= '  </tr>' . "\n";  
    return $output_string;
  }
  

    function credit_selection() {
      global  $language;
      $selection_string = '';
        $selection_string .= '<tr>' . "\n";
        $selection_string .= '<td width="10">' .  tep_draw_separator('pixel_trans.gif', '10', '1') .'</td>';                             
        $selection_string .= '<td class="main">' . "\n";
        $image_submit = '<input type="image" name="submit_redeem_coupon" onClick="submitFunction()" src="' . DIR_WS_LANGUAGES . $language . '/images/buttons/button_redeem.gif" border="0" alt="' . TEXT_REDEEM_COUPON . '">';
        $selection_string .= ENTER_REDEEM_COUPON . 
                           tep_draw_input_field('coupon_redeem_code') . '</td>';
        $selection_string .= '<td align="right"' . $image_submit . '</td>';
        $selection_string .= '<td width="10">' .  tep_draw_separator('pixel_trans.gif', '10', '1') .'</td>';                             
        $selection_string .= '</tr>' . "\n";
    return $selection_string;
    }

    
  function collect_posts() {
    global $HTTP_POST_VARS, $customer_id, $currencies;
    if ($HTTP_POST_VARS['coupon_redeem_code']) {

// get some info from the coupon table
    $coupon_query=tep_db_query("select name, amount, type, min_order, uses_coupon, uses_user, products, categories, use_count from cc_coupons where code='".$HTTP_POST_VARS['coupon_redeem_code']."' and coupon_active='Y'");
    if (tep_db_num_rows($coupon_query)==0) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_NO_INVALID_REDEEM_COUPON), 'SSL'));
    }
    $date_query=tep_db_query("select startdate from cc_coupons where startdate <= now() and code='".$HTTP_POST_VARS['coupon_redeem_code']."'");
    if (tep_db_num_rows($date_query)==0) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_INVALID_STARTDATE_COUPON), 'SSL'));
    }
    $date_query=tep_db_query("select finishdate from cc_coupons where finishdate >= now() and code='".$HTTP_POST_VARS['coupon_redeem_code']."'");
    if (tep_db_num_rows($date_query)==0) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_INVALID_FINISDATE_COUPON), 'SSL'));
    }  
    $coupon_result=tep_db_fetch_array($coupon_query);
    if ($coupon_result['use_count']>=$coupon_result['uses_coupon'] && $coupon_result['uses_coupon'] > 0) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_INVALID_USES_COUPON . $coupon_result['uses_coupon'] . TIMES ), 'SSL'));
    }
    $coupon_amount = $currencies->format($coupon_result['amount']) . ' ';
    if ($coupon_result['type']=='P') $coupon_amount = $coupon_result['amount'] . '% ';
    if ($coupon_result['min_order']>0) $coupon_amount .= 'on orders greater than ' .  $coupon_result['min_order'];     
    $track_query=tep_db_query("select use_count from cc_coupon_track where customer_id='".$customer_id."' and coupon_code='".$HTTP_POST_VARS['coupon_redeem_code']."'");
    if (tep_db_num_rows($track_query) !=0) {
      $track_result = tep_db_fetch_array($track_query);
      if ($track_result['use_count']>=$coupon_result['uses_user'] && $coupon_result['uses_user'] > 0) {
        tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_INVALID_USES_USER_COUPON), 'SSL'));
      }
    }
    $tmp_query = tep_db_query("select customer_id from cc_coupon_temp where customer_id = '".$customer_id."'");
    if (tep_db_num_rows($tmp_query) !=0) {
    $delete_query = tep_db_query("delete from cc_coupon_temp where customer_id = '" . $customer_id . "'");

//      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_INVALID_USES_REDEEM_COUPON), 'SSL'));
    }    
    $insert_query = tep_db_query("insert into cc_coupon_temp (customer_id, coupon_code) values ('".$customer_id."', '".$HTTP_POST_VARS['coupon_redeem_code']."')");  
    if ($coupon_result['min_order'] > 0) $coupon_extra = REDEEMED_MIN_ORDER . $currencies->format($coupon_result['min_order']);
    if ($coupon_result['products'] || $coupon_result['categories']) $coupon_extra .= REDEEMED_RESTRICTIONS;
//    tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_REEDEEMED_AMOUNT.REDEEMED_COUPON.$coupon_amount.' '.$coupon_extra), 'SSL'));
    }
    if ($HTTP_POST_VARS['submit_redeem_coupon_x'] && !$HTTP_POST_VARS['coupon_redeem_code']) tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_NO_REDEEM_CODE. $coupon_amount), 'SSL'));   
  }  
   
  function calculate_credit($amount) {
    global $customer_id, $order;
    $od_amount = 0;
    $coupon_query = tep_db_query("select coupon_code from cc_coupon_temp where customer_id = '" . $customer_id . "'");
    if (tep_db_num_rows($coupon_query) !=0 ) {
      $coupon_result = tep_db_fetch_array($coupon_query);
    $this->coupon_code = $coupon_result['coupon_code'];
     $coupon_get = tep_db_query("select amount, min_order, products, categories, type from cc_coupons where code = '". $coupon_result['coupon_code'] . "'");
      $get_result = tep_db_fetch_array($coupon_get);
      if ($get_result['min_order'] <= $this->get_order_total()) {
        if ($get_result['products'] || $get_result['categories']) {
          for ($i=0; $i<sizeof($order->products); $i++) {
            if ($get_result['products']) {
              $pr_ids = split("[,]", $get_result['products']);
              for ($ii = 0; $ii < count($pr_ids); $ii++) {
                if ($pr_ids[$ii] == tep_get_prid($order->products[$i]['id'])) {
                  if ($get_result['type'] == 'P') {
                    $od_amount = round($amount*10)/10*$get_result['amount']/100;
                    $pr_c = $order->products[$i]['final_price']*$order->products[$i]['qty'];
                    $pod_amount = round($pr_c*10)/10*$get_result['amount']/100;
                  } else {
                    $od_amount = $get_result['amount'];
                  }
                }
              }         
            } else {
              $cat_ids = split("[,]", $get_result['categories']);
              for ($i=0; $i<sizeof($order->products); $i++) {
                $my_path = tep_get_product_path(tep_get_prid($order->products[$i]['id']));
                $sub_cat_ids = split("[_]", $my_path);
                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]) {
                      if ($get_result['type'] == 'P') {
                        $od_amount = round($amount*10)/10*$get_result['amount']/100;
                        $pr_c = $order->products[$i]['final_price']*$order->products[$i]['qty'];
                        $pod_amount = round($pr_c*10)/10*$get_result['amount']/100;
                      } else {
                        $od_amount = $get_result['amount'];
                      }                        
                    }
                  }
                }
              } 
            }
          }
        } else {
          if ($get_result['type'] !='P') {
            $od_amount = $get_result['amount'];                  
          } else {
//            echo $get_result['amount'] . ':' . $amount . ':';
            $od_amount = $amount * $get_result['amount'] / 100;
//            echo $od_amount;
          }
        }
      }
    }
    if ($od_amount>$amount) $od_amount = $amount;
    return $od_amount;
  }
  
  function calculate_tax_deduction($amount, $od_amount) {
    global $customer_id, $order;
    $coupon_query = tep_db_query("select coupon_code from cc_coupon_temp where customer_id = '" . $customer_id . "'");
    if (tep_db_num_rows($coupon_query) !=0 ) {
      $coupon_result = tep_db_fetch_array($coupon_query);
      $coupon_get = tep_db_query("select amount, min_order, products, categories, type from cc_coupons where code = '". $coupon_result['coupon_code'] . "'");
      $get_result = tep_db_fetch_array($coupon_get);
      if ($get_result['products'] || $get_result['categories']) {

      } else {
        if ($get_result['type'] !='P') {
          $tod_amount = 0;
          reset($order->info['tax_groups']);
          while (list($key, $value) = each($order->info['tax_groups'])) {
            $net = $key * $order->info['tax_groups'][$key];
            if ($net>0) $ratio1 = $od_amount/$net;
            $god_amount = $order->info['tax_groups'][$key] * $ratio1;
            $tod_amount += $god_amount;
            $order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount;
          }           
          $order->info['tax'] -= $tod_amount;
          $order->info['total'] -= $tod_amount;
        } else {
          $tod_amount=0;
          reset($order->info['tax_groups']);
          while (list($key, $value) = each($order->info['tax_groups'])) {
            $god_amout=0;
            $net = $key * $order->info['tax_groups'][$key];
            if ($net>0) $god_amount = $order->info['tax_groups'][$key] * $get_result['amount']/100;
            $tod_amount += $god_amount;
            $order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount;
          }           
          $order->info['tax'] -= $tod_amount;
          $order->info['total'] -= $tod_amount; 
        }
      }
    }
    return $tod_amount;
  }

function update_credit_account($i) {
 }
    
 function apply_credit() {
   global $customer_id;
// OK Coupon used - Things to do
// Remove temp Entry
// update tracking entry
// update coupon count entry
    if ($this->deduction !=0) {
    $tmp_query=tep_db_query("select coupon_code from cc_coupon_temp where customer_id = '" . $customer_id . "'");
    if (tep_db_num_rows($tmp_query) !=0) {
      $tmp_result = tep_db_fetch_array($tmp_query);
      $coupon_code = $tmp_result['coupon_code'];
      $del_query=tep_db_query("delete from cc_coupon_temp where customer_id = '" . $customer_id ."'");
      $track_query=tep_db_query("select use_count from cc_coupon_track where customer_id = '" . $customer_id . "' and coupon_code = '" . $coupon_code . "'");
      if (tep_db_num_rows($track_query) !=0 ) {
        $track_result = tep_db_fetch_array($track_query);
        $use_count = $track_result['use_count']+1;
        tep_db_query("update cc_coupon_track set use_count = '" . $use_count . "' where coupon_code = '" . $coupon_code . "'"); 
      } else {
        tep_db_query("insert into cc_coupon_track (coupon_code, use_count, customer_id) values ('" . $coupon_code . "', '1', '" . $customer_id . "')");  
      }
      $c_query = tep_db_query("select use_count from cc_coupons where code = '" . $coupon_code . "'");
      $c_result = tep_db_fetch_array($c_query);
      $use_count = $c_result['use_count'] + 1;
      tep_db_query("update cc_coupons set use_count = '". $use_count . "' where code = '" . $coupon_code . "'");      
    }
}
  }   
  
  function get_order_total() {
    global  $order, $cart, $customer_id;
    $order_total = $order->info['total'];
// Check if gift voucher is in cart and adjust total
    $products = $cart->get_products();
    for ($i=0; $i<sizeof($products); $i++) {
      $t_prid = tep_get_prid($products[$i]['id']);
      $gv_query = tep_db_query("select products_price, products_tax_class_id, products_model from " . TABLE_PRODUCTS . " where products_id = '" . $t_prid . "'");
      $gv_result = tep_db_fetch_array($gv_query);
      if (ereg('^GIFT', addslashes($gv_result['products_model']))) { 
        $qty = $cart->get_quantity($t_prid);
        $products_tax = tep_get_tax_rate($gv_result['products_tax_class_id']);
        if ($this->include_tax =='false') {
           $gv_amount = $gv_result['products_price'] * $qty;
        } else {
          $gv_amount = ($gv_result['products_price'] + tep_calculate_tax($gv_result['products_price'],$products_tax)) * $qty;
        }
        $order_total=$order_total - $gv_amount;
      }
    }
    if ($this->include_tax == 'false') $order_total=$order_total-$order->info['tax'];
//    echo $order->info['tax'];
    if ($this->include_shipping == 'false') $order_total=$order_total-$order->info['shipping_cost'];
// OK thats fine for global coupons but what about restricted coupons 
// where you can only redeem against certain products/categories.
// and I though this was going to be easy !!!
   $coupon_query=tep_db_query("select coupon_code  from cc_coupon_temp where customer_id='".$customer_id."'");
   if (tep_db_num_rows($coupon_query) !=0) {
     $coupon_result=tep_db_fetch_array($coupon_query);
     $coupon_get=tep_db_query("select amount, min_order,products,categories, type from cc_coupons where code='".$coupon_result['coupon_code']."'");
     $get_result=tep_db_fetch_array($coupon_get);
     $in_cat = true;
     if ($get_result['categories']) {
       $cat_ids = split("[,]", $get_result['categories']);
       $in_cat=false;
       for ($i = 0; $i < count($cat_ids); $i++) {
         if (is_array($this->contents)) {
           reset($this->contents);
           while (list($products_id, ) = each($this->contents)) {
            $cat_query = tep_db_query("select products_id from products_to_categories where products_id = '" . $products_id . "' and categories_id = '" . $cat_ids[$i] . "'");
             if (tep_db_num_rows($cat_query) !=0 ) {
               $in_cat = true;
               $total_price += $this->get_product_price($products_id);
             }
           }
         }      
       }          
     }
     $in_cart = true;
     if ($get_result['products']) {

       $pr_ids = split("[,]", $get_result['products']);

       $in_cart=false;
       $products_array = $cart->get_products();

       for ($i = 0; $i < sizeof($pr_ids); $i++) {
         for ($ii = 1; $ii<=sizeof($products_array); $ii++) {
           if (tep_get_prid($products_array[$ii-1]['id']) == $pr_ids[$i]) {
             $in_cart=true;
             $total_price += $this->get_product_price($products_array[$ii-1]['id']);
           }
         } 
       }
       $order_total = $total_price;         
     }
   }
   return $order_total;
  }   

function get_product_price($product_id) {
    global $cart; 
 // products price
    $qty = $cart->contents[$product_id]['qty'];
    $product_query = tep_db_query("select products_id, products_price, products_tax_class_id, products_weight from " . TABLE_PRODUCTS . " where products_id='" . $product_id . "'");
    if ($product = tep_db_fetch_array($product_query)) {
      $prid = $product['products_id'];
      $products_tax = tep_get_tax_rate($product['products_tax_class_id']);
      $products_price = $product['products_price'];
      $specials_query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id = '" . $prid . "' and status = '1'");
      if (tep_db_num_rows ($specials_query)) {
        $specials = tep_db_fetch_array($specials_query);
        $products_price = $specials['specials_new_products_price'];
      }
      if ($this->include_tax == 'true') {
        $total_price += ($products_price + tep_calculate_tax($products_price, $products_tax)) * $qty;
      } else {
        $total_price += $products_price * $qty;
      }

// attributes price
      if ($cart->contents[$products_id]['attributes']) {
        reset($cart->contents[$products_id]['attributes']);
        while (list($option, $value) = each($this->contents[$products_id]['attributes'])) {
          $attribute_price_query = tep_db_query("select options_values_price, price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . $prid . "' and options_id = '" . $option . "' and options_values_id = '" . $value . "'");
          $attribute_price = tep_db_fetch_array($attribute_price_query);
          if ($attribute_price['price_prefix'] == '+') {
            if ($this->include_tax == 'true') {
              $total_price += $qty * ($attribute_price['options_values_price'] + tep_calculate_tax($attribute_price['options_values_price'], $products_tax));
            } else {
              $total_price += $qty * ($attribute_price['options_values_price']);
            }
          } else {
            if ($this->include_tax == 'true') {
              $total_price -= $qty * ($attribute_price['options_values_price'] + tep_calculate_tax($attribute_price['options_values_price'], $products_tax));
            } else {
              $total_price -= $qty * ($attribute_price['options_values_price']);
            }
          }
        }
      }
    }
    return $total_price;  
}
        
    function check() {
      if (!isset($this->check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_ORDER_TOTAL_COUPON_STATUS'");
        $this->check = tep_db_num_rows($check_query);
      }

      return $this->check;
    }

    function keys() {
      return array('MODULE_ORDER_TOTAL_COUPON_STATUS', 'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER', 'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING', 'MODULE_ORDER_TOTAL_COUPON_INC_TAX', 'MODULE_ORDER_TOTAL_COUPON_CALC_TAX');
    }

    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Display Total', 'MODULE_ORDER_TOTAL_COUPON_STATUS', 'true', 'Do you want to enable Discount Coupons?', '6', '1','tep_cfg_select_option(array(\'true\', \'false\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER', '9', 'Sort order of display.', '6', '2', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Include Shipping', 'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING', 'true', 'Include Shipping in calculation', '6', '5', 'tep_cfg_select_option(array(\'true\', \'false\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Include Tax', 'MODULE_ORDER_TOTAL_COUPON_INC_TAX', 'true', 'Include Tax in calculation.', '6', '6','tep_cfg_select_option(array(\'true\', \'false\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function ,date_added) values ('Re-calculate Tax', 'MODULE_ORDER_TOTAL_COUPON_CALC_TAX', 'false', 'Re-Calculate Tax', '6', '7','tep_cfg_select_option(array(\'true\', \'false\'), ', now())");
    }

    function remove() {
      $keys = '';
      $keys_array = $this->keys();
      for ($i=0; $i<sizeof($keys_array); $i++) {
        $keys .= "'" . $keys_array[$i] . "',";
      }
      $keys = substr($keys, 0, -1);

      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in (" . $keys . ")");
    }
  }
?>