<?php
class Goshippo extends Shop_Abstract_Shipping_Gateway
{
	private $norates = "No shipping methods were found for one of the following reasons: <ul style=\"text-align: left; color: #000; font-weight: normal;\"><li>You may have entered incorrect address information. Please verify your address information and try again.</li><li>You may be ordering an item that is too large for standard shipping. Please submit your order using \"Pickup In Store\" and then call us to arrange shipping for your order.<li>Purolator doesn't ship to your location (unlikely). Please submit your order using \"Pickup In Store\" and then call us to arrange shipping for your order.</li></ul>";
	private $box_cache = array();
	private $config = array();

	public function __construct()
	{
		$CI =& get_instance();
		$query = $CI->db->query("SELECT * FROM shop_shipping_gateways WHERE filename='goshippo' LIMIT 1");

		foreach($query->result() as $row)
		{
			$configs = explode("\n", $row->configuration);
			$this->config = array();

			foreach($configs as $config)
			{
				if($config)
				{
					$line = explode("=", $config, 2);
					$this->config[$line[0]] = $line[1];
				}
			}
		}
	}

    public function get_rates($gateway_data)
    {
        $CI =& get_instance();

        $shipping_name       = $CI->input->get_post("shipping_name");
        $shipping_email      = $CI->input->get_post("shipping_email");
        $shipping_address    = $CI->input->get_post("shipping_address");
        $shipping_city       = $CI->input->get_post("shipping_city");
        $shipping_province   = $CI->input->get_post("shipping_province");
        $shipping_postalcode = $CI->input->get_post("shipping_postalcode");
        $shipping_country    = $CI->input->get_post("shipping_country");

        //make sure the postal code is formatted P1A 2V4 (space, no dash, etc)
        $shipping_postalcode = str_replace("-", "", strtoupper($shipping_postalcode));

        if(strlen($shipping_postalcode) == 6)
        {
            $shipping_postalcode = substr($shipping_postalcode, 0, 3) . " " . substr($shipping_postalcode, 3);
        }

		$gateway_data["shipping_info"]["name"]       = $shipping_name;
		$gateway_data["shipping_info"]["email"]      = $shipping_email;
		$gateway_data["shipping_info"]["address"]    = $shipping_address;
		$gateway_data["shipping_info"]["city"]       = $shipping_city;
		$gateway_data["shipping_info"]["province"]   = $shipping_province;
		$gateway_data["shipping_info"]["postalcode"] = $shipping_postalcode;
		$gateway_data["shipping_info"]["country"]    = $shipping_country;

		require_once(APPLICATION_PATH . '/third_party/shippo/Shippo.php');
		Shippo::setApiKey($this->config["api_key"]);

		$fromAddress = array(
		    'object_purpose' => 'PURCHASE',
		    'name' => COMPANY_NAME,
		    'street1' => $this->config["address"],
		    'city' => $this->config["city"],
		    'state' => $this->config["province"],
		    'zip' => $this->config["postalcode"],
		    'country' => $this->config["country"],
		    'phone' => "+1 555 555 5555",
		    'email' => COMPANY_EMAIL
		);

		$toAddress = array(
		    'object_purpose' => 'PURCHASE',
		    'name' => ($shipping_name ? $shipping_name : COMPANY_NAME),
		    'street1' => $shipping_address,
		    'city' => $shipping_city,
		    'state' => $shipping_province,
		    'zip' => $shipping_postalcode,
		    'country' => $shipping_country,
		    'phone' => '+1 555 555 5555',
		    'email' => ($shipping_email ? $shipping_email : COMPANY_EMAIL)
		);

        $cart_items 	= $gateway_data["cart_items"];
        $items 			= 0;
        $l 				= 0;
        $w 				= 0;
        $h 				= 0;
        $weight 		= 0;

        foreach($cart_items as $cart_item)
        {
        	if($cart_item->shipping_na)
			{
				continue;
			}

            // Shipping TBD items will get tallied up in the view.
            // As long as we only request shipping quotes for items other than that, we're good. the view does the rest.
            if($cart_item->shipping_tbd == 1)
            {
            }
            else
            {
            	$p = new Page();
            	$p->load($cart_item->page_id);

                for($qty = 1; $qty <= $cart_item->quantity; $qty++)
                {
                    $items 	++;
                    $l 		+= ($p->field("shipping_length") > 0 ? $p->field("shipping_length") : $this->config["default_length"]);
                    $w 		+= ($p->field("shipping_width") > 0 ? $p->field("shipping_width") : $this->config["default_width"]);
                    $h 		+= ($p->field("shipping_height") > 0 ? $p->field("shipping_height") : $this->config["default_height"]);
                    $weight += ($p->field("shipping_weight") > 0 ? $p->field("shipping_weight") : $this->config["default_weight"]);
                }
            }
        }

        if($items > 0)
        {
	        if($shipping_city == "" || $shipping_province == "" || $shipping_postalcode == "" || $shipping_country == "")
	        {
	            return "Please enter all shipping information to view available shipping methods.";
	        }
	    }
	    else
	    {
	    	return "No items in your cart require shipping.";
	    }

        $parcel = array(
		    'length'			=> $l,
		    'width'				=> $w,
		    'height'			=> $h,
		    'distance_unit'		=> 'in',
		    'weight'			=> $weight,
		    'mass_unit'			=> 'lb',
		);


		$shipment = Shippo_Shipment::create( array(
		    'object_purpose'	=> 'PURCHASE',
		    'address_from'		=> $fromAddress,
		    'address_to'		=> $toAddress,
		    'parcel'			=> $parcel,
		    'async'				=> false
		    )
		);

		$rates = array();

        foreach($shipment->rates_list as $rate)
		{
			$rates[] = $rate;
		}

		return $rates;
    }

    public function name()
    {
        return "Shippo";
    }

    public function tracking_url($tracking_number)
    {
        return "";
    }

    public function qualifies($gateway_data)
    {
    	return true;
    }
}
