<?php
  require('includes/application_top.php');
  require(DIR_WS_FUNCTIONS . 'ship_fedex.php');
  include(DIR_WS_INCLUDES . 'abbreviate.php'); // used to abbreviate state & country names
  require(DIR_WS_INCLUDES . 'fedexdc.php');
  

  if ($_POST['address_id'] != '' && (int)$_POST['address_id'] > 0) {
    // get alternate address
    $senders_address_query = "SELECT company, name, address_1, address_2, city, state, zip, country 
                               FROM " . TABLE_MULTI_ADDRESS . "
                               WHERE address_id = " . (int)$_POST['address_id'] . "
                               LIMIT 1;";
    $senders_address = $db->Execute($senders_address_query);
    $senders_company = $senders_address->fields['company']; 
    $senders_name = $senders_address->fields['name'];
    //if ($senders_company == '') $senders_company = $senders_name; // if no company, use name for company
    $senders_address_1 = $senders_address->fields['address_1'];
    $senders_address_2 = $senders_address->fields['address_2'];
    if ($senders_address_2 == '') $senders_address_2 = "NONE";
    $senders_city = $senders_address->fields['city'];
    $senders_state = $senders_address->fields['state'];
    $senders_zip = $senders_address->fields['zip'];
    $senders_country = abbreviate_country(zen_get_country_name($senders_address->fields['country']));
  } else {
    // set some defaults
    $senders_company = MODULE_SHIPPING_FEDEX_COMPANY_NAME;
    $senders_name = MODULE_SHIPPING_FEDEX_CONTACT_NAME;
    $senders_address_1 = MODULE_SHIPPING_FEDEX_ADDRESS_1;
    $senders_address_2 = MODULE_SHIPPING_FEDEX_ADDRESS_2;
    $senders_city = MODULE_SHIPPING_FEDEX_CITY;
    $senders_state = MODULE_SHIPPING_FEDEX_STATE;
    $senders_zip = MODULE_SHIPPING_FEDEX_POSTAL;
    $senders_country = abbreviate_country(zen_get_country_name(STORE_COUNTRY));
  }

  // get sender's fedex info from configuration table
  if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
    $fedex_account = MODULE_SHIPPING_FEDEX_ACCOUNT;
  } else {
    $fedex_account = MODULE_SHIPPING_FEDEX_TEST_ACCOUNT;
  }
  
  $fedex_vars = array (
    10=>$fedex_account, // 0
    498=>MODULE_SHIPPING_FEDEX_METER,   // 1
    75=>MODULE_SHIPPING_FEDEX_WEIGHT,  // 2
    4=>$senders_company, // 3
    32=>$senders_name,
    5=>$senders_address_1,// 4
    6=>$senders_address_2,// 5
    7=>$senders_city,      // 6
    8=>$senders_state,    // 7
    9=>$senders_zip,    // 8
    183=>trim(str_replace($unwanted, '', MODULE_SHIPPING_FEDEX_PHONE)),  // 9
    68=>MODULE_SHIPPING_FEDEX_CURRENCY,                // 10
  );
  $fedex_keys = array_keys($fedex_vars);

  ////
  // create new FedExDC object
  $fed = new FedExDC($fedex_vars[0][10],$fedex_vars[1][498]);
  $order = $_POST['orders_id'];
  // get all information from the order record
  $order_query = "select * from " . TABLE_ORDERS . " where orders_id = $order";

  $order_info = $db->Execute($order_query);

  // abbreviate the delivery state (function is in abbreviate.php)
  $delivery_state = abbreviate_state($order_info->fields['delivery_state']);

  // abbreviate the delivery country (function is in abbreviate.php)
  $delivery_country = abbreviate_country($order_info->fields['delivery_country']);

  // get rid of dashes, parentheses and periods in customer's telephone number
  $delivery_phone = trim(str_replace($unwanted, '', $_POST['telephone']));
  // remove "1" from start of phone number
  if (strlen($delivery_phone) > 10) {
    if (strpos($delivery_phone, "1") == 0) {
      $delivery_phone = substr($delivery_phone, 1, 10);
    }
  }

  // get the transaction value
  //    $value_query = zen_db_query("select value from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order . "' and class='ot_subtotal'");
  //    $order_value = $db->Execute($value_query);
  //    $order_value = round($order_value->fields['value'], 0);

  //// some form variables

  // format the form date (comes in as mm-dd-yyyy)
  $date_array = explode('-',$_POST['pickup_date']);
  $corrected_date = $date_array[2] . $date_array[0] . $date_array[1];

  // determine whether the ship date is today or later
  if ($corrected_date == date(Ymd)) {
    $future = 'N'; // today
  }  else {
    $future = 'Y';  // later date
  }
  if (MODULE_SHIPPING_FEDEX_EMAIL_ON_SHIPPING == 'true') $shipAlert = 'Y'; else $shipAlert = 'N';
  // start the array for fedex
  $shipData = array(
     0     => $transaction_code // transaction code
    ,2399 => $_POST['signature_type'] // signature type
    ,16   => $delivery_state // delivery state
    ,13   => $order_info->fields['delivery_street_address'] // delivery address
    ,14   => $order_info->fields['delivery_suburb'] // delivery address line 2
    ,1273 => $_POST['packaging_type'] // packaging type (01 is customer packaging)
    ,1274 => $_POST['service_type'] //
    ,18   => $_POST['telephone'] // customer's phone number
    ,15   => $order_info->fields['delivery_city']
    ,23   => $_POST['bill_type'] // payment type (1 is bill to sender)
    ,116  => $_POST['package_num'] // total packages
    ,117  => $senders_country // sender's country
    ,17   => str_replace(' ', '', $order_info->fields['delivery_postcode']) // postal code it's going to
    ,50   => $delivery_country // country it's going to
    ,11   => substr($order_info->fields['delivery_company'], 0, 35) // recipient's company name
    ,12   => name_length(name_case($order_info->fields['delivery_name'])) // recipient's contact name
    ,1201 => STORE_OWNER_EMAIL_ADDRESS // sender's email address
    ,1202 => $order_info->fields['customers_email_address'] // recipient's email address
    ,1554 => 'Y' // Shipper ShipAlert Flag 
    ,1557 => $shipAlert //Recipient ShipAlert Flag
    ,1333 => $_POST['dropoff_type'] // drop off type (1 is regular pickup)
    ,1415 => number_format(round($_POST['declare_value'], 2),2) // total order value, forced to 2 decimal places
    ,1368 => 2 // label type (2 is standard)
    ,1369 => 1 // printer type (1 is laser)
    ,1370 => (($thermal_printing) ? 7 : 5) // label media (5 is plain paper, 7 is 4x6 image)
    ,3002 => $_POST['package_invoice'] // invoice number
    ,25   => $_POST['package_reference'] // reference number
    ,3001 => $_POST['package_po'] // purchase order number
    ,38   => $_POST['package_department'] // department name
    ,24   => $corrected_date  // ship date
    ,1119 => $future // future day shipment
    ,2975 => 'Y'  // keep your fedex number off the label
    ,1266 => $_POST['saturday_delivery'] // Saturday delivery
    ,1200 => $_POST['hold_at_location'] // Hold At Fedex Location
    ,44   => $_POST['hal_address'] // Hold At Location address
    ,46   => $_POST['hal_city'] // Hold At Location city
    ,47   => $_POST['hal_state'] // Hold At Location state
    ,48   => $_POST['hal_postcode'] // Hold At Location postal code
    ,49   => $_POST['hal_phone'] // Hold At Location phone number
    ,57   => $_POST['dim_height'] // "your package" height dimension
    ,58   => $_POST['dim_width'] // "your package" width dimension
    ,59   => $_POST['dim_length'] // "your package length dimension
    ,3008 => $_POST['autopod'] // Automatic Proof of Delivery
    );

  // if it's home delivery (90), add the "residential delivery flag" (440)
  if ($_POST['service_type'] == 90) {
    $shipData[440] = 'Y';
  }else {
    $shipData[440] = 'N';
  }

  // if it's a Saturday delivery
  if ($_POST['service_type'] == 03 && $_POST['saturday_delivery'] == 1) {
    $shipData[1266] = 'Y';
  }
  if ($_POST['service_type'] == 01 && $_POST['saturday_delivery'] == 1) {
    $shipData[1266] = 'Y';
  } else {
    $shipData[1266] = 'N';
  }

  // if it's a Hold At Fedex Location delivery
  if ($_POST['hold_at_location'] == 1) {
    $shipData[1200] = 'Y';
  } else {
    $shipData[1200] = 'N';
  }

  // if AutoPOD, add AutoPOD flag
  if ($_POST['autopod'] == 1) {
    $shipData[3008] = 'Y';
  } else {
    $shipData[3008] = 'N';
  }

  // if "your package" type is selected, add the dimensions flag
  if ($_POST['packaging_type'] == 01) {
    $shipData[57] = $_POST['dim_height'];
    $shipData[58] = $_POST['dim_width'];
    $shipData[59] = $_POST['dim_length'];
  }


  // if it's an oversized shipment...
  if ($oversized) {
    $shipData[3124] = $_POST['oversized'];
  }

  ////
  // if there's no meter number in the database, ask for a new one
  if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
    $shipping_meter = $fedex_vars[498];
  } else {
    $shipping_meter = '';
  }
  if (!$shipping_meter) {
    $fed = new FedExDC($fedex_keys[10]);

    // variables needed to subscribe
    $requestData = array (
      0 => 211, // 211 is the transaction code for a subscription request
      10 => $fedex_vars[10], // account number
      4003 => $fedex_vars[4], // contact name, using store name for now
      4008 => $fedex_vars[5], // street address
      4011 => $fedex_vars[7], // city
      4012 => $fedex_vars[8], // state
      4013 => $fedex_vars[9], // postal code
      4014 => $senders_country, // country
      4015 => $fedex_vars[183] // phone number
      );

    $keyRequest = $fed->subscribe($requestData);
    // todo: add appropriate error checking for at least some of the possible errors
    if ($error = $fed->getError()) {
      echo '<pre>';
      print_r($requestData);
      echo '</pre>';
      echo '<pre>';
      print_r($keyRequest);
      echo '</pre>';
      die("ERROR: ". $error);
    } else {
      if (MODULE_SHIPPING_FEDEX_SERVER == 'production') {
        $db->Execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $keyRequest[498] . "' where configuration_key = 'MODULE_SHIPPING_FEDEX_METER'");
      }
      $fedex_vars[498] = $keyRequest[498];
    }
  }
  // end meter request

  ////
  // put the form array together with the stuff from the database
  $shipData = $shipData+$fedex_vars;
  // get the package weight/total weight and format it to one decimal place
  $total_weight = round($_POST['package_weight'], 1);
  $total_weight = sprintf("%01.1f", $total_weight); 
  $shipData[1401] = $total_weight; 

  $rate = new FedExDC($shipData[0][10],$shipData[1][498]);
  $rate_array = $rate->rate_services($shipData);
  $count = 0;
  $continue = true;
  while ($continue) {
    $count++;
    if ($rate_array[1274 . '-' . $count] != '') {
      $continue = true;
      $type = $rate_array[1274 . '-' . $count];
      $cost = '$' . $rate_array[1419 . '-' . $count];
      switch (substr($type, 0, 2)) {
      case 92:
        echo 'FedEx Ground Service: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 90:
        echo 'FedEx Home Delivery: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 01:
        echo 'FedEx Priority Overnight: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 03:
        echo 'FedEx 2day: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 05:
        echo 'FedEx Standard Overnight: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 06:
        echo 'FedEx First Overnight: ' . $cost . "\n";
        $rate_returned = true;
        break;
      case 20:
        echo 'FedEx Express Saver: ' . $cost . "\n";
        $rate_returned = true;
        break;
      }
    } else {
      $continue = false;
    }
  }
  if (!$rate_returned) {
    echo 'Invalid shipment, or no rates returned.';
  }  
?>