Hi Zen masters!

My head is about to explode trying to fix this weird bug. So I'm hoping that someone could help me figure this out.

I had to create a zone based shipping module to calculate shipping fees based on the zip code of the shipping address. There's a table in the database that defines all the zones for different zip codes. For example, if the first 3 digit of the zip code is between 200 and 299, then it belongs to zone #8. Based on the number of boxes and the selected shipping method (i.e. ground, 2-day, next day), it then looks up another custom table to determine the proper shipping rate. Each shipping method has its own table. So 2-day shipping for 3 boxes to zone #8 would cost $29.

I figured that the closest shipping module would be the UPS module because it allows multiple shipping methods. So I cloned it from that module. Everything seems to be working well. The ONLY thing (and it's really the ONLY problem) is that the shipping method is always set to Ground on the billing page and confirmation page, even if you selected 2-Day or Next Day. I'm pretty sure it's not a problem with the template, because the same template works fine for the regular UPS module.

I'm not a very experienced PHP developer so forgive me if I made a stupid mistake. Any help would be greatly appreciated!! THANK YOU!

Here's the source code:

Code:
<?php
/**
 * @package shippingMethod
 * @copyright Copyright 2003-2009 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: ddc.php
 */
/**
 * DDC Shipping Module class
 *
 */
class ddc extends base {
  /**
   * Declare shipping module alias code
   *
   * @var string
   */
  var $code;
  /**
   * Shipping module display name
   *
   * @var string
   */
  var $title;
  /**
   * Shipping module display description
   *
   * @var string
   */
  var $description;
  /**
   * Shipping module icon filename/path
   *
   * @var string
   */
  var $icon;
  /**
   * Shipping module status
   *
   * @var boolean
   */
  var $enabled;
  /**
   * Shipping module list of supported countries (unique to USPS/UPS)
   *
   * @var array
   */
  var $types;
  /**
   * Constructor
   *
   * @return ddc
   */
  function ddc() {
    global $order, $db, $template, $current_page_base;

    $this->code = 'ddc';
    $this->title = MODULE_SHIPPING_DDC_TEXT_TITLE;
    $this->description = MODULE_SHIPPING_DDC_TEXT_DESCRIPTION;
    $this->sort_order = MODULE_SHIPPING_DDC_SORT_ORDER;
    $this->icon = '';
    $this->tax_class = MODULE_SHIPPING_DDC_TAX_CLASS;
    $this->tax_basis = MODULE_SHIPPING_DDC_TAX_BASIS;
	$this->_allowedMethods = explode(", ", MODULE_SHIPPING_DDC_TYPES);

    // disable only when entire cart is free shipping
    if (zen_get_shipping_enabled($this->code)) {
      $this->enabled = ((MODULE_SHIPPING_DDC_STATUS == 'True') ? true : false);
    }

    if ($this->enabled) {
      // check MODULE_SHIPPING_DDC_HANDLING_METHOD is in
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_DDC_HANDLING_METHOD'");
      if ($check_query->EOF) {
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Handling Per Order or Per Box', 'MODULE_SHIPPING_DDC_HANDLING_METHOD', 'Box', 'Do you want to charge Handling Fee Per Order or Per Box?', '6', '0', 'zen_cfg_select_option(array(\'Order\', \'Box\'), ', now())");
      }
    }

    if ( ($this->enabled == true) && ((int)MODULE_SHIPPING_DDC_ZONE > 0) ) {
      $check_flag = false;
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_SHIPPING_DDC_ZONE . "' and zone_country_id = '" . $order->delivery['country']['id'] . "' order by zone_id");
      while (!$check->EOF) {
        if ($check->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check->fields['zone_id'] == $order->delivery['zone_id']) {
          $check_flag = true;
          break;
        }
        $check->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }

    $this->types = array('QGND' => 'Ground',
						 'Q2DA' => '2 Day',
						 'Q1DA' => 'Next Day');
  }
  /**
   * Get quote according to the pricing table
   *
   * @param string $method
   * @return array of quotation results
   */
  function quote($method = '') {
    global $_POST, $order, $total_count, $shipping_num_boxes;
	
	// adjusted count for free shipping
    $this->_itemTotalCount = $total_count - $_SESSION['cart']->free_shipping_items();

    if ( (zen_not_null($method)) && (isset($this->types[$method])) ) {
      //$prod = $method;
      // BOF: UPS USPS
    } else if ($order->delivery['country']['iso_code_2'] == 'CA') {
      //$prod = 'STD';
      // EOF: UPS USPS
    } else {
      //$prod = 'GNDRES';
    }

	// Find out what zone the shipping address belongs to

	$this->_ddcGetZone($order->delivery['postcode']);
	$ddcQuote = $this->_ddcGetQuote();

    if ( $this->_ddcShippingZone ) {
	  switch (SHIPPING_BOX_WEIGHT_DISPLAY) {
        case (0):
        $show_box_weight = '';
        break;
        case (1):
        $show_box_weight = ' (' . $shipping_num_boxes . ' ' . TEXT_SHIPPING_BOXES . ')';
        break;
        case (2):
        $show_box_weight = ' (' . number_format($ups_shipping_weight * $shipping_num_boxes,2) . TEXT_SHIPPING_WEIGHT . ')';
        break;
        default:
        $show_box_weight = ' (' . $shipping_num_boxes . ' x ' . number_format($ups_shipping_weight,2) . TEXT_SHIPPING_WEIGHT . ')';
        break;
      }

      $this->quotes = array('id' => $this->code,
                            'module' => $this->title);

      $methods = array();
      $qsize = sizeof($ddcQuote);
	  $std_rcd = false;

      for ($i=0; $i<$qsize; $i++) {
		list($type, $cost) = $ddcQuote[$i];
		
		if ($type=='STD') {
          if ($std_rcd) continue;
          else $std_rcd = true;
        }
        if (!in_array($type, $this->_allowedMethods)) continue;

        $cost = preg_replace('/[^0-9.]/', '',  $cost);
        $methods[] = array('id' => $type,
                           'title' => $this->types[$type],//$this->types[$type],
                           'cost' => $cost + (MODULE_SHIPPING_DDC_HANDLING_METHOD == 'Box' ? MODULE_SHIPPING_DDC_HANDLING * $shipping_num_boxes : MODULE_SHIPPING_DDC_HANDLING) );
      }

      $this->quotes['methods'] = $methods;

      if ($this->tax_class > 0) {
        $this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
      }
     } else { 	// If the zip code doesn't belong to any zone
      $this->quotes = array('module' => $this->title,
                            'error' => 'We are unable to obtain a rate quote for Qualia shipping.<br />Please contact the store if no other alternative is shown.');
    } 

    return $this->quotes;
  }
  /**
   * check status of module
   *
   * @return boolean
   */
  function check() {
    global $db;
    if (!isset($this->_check)) {
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_DDC_STATUS'");
      $this->_check = $check_query->RecordCount();
    }
    return $this->_check;
  }
  /**
   * Install this module
   *
   */
  function install() {
    global $db;
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable DDC Shipping', 'MODULE_SHIPPING_DDC_STATUS', 'True', 'Do you want to offer DDC shipping?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Handling Fee', 'MODULE_SHIPPING_DDC_HANDLING', '0', 'Handling fee for this shipping method.', '6', '0', now())");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Handling Per Order or Per Box', 'MODULE_SHIPPING_DDC_HANDLING_METHOD', 'Box', 'Do you want to charge Handling Fee Per Order or Per Box?', '6', '0', 'zen_cfg_select_option(array(\'Order\', \'Box\'), ', now())");

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_SHIPPING_DDC_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '6', '0', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Tax Basis', 'MODULE_SHIPPING_DDC_TAX_BASIS', 'Shipping', 'On what basis is Shipping Tax calculated. Options are<br />Shipping - Based on customers Shipping Address<br />Billing Based on customers Billing address<br />Store - Based on Store address if Billing/Shipping Zone equals Store zone', '6', '0', 'zen_cfg_select_option(array(\'Shipping\', \'Billing\', \'Store\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Shipping Zone', 'MODULE_SHIPPING_DDC_ZONE', '0', 'If a zone is selected, only enable this shipping method for that zone.', '6', '0', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_SHIPPING_DDC_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
    // BOF: UPS USPS
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ( 'Shipping Methods: Ground, 2 Day, Next Day', 'MODULE_SHIPPING_DDC_TYPES', 'QGND, Q2DA, Q1DA', 'Select the DDC services to be offered.', '6', '13', 'zen_cfg_select_multioption(array(\'QGND\', \'Q2DA\', \'Q1DA\'), ', now() )");
    // EOF: UPS USPS
  }
  /**
   * Remove this module
   *
   */
  function remove() {
    global $db;
    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key like 'MODULE\_SHIPPING\_DDC\_%' ");
  }
  /**
   * Build array of keys used for installing/managing this module
   *
   * @return array
   */
  function keys() {
    return array('MODULE_SHIPPING_DDC_STATUS', 'MODULE_SHIPPING_DDC_HANDLING', 'MODULE_SHIPPING_DDC_HANDLING_METHOD', 'MODULE_SHIPPING_DDC_TAX_CLASS', 'MODULE_SHIPPING_DDC_TAX_BASIS', 'MODULE_SHIPPING_DDC_ZONE', 'MODULE_SHIPPING_DDC_SORT_ORDER', 'MODULE_SHIPPING_DDC_TYPES');
  }
  
  /*************************************************************
  * DDC SHIPPING CALCULATOR
  *************************************************************/
  function _ddcGetZone($zip) {
	global $db, $order;
	
	$zone = '';
	// strip the first 3 digits
	$zip = substr($zip, 0, 3);

	if ($order->delivery['state']=='New Jersey') {
		$zone = 40;	
	}
 	else if ($order->delivery['state']=='Hawaii') {
		$zone = 20;
	}
	else if ($order->delivery['state']=='Alaska') {
		$zone = 30;
	}
	// If not any of the above states, query the database
	else {
		$check_query = $db->Execute("select zone from qualia_ddc_zones where start_zip<=" . $zip . " AND end_zip>=" . $zip);		
		$check_query->fields['zone'];
		$zone = $check_query->fields['zone'];
	}

	$this->_ddcShippingZone = $zone;
  }
  
  function _ddcGetQuote() {
	global $db;
	
	$returnval = array();
	
	$totalBottles = $this->_itemTotalCount;
	$shippingMethods = $this->_allowedMethods;

// print_r( $_SESSION['shipping']);	
	
	// popuplate the quote array
	for ($i=0; $i<sizeof($this->_allowedMethods); $i++) {
		if ($totalBottles > 12) {
			$num_cases = floor($totalBottles/12);
			$remaining_bottles = $totalBottles%12;
			
			$check_query = $db->Execute("select zone" . $this->_ddcShippingZone . " from qualia_ddc_shipping_" . strtolower($shippingMethods[$i]) . " where bottles=12");
			$case_shipping = $check_query->fields['zone'.$this->_ddcShippingZone] * $num_cases;
			
			$check_query = $db->Execute("select zone" . $this->_ddcShippingZone . " from qualia_ddc_shipping_" . strtolower($shippingMethods[$i]) . " where bottles=" . $remaining_bottles);
			$remaining_shipping = $check_query->fields['zone'.$this->_ddcShippingZone];
			
			$total_shipping = $case_shipping + $remaining_shipping;
			
			$returnval[$i][0] = $this->_allowedMethods[$i];
			$returnval[$i][1] = $total_shipping;
		}
		else if ($totalBottles <= 12) {
			$check_query = $db->Execute("select zone" . $this->_ddcShippingZone . " from qualia_ddc_shipping_" . strtolower($shippingMethods[$i]) . " where bottles=" . $totalBottles);
			$returnval[$i][0] = $shippingMethods[$i];
			$returnval[$i][1] = $check_query->fields['zone'.$this->_ddcShippingZone];
		}
	
	}
	return $returnval;
	
  }
  
}