<?php

class ATPCurierat_Ship_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface {

    protected $_code = 'atpcurierat_ship';

    public function isTrackingAvailable() {
        return true;
    }

    public function collectRates(Mage_Shipping_Model_Rate_Request $request) {

        if (!Mage::getStoreConfig('carriers/' . $this->_code . '/active')) {
            return false;
        }

        $result = Mage::getModel('shipping/rate_result');
        /* @var $result Mage_Shipping_Model_Rate_Result */

        $result->append($this->_getStandardShippingRate($request));


        return $result;
    }

    protected function _getStandardShippingRate(Mage_Shipping_Model_Rate_Request $request) {
        $rate = Mage::getModel('shipping/rate_result_method');
        $error = Mage::getModel('shipping/rate_result_error');
        /* @var $rate Mage_Shipping_Model_Rate_Result_Method */


        $email = $this->getConfigData('email');
        $password = $this->getConfigData('password');
        $awb_parcel = $this->getConfigData('parcel');
        $labels = $this->getConfigData('labels');
        $awb_rambus = $this->getConfigData('ramburs');
        $awb_content = $this->getConfigData('content');
        $contcolector = $this->getConfigData('contcolector');

        $awb_payer = $this->getConfigData('payer');
        $payment_hide = $this->getConfigData('payment_hide');
        $payment_min_country = $this->getConfigData('payment_min_country');
        $payment_min_capital = $this->getConfigData('payment_min_capital');
        $awb_observation = $this->getConfigData('comment');
        $insurance = $this->getConfigData('insurance');

        $awb_payer = !empty($awb_payer) ? 2 : 1;

        if ($awb_parcel) {
            $awb_envelope = "0";
            if (is_numeric($labels)) {
                $awb_parcel = $labels;
            } else {
                $awb_parcel = 1;
            }
        } else {
            $awb_parcel = "0";
            if (is_numeric($labels)) {
                $awb_envelope = $labels;
            } else {
                $awb_envelope = 1;
            }
        }



        $q = 'x';
        $total_weight=0;
        foreach ($request->getAllItems() as $item) {
            $q = $item->GetId();
            $total_weight += number_format(round((float) $item->getWeight(), 0), 0, '.', '') *$item->getQty() ;  
        }

        $resource = Mage::getSingleton('core/resource');
        $connection = $resource->getConnection('core_write');
        $sales_flat_quote_address = $resource->getTableName('sales_flat_quote_address');
        $sales_flat_quote_item = $resource->getTableName('sales_flat_quote_item');
        $directory_country_region = $resource->getTableName('directory_country_region');
        $sales_flat_quote_payment = $resource->getTableName('sales_flat_quote_payment');

        if (is_numeric($q)) {
            $query = "SELECT $sales_flat_quote_address.* FROM $sales_flat_quote_address left join $sales_flat_quote_item on $sales_flat_quote_item.quote_id = $sales_flat_quote_address.quote_id WHERE $sales_flat_quote_address.address_type='shipping' and $sales_flat_quote_item.item_id = {$q}";
            $resource = Mage::getSingleton('core/resource');
            $readConnection = $resource->getConnection('core_read');
            $results = $readConnection->fetchAll($query);

            if (count($results) > 0) {


                $awb_value = number_format(round((float) $results[0]["subtotal_incl_tax"], 2), 2, '.', '');                
                $awb_weight = $total_weight;
             
                //
                if ($awb_weight > 1) {
                    $awb_envelope = 0;
                    if (is_numeric($labels)) {
                        $awb_parcel = $labels;
                    } else {
                        $awb_parcel = 1;
                    }
                }


                //Localitate (pt minim gratuit)
                $to_locality = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $request->getDestCity());

                if (strtolower($to_locality) == 'bucuresti' and $payment_min_capital != 0)
                    $min_gratuit = $payment_min_capital;
                else
                    $min_gratuit = $payment_min_capital;


                //In caz de ramburs si/sau cash on delivery
                if ($rambus) {

                    $rambus_value_format = number_format(round((float) $results[0]["subtotal"], 2), 2, '.', '');
                    $rambus_value = round((float) $results[0]["subtotal"], 2) + 0;

                    if ($min_gratuit <= $rambus_value and $min_gratuit != 0) {
                        $rambus_value = "";
                        $rambus_value_format = "";
                    }
                }



                $to_county = $request->getDestRegionID();
                $query_directory_country_region = "SELECT * FROM $directory_country_region WHERE region_id = '$to_county' LIMIT 0 , 30";
                $resource_directory_country_region = Mage::getSingleton('core/resource');
                $readConnection_directory_country_region = $resource_directory_country_region->getConnection('core_read');
                $results_directory_country_region = $readConnection_directory_country_region->fetchAll($query_directory_country_region);
                $to_county = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $results_directory_country_region[0]["default_name"]);
                $to_country = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $results_directory_country_region[0]["country_id"]);

                $session = Mage::getSingleton('admin/session');
                if (!$session->getUser()) {
                    $session = Mage::getSingleton('customer/session')->getCustomer();
                    $customerid = Mage::getSingleton('customer/session')->getCustomerId();
                } else {
                    $session = Mage::getSingleton('admin/session')->getUser();
                }


                if (!is_null($results[0]["company"]) and $results[0]["company"] != "") {
                    $to_name = $results[0]["company"];
                    $to_name = urlencode($to_name);
                    $to_person = $results[0]["firstname"] . " " . $results[0]["lastname"];
                    $to_person = urlencode($to_person);
                } else {
                    $to_name = $results[0]["firstname"] . " " . $results[0]["lastname"];
                    $to_name = urlencode($to_name);
                    $to_person = "";
                }

                $to_person_phone = $results[0]["telephone"];
                $to_person_email = $results[0]["email"];


                $to_address = $request->getDestStreet();
                $to_postalcode = $request->getDestPostcode();

                $handling = Mage::getStoreConfig('carriers/' . $this->_code . '/handling');
                $result = Mage::getModel('shipping/rate_result');



                if ($to_country == "RO") {

                    $url = 'http://www.atp-curierat.com/api/v1/price/';

                    $data = array("email" => $email,
                        "password" => $password,
                        "from" => true,
                        "awb_service" => "Transit",
                        "awb_payer" => $awb_payer,
                        "awb_rambus_value" => $rambus_value,
                        "awb_insurance" => $insurance,
                        "awb_value" => $awb_value,
                        "awb_parcel" => $awb_parcel,
                        "awb_envelope" => $awb_envelope,
                        "awb_weight" => $awb_weight,
                        "to_county" => $to_county,
                        "to_locality" => $to_locality,
                        "to_postalcode" => $to_postalcode);
                   

                    $c = curl_init($url);
                    curl_setopt($c, CURLOPT_POST, true);
                    curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($data));
                    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
                    $page = curl_exec($c);
                    curl_close($c);

                    $price = json_decode($page);
               
                    if ($price->success) {
                        $rate->setCarrier($this->_code);
                        $rate->setCarrierTitle($this->getConfigData('title'));

                        $rate->setMethod('standand');
                        $rate->setMethodTitle('Standard');

                        $rate->setPrice($price->result->price_tva);
                        $rate->setCost($price->result->price_tva);

                        return $rate;
                    } else {
                        
                        $error = Mage::getModel('shipping/rate_result_error');
                        $error->setCarrier($this->_code);
                        $error->setCarrierTitle($this->getConfigData('title'));                                                 
                        $error->setErrorMessage($price->result);
                        $result->append($error);
                        return $error;
                        
                    }
                }
            }
        }
    }

    /**
     * Get Tracking Info
     *
     * @param mixed $tracking
     * @return mixed
     */
    public function getTrackingInfo($tracking) {
        $result = $this->getTracking($tracking);
        if ($result instanceof Mage_Shipping_Model_Tracking_Result) {
            if ($trackings = $result->getAllTrackings()) {
                return $trackings[0];
            }
        } elseif (is_string($result) && !empty($result)) {
            return $result;
        }

        return false;
    }

    /**
     * Get Tracking
     *
     * @param array $trackings
     * @return Mage_Shipping_Model_Tracking_Result
     */
    public function getTracking($trackings) {
        $this->_result = Mage::getModel('shipping/tracking_result');
        foreach ((array) $trackings as $code) {
            $this->_getTracking($code);
        }

        return $this->_result;
    }

    /**
     * Protected Get Tracking, opens the request to ATPCurierat
     *
     * @param string $code
     * @return boolean
     */
    protected function _getTracking($code) {

      
        $email = $this->getConfigData('email');
        $password = $this->getConfigData('password');

        $url = 'http://www.atp-curierat.com/api/v1/tracking/';

        $c = curl_init($url);
        curl_setopt($c, CURLOPT_POST, true);
        curl_setopt($c, CURLOPT_POSTFIELDS, "email=$email&password=$password&awb_number=$code");
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        $page = curl_exec($c);
        curl_close($c);
        $page = json_decode($page);
       
        $packageProgress=array();       
        
          if ($page->success) 
          {
              
                       $track = array();
              if ($page->result)
              foreach ($page->result as $r)
              { 
                  $tempArr=array();
                            $tempArr['deliverylocation']=$r->user_branch;
                              $tempArr['activity'] = trim($r->status." ".$r->description); //user_branch
                              $tempArr['deliverydate'] = (string)date("Y-m-d", strtotime($r->created_on));                                                                                        
                              $tempArr['deliverytime'] =(string)date("H:i", strtotime($r->created_on));                                                                              
                              $packageProgress[] = $tempArr;
                  
                  
              }
              
    
            $resultArr['progressdetail'] = $packageProgress;
     

          $tracking = Mage::getModel('shipping/tracking_result_status');
          $tracking->setTracking($code);
          $tracking->setCarrier('ATPCurierat');
          $tracking->setCarrierTitle($this->getConfigData('title'));
          $tracking->addData($resultArr);
          }

          $this->_result->append($tracking); 
        return true;
    }

    public function getAllowedMethods() {
        return array(
            'standard' => 'Standard'
        );
    }

}
