<?php
/*
  $Id: ot_gv.php,v 1.12 2003/02/01 19:41:07 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_gv {
    var $title, $output;

    function ot_gv() {
      $this->code = 'ot_gv';
      $this->title = MODULE_ORDER_TOTAL_GV_TITLE;
      $this->description = MODULE_ORDER_TOTAL_GV_DESCRIPTION;
      $this->user_prompt = MODULE_ORDER_TOTAL_GV_USER_PROMPT; 
      $this->enabled = MODULE_ORDER_TOTAL_GV_STATUS;
      $this->sort_order = MODULE_ORDER_TOTAL_GV_SORT_ORDER;
      $this->include_shipping = MODULE_ORDER_TOTAL_GV_INC_SHIPPING;
      $this->include_tax = MODULE_ORDER_TOTAL_GV_INC_TAX;
      $this->calculate_tax = MODULE_ORDER_TOTAL_GV_CALC_TAX;
      $this->credit_tax = MODULE_ORDER_TOTAL_GV_CREDIT_TAX;
      $this->show_redeem_box = MODULE_ORDER_TOTAL_GV_REDEEM_BOX;
      $this->credit_class = true;
      $this->checkbox = $this->user_prompt . '<input type="checkbox" onClick="submitFunction()" name="'. 'c_'.$this->code . '">';
      $this->output = array();
    }

    function process() {
      global $order, $currencies;
      if ($GLOBALS['c_'.$this->code]) {
        $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);
          $od_amount = $this->calculate_credit($order_total - $tod_amount);

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


  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";
    if ($this->selection_test()) {
      $output_string .=  '    <td align="right" class="main">';
      $output_string .= '<b>' . $this->checkbox . '</b>' . '</td>' . "\n";
    } else {
    $output_string .= '<td>&nbsp;</td>';
    }
    $output_string .= '<td width="10">' .  tep_draw_separator('pixel_trans.gif', '10', '1') .'</td>'; 
    $output_string .= '  </tr>' . "\n"; 
    return $output_string;
  }

 
    function update_credit_account($i) {
      global $order, $customer_id, $insert_id;
      if (ereg('^GIFT', addslashes($order->products[$i]['model']))) {
        $gv_order_amount = ($order->products[$i]['final_price']*$order->products[$i]['qty']);
        if ($this->credit_tax=='true') $gv_order_amount = $gv_order_amount * (100+$order->products[$i]['tax'])/100;
        $gv_order_amount += 0.001;
        $gv_order_amount=round($gv_order_amount*100)/100;
        if (GV_IMMEDIATE) {
          // GV_IMMEDIATE is true so release amount to account immediately
          $gv_query=tep_db_query("select amount from ".TABLE_GV_CUSTOMER." where customer_id='".$customer_id."'");
          $customer_gv=false;
          $total_gv_amount=0;
          if ($gv_result=tep_db_fetch_array($gv_query)) {
            $total_gv_amount=$gv_result['amount'];
            $customer_gv=true;
          }     
          $total_gv_amount=$total_gv_amount+$gv_order_amount;
          if ($customer_gv) {
            $gv_update=tep_db_query("update ".TABLE_GV_CUSTOMER." set amount='".$total_gv_amount."' where customer_id='".$customer_id."'");
          } else {
            $gv_insert=tep_db_query("insert into ".TABLE_GV_CUSTOMER." (customer_id, amount) values ('".$customer_id."','".$total_gv_amount."')");
          }
          } else {
         // GV_IMMEDIATE is false - so queue the gv for release by store owner
         $gv_insert=tep_db_query("insert into ".TABLE_GV_QUEUE." (customer_id,order_id,amount,date_created,ipaddr) values(
                              '".$customer_id."','".$insert_id."','".$gv_order_amount."',NOW(),'".$REMOTE_ADDR."')");
        }
      }
    }
    
    
    function credit_selection() {
      global $customer_id, $currencies, $language;
      $selection_string = '';

        $gv_query=tep_db_query("select amount from ".TABLE_GV_CUSTOMER." where customer_id='".$customer_id."'");
        $gv_result=tep_db_fetch_array($gv_query);
        $gv_amount = $gv_result['amount'];
        $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" onClick="submitFunction()" src="' . DIR_WS_LANGUAGES . $language . '/images/buttons/button_redeem.gif" border="0" alt="' . TEXT_REDEEM_VOUCHER . '">';
        $selection_string .= ENTER_VOUCHER_CODE . 
                           tep_draw_input_field('gv_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 pre_confirmation_check($order_total) {
   if ($GLOBALS['c_'.$this->code]) {
       $gv_payment_amount = $this->calculate_credit($order_total);
   }
      return $gv_payment_amount;
    }
    
 function apply_credit() {
    global $order,$customer_id;
    if ($GLOBALS['c_'.$this->code]) {
      $gv_query=tep_db_query("select amount from gv_customer where customer_id='".$customer_id."'");
       $gv_result=tep_db_fetch_array($gv_query);
       $gv_payment_amount=$this->deduction;
       $gv_amount = $gv_result['amount'] - $gv_payment_amount;
       $gv_update=tep_db_query("update ".TABLE_GV_CUSTOMER." set amount='".$gv_amount."' where customer_id='".$customer_id."'");    
       $gv_insert=tep_db_query("insert into credit_payment (order_id, amount, credit_class) values('".$insert_id."','".$gv_payment_amount."', '" . $this->title . "')"); 
    }
      return $gv_payment_amount;
    }   
     
  function collect_posts() {
    global $HTTP_POST_VARS, $customer_id;
    if ($HTTP_POST_VARS['gv_redeem_code']) {
      $gv_query=tep_db_query("select gv_amount from ".TABLE_GV_TRACKING." where gv_number='".$HTTP_POST_VARS['gv_redeem_code']."' and redeem_flag='N'");
      if (tep_db_num_rows($gv_query)==0) {
        tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_NO_INVALID_REDEEM_GV), 'SSL'));
      }
    $gv_result=tep_db_fetch_array($gv_query);
    $gv_amount = $gv_result['gv_amount'];
// Things to set
// ip address of claimant
// customer id of claimant
// date 
// redemption flag
    $gv_query=tep_db_query("update ".TABLE_GV_TRACKING." set redeem_flag='Y', ip_address='".$REMOTE_ADDR."', customer_id_redeem='".$customer_id."',date_redeemed=NOW() where gv_number='".$HTTP_POST_VARS['gv_redeem_code']."'");
// now update customer account with gv_amount
    $gv_query=tep_db_query("select amount from gv_customer where customer_id='".$customer_id."'");
    $customer_gv=false;
    $total_gv_amount=$gv_amount;;
    if ($gv_result=tep_db_fetch_array($gv_query)) {
      $total_gv_amount=$gv_result['amount']+$gv_amount;
      $customer_gv=true;
    }
    if ($customer_gv) {
      // already has gv_amount so update
      $gv_update=tep_db_query("update gv_customer set amount='".$total_gv_amount."' where customer_id='".$customer_id."'");
    } else {
      // no gv_amount so insert
      $gv_insert=tep_db_query("insert into gv_customer (customer_id, amount) values ('".$customer_id."','".$total_gv_amount."')");
    }
    tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_REEDEEMED_AMOUNT. $gv_amount), 'SSL'));
    }
    if ($HTTP_POST_VARS['submit_redeem_x']) tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(ERROR_NO_REDEEM_CODE. $gv_amount), 'SSL'));   
  }  
   
  function calculate_credit($amount) {
      global $customer_id, $order;
       $gv_query=tep_db_query("select amount from gv_customer where customer_id='".$customer_id."'");
       $gv_result=tep_db_fetch_array($gv_query);
       $gv_payment_amount=$gv_result['amount'];
       $gv_amount=$gv_payment_amount;
       $save_total_cost=$amount;
       $full_cost=$save_total_cost-$gv_payment_amount;
       if ($full_cost<0) {
         $full_cost=0;
         $gv_payment_amount=$save_total_cost;
       }
//       if ($this->calculate_tax == 'true' && $do_tax) {
//          $ratio1 = $gv_payment_amount/($amount - $order->info['tax']) ;
//          $ratio1 = $gv_payment_amount/$amount ;
//          $tod_amount = $order->info['tax'] * $ratio1;
//          reset($order->info['tax_groups']);
//          $order->info['tax'] -= $tod_amount;
//          $order->info['total'] -= $tod_amount;
//          while (list($key, $value) = each($order->info['tax_groups'])) {
//            $god_amount = $order->info['tax_groups'][$key] * $ratio1;
//            $order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount;
//          }
//       }
//       if ($order->info['total']<0) {
//         $gv_payment_amount += $order->info['total'];
//         $order->info['total'] = 0;
//       }
       return $gv_payment_amount;
}

  function calculate_tax_deduction($amount, $od_amount) {
    global $order;
    $ratio1 = $od_amount/$amount;
    $tod_amount = 0;
    reset($order->info['tax_groups']);
    while (list($key, $value) = each($order->info['tax_groups'])) {
     $total_net += $key * $order->info['tax_groups'][$key];
    }
    if ($od_amount>$total_net) $od_amount = $total_net;  
    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;
    return $tod_amount;
  }

  function user_has_gv_account($c_id) {
    $gv_query=tep_db_query("select amount from ".TABLE_GV_CUSTOMER." where customer_id='".$c_id."'");
    if ($gv_result=tep_db_fetch_array($gv_query)) {
      if ($gv_result['amount']>0) {
        return true;
      }
    }
    return false;
  }
    
  function get_order_total() {
    global  $order;
    $order_total = $order->info['total'];
    if ($this->include_tax == 'false') $order_total=$order_total-$order->info['tax'];
    if ($this->include_shipping == 'false') $order_total=$order_total-$order->info['shipping_cost'];
    return $order_total;
  }    
        
    function check() {
      if (!isset($this->check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_ORDER_TOTAL_GV_STATUS'");
        $this->check = tep_db_num_rows($check_query);
      }

      return $this->check;
    }

    function keys() {
      return array('MODULE_ORDER_TOTAL_GV_STATUS', 'MODULE_ORDER_TOTAL_GV_SORT_ORDER', 'MODULE_ORDER_TOTAL_GV_INC_SHIPPING', 'MODULE_ORDER_TOTAL_GV_INC_TAX', 'MODULE_ORDER_TOTAL_GV_CALC_TAX', 'MODULE_ORDER_TOTAL_GV_CREDIT_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_GV_STATUS', 'true', 'Do you want to enable Gift Vouchers?', '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_GV_SORT_ORDER', '740', '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_GV_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_GV_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_GV_CALC_TAX', 'false', 'Re-Calculate Tax', '6', '7','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 ('Credit including Tax', 'MODULE_ORDER_TOTAL_GV_CREDIT_TAX', 'false', 'Add tax to purchased Gift Voucher when crediting to Account', '6', '8','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 . ")");
    }
  }
?>