<?php

class ATPCurierat_Ship_Adminhtml_CustomController extends Mage_Adminhtml_Controller_Action {

    protected $_code = 'atpcurierat_ship';

    public function indexAction() {
        $this->_redirectUrl("http://www.atp-curierat.com/");
    }

    /**
     * Generate awb  action
     */
    public function generateAction() {
        if (!Mage::getStoreConfig('carriers/' . $this->_code . '/active')) {
            return false;
        }



        $orderId = $this->getRequest()->getParam('order_id');



        if ($orderId) {

            $order = Mage::getModel('sales/order')->load($orderId);
            $email = Mage::getStoreConfig('carriers/' . $this->_code . '/email');

            $password = Mage::getStoreConfig('carriers/' . $this->_code . '/password');
            $awb_parcel = Mage::getStoreConfig('carriers/' . $this->_code . '/parcel');
            $labels = Mage::getStoreConfig('carriers/' . $this->_code . '/labels');
            $awb_rambus = Mage::getStoreConfig('carriers/' . $this->_code . '/ramburs');
            $awb_content = Mage::getStoreConfig('carriers/' . $this->_code . '/content');
            $contcolector = Mage::getStoreConfig('carriers/' . $this->_code . '/contcolector');

            $awb_payer = Mage::getStoreConfig('carriers/' . $this->_code . '/payer');
            $payment_hide = Mage::getStoreConfig('carriers/' . $this->_code . '/payment_hide');
            $payment_min_country = Mage::getStoreConfig('carriers/' . $this->_code . '/payment_min_country');
            $payment_min_capital = Mage::getStoreConfig('carriers/' . $this->_code . '/payment_min_capital');
            $awb_observation = Mage::getStoreConfig('carriers/' . $this->_code . '/comment');
            $insurance = Mage::getStoreConfig('carriers/' . $this->_code . '/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;
                }
            }

            $fName = $order->getShippingAddress()->getData('firstname');
            $lName = $order->getShippingAddress()->getData('lastname');

            $to_name = $order->getShippingAddress()->getData('company');
            $to_person = $fName . ' ' . $lName;

            if (empty($to_name))
                $to_name = $to_person;



            $customerDestCountry = $order->getShippingAddress()->getData('country_id');
            $to_country = $customerDestCountry;

            $customerDestJudetId = $order->getShippingAddress()->getData('region');
            $to_county = $customerDestJudetId;

            $customerDestLocalitate = $order->getShippingAddress()->getData('city');
            $to_locality = $customerDestLocalitate;

            $to_address = $order->getShippingAddress()->getData('street');
            $to_person_phone = $order->getShippingAddress()->getData('telephone');
            $to_person_email = $order->getShippingAddress()->getData('customer_email');
            $to_postalcode = $order->getShippingAddress()->getData('postcode');
            
            $awb_weight = number_format(round((float)$order->getData("weight"),0), 0, '.', '');
            $awb_value = number_format(round((float)$order->getData("subtotal"),0), 0, '.', '');
            if ($awb_weight > 1) {
                    $awb_envelope = 0;
                    if (is_numeric($labels)) {
                        $awb_parcel = $labels;
                    } else {
                        $awb_parcel = 1;
                    }
                }

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

                $rambus_value_format = number_format(round((float) $order->getData("subtotal"), 2), 2, '.', '');
                $rambus_value = round((float) $order->getData("subtotal"), 2) + 0;

                if ($min_gratuit <= $rambus_value and $min_gratuit != 0) {
                    $rambus_value = "";
                    $rambus_value_format = "";
                }
                
                if ($contcolector)
                    $awb_rambus_pay=2; else $awb_rambus_pay=1;
            }

            if ($to_country == "RO") {

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

                $data = array("email" => $email,
                    "password" => $password,
                    "from" => true,
                    "awb_service" => "Transit",
                    "awb_payer" => $awb_payer,
                    "awb_rambus_value" => $rambus_value,
                    "awb_rambus_pay" => $awb_rambus_pay,
                    "awb_insurance" => $insurance,
                    "awb_value" => $awb_value,
                    "awb_parcel" => $awb_parcel,
                    "awb_envelope" => $awb_envelope,
                    "awb_weight" => $awb_weight,
                    "awb_reference"=> $awb_observation,
                    "to_name" => $to_name,
                    "to_coutry" => $to_country,
                    "to_county" => $to_county,
                    "to_locality" => $to_locality,
                    "to_postalcode" => $to_postalcode,
                    "to_address" => $to_address,
                    "to_person" => $to_name,
                    "to_person_phone" => $to_person_phone,
                    "to_person_email" => $to_person_email);


                $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);



                $result = json_decode($page);



                if ($result->success) {
                    Mage::getSingleton('adminhtml/session')->addSuccess("A fost creat awb-ul: " . $result->result);
                    Mage::getSingleton('adminhtml/session')->setFormData(false);


                    $shipmentId = $this->getRequest()->getParam('shippment_id');
                    if ($shipmentId) {
                        //   $model->setData('shippment_id', $shipmentId);
                        $shippment = Mage::getModel('sales/order_shipment')->load($shipmentId);

                        $track = Mage::getModel('sales/order_shipment_track')
                                ->setShipment($shippment)
                                ->setData('title', 'ATP Curierat')
                                ->setData('number', $result->result)
                                ->setData('carrier_code', $this->_code)
                                ->setData('order_id', $orderId)
                                ->save();
                    }

                    $this->_redirectReferer();
                } else {

                    Mage::getSingleton('adminhtml/session')->addError($result->result);
                    Mage::getSingleton('adminhtml/session')->setFormData(false);
                    $this->_redirectReferer();
                }
            }
        }
    }

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

        $password = Mage::getStoreConfig('carriers/' . $this->_code . '/password');
        $shipmentId = $this->getRequest()->getParam('shippment_id');
        $shipment = Mage::getModel("sales/order_shipment")->load($shipmentId);

        $alltrackback = $shipment->getAllTracks();
        foreach ($alltrackback as $track) {
            if ($track->getCarrierCode() == $this->_code)
                $awb_number = $track->getTrackNumber();
        }

        if ($awb_number) {
            $url = 'http://www.atp-curierat.com/api/v1/label/';

            $data = array("email" => $email,
                "password" => $password,
                "awb_number" => $awb_number);


            $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);


            $result = json_decode($page);


            echo $result->result;
        } else {

            Mage::getSingleton('adminhtml/session')->addError("Nu exista awb-ul : " . $awb_number);
            Mage::getSingleton('adminhtml/session')->setFormData(false);
            $this->_redirectReferer();
        }
    }

    public function deleteAction() {
        if (!Mage::getStoreConfig('carriers/' . $this->_code . '/active')) {
            return false;
        }
        $email = Mage::getStoreConfig('carriers/' . $this->_code . '/email');
        $password = Mage::getStoreConfig('carriers/' . $this->_code . '/password');
        $shipmentId = $this->getRequest()->getParam('shippment_id');
        $shipment = Mage::getModel("sales/order_shipment")->load($shipmentId);

        $alltrackback = $shipment->getAllTracks();
        foreach ($alltrackback as $track) { 
            if ($track->getCarrierCode() == $this->_code) {
                
                
                $awb_number = $track->getTrackNumber();

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

                $data = array("email" => $email,
                    "password" => $password,
                    "awb_number" => $awb_number);


                $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);
                $result = json_decode($page);
             
               
                if ($result->success) {
                    
                     $track->delete();
                    Mage::getSingleton('adminhtml/session')->addSuccess("A fost sters awb-ul: " . $awb_number);
                    Mage::getSingleton('adminhtml/session')->setFormData(false);                    
                 
                
                }
                else {
                    Mage::getSingleton('adminhtml/session')->addError($result->result);
                    Mage::getSingleton('adminhtml/session')->setFormData(false);
                                   }
            }
        }
         $this->_redirectReferer();
    }

}
