<?php
class UrgentCurier {
    private $key;
    private $curl;
    public $url='https://urgentcargus.azure-api.net/api';

    function __construct($key) {
        $this->key = $key;

        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($this->curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
    }

    function CallMethod($function, $parameters = '', $verb, $token = null) {
        $json = json_encode($parameters);

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $json);
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $verb);
        curl_setopt($this->curl, CURLOPT_URL, $this->url . '/' . $function);

        if ($function == 'LoginUser') {
            $headers = array (
                'Ocp-Apim-Subscription-Key: '.$this->key,
                'Ocp-Apim-Trace: true',
                'Content-Type: application/json',
                'ContentLength: '.strlen($json)
            );
        } else {
            $headers = array (
                'Ocp-Apim-Subscription-Key: '.$this->key,
                'Ocp-Apim-Trace: true',
                'Authorization: Bearer '.$token,
                'Content-Type: application/json',
                'Content-Length: '.strlen($json)
            );
            if ($function == 'Awbs' && $verb == 'POST') {
                $ver = Mage::getVersionInfo();
                $headers[] = 'path: MG'.$ver['major'].$ver['minor'].$ver['revision'];
            }
        }

        curl_setopt(
            $this->curl,
            CURLOPT_HTTPHEADER,
            $headers
        );

        $result = curl_exec($this->curl);
        $header = curl_getinfo($this->curl);

        $data = json_decode($result, true);
        $status = $header['http_code'];

        if ($status == '200') {
            if (is_array($data) && isset($data['message'])) {
                return $data['message'];
            } else {
                return $data;
            }
        } else if ($status == '204') {
            return null;
        } else {
            @ob_end_clean();
            echo '<pre>';
            echo 'Status<br/>';
            print_r(array(
                'status' => $status,
                'method' => $function,
                'verb' => $verb,
                'token' => $token,
                'params' => $parameters,
                'data' => $data,
                'lenght' => strlen($json)
            ));
            echo 'CURL Error<br/>';
            print_r(curl_error($this->curl));
            echo '</pre>';
            die();
        }
    }


}


require_once('app/Mage.php'); 
Mage::init();
Mage::app();
umask(0644);

if (!empty($_GET)) {

	/* Print Label Request Start */
	$order = Mage::getModel('sales/order')->loadByIncrementId($_GET['nr_comanda']);
	$order_id = $_GET['nr_comanda'];


	$key = '41cecf95e26f479c97864f07522004d3';
	$urgent = new UrgentCurier($key);
    $fields = array(
	    'UserName' => 'new_urban',
	    'Password' => '1234'
	);

    $token = $urgent->CallMethod('LoginUser', $fields, 'POST'); //avem token de autentificare

    
    $location = array();
    //var_dump($pickups);
    $pickups = $urgent->CallMethod('PickupLocations', array(), 'GET', $token);
    if (is_null($pickups)) {
        die('Nu exista niciun punct de ridicare asociat acestui cont!');
    }

    $location = $pickups[0]['LocationId']; //Dobroesti
    $shipping=$order->getShippingAddress();
	$county = $shipping->getRegion();
    $city = $shipping->getCity();
    if($city=="Bucuresti Sector 1" or $city=="Bucuresti Sector 2" or $city=="Bucuresti Sector 3" or $city=="Bucuresti Sector 4" or $city=="Bucuresti Sector 5" or $city=="Bucuresti Sector 6"){
        $city="Bucuresti";
    }
    $address = $shipping->getStreetFull();
    $address2 = $order->getData('customer_taxvat');
    if($shipping->getFax()!=""){
        $address3='nr. '.$shipping->getFax();
    } else {
        $address3="";
    }
    
    $codpostal = $shipping->getPostcode();

	$numeclient = $order->getCustomerName();
	if ($shipping->getCompany()){
	   $numeclient = $shipping->getCompany();
    }
    
    $mail_client = $shipping->getEmail();
    if( $mail_client == ''){
        $mail_client = 'test@test.com';
    }

    $phone = $shipping->getTelephone();

    // if ($order->getPayment()->getMethod() == "cashondelivery"){
    //     $bankRepayment = $order->getGrandTotal()+0;
    // } else {
    //     $bankRepayment='0';
    // }
     $bankRepayment = 34.9;
	 $nrcolete = 1;
	 $greutate = 1;
	 $sambata = false;

    // $resource = Mage::getSingleton('core/resource');
    // $read = $resource->getConnection('core_read');

    // $packeRow = $read->fetchAll("SELECT * FROM `numarcolete` WHERE `IdComanda` = '".$order_id."' LIMIT 1");
    // if (count($packeRow) > 0) {
    //     $nrcolete = $packeRow[0]['NrColete'];
    //     $greutate = $packeRow[0]['Greutate'];
    //     $sambata = $packeRow[0]['LivSambata'];
    // } else {
    //     $nrcolete = 1;
    //     $greutate = 1;
    //     $sambata = false;
    // }	

    // if($sambata=="da") {
	//    $sambata = true;
	// } else {
	//    $sambata = false;
	// }
	
    $fields = array(
        'Sender' => array(
            'LocationId' => $location
        ),
        'Recipient' => array(            
            'LocationId' => 0,
            'Name' => $numeclient,
            'CountyId' => 0,
            'CountyName' => $county,
            'LocalityId' => 0,
            'LocalityName' => $city,
            'StreetId' => 0,
            'StreetName' => $address.' '.$address3.' '.$address2,
            'BuildingNumber' => '1',
            'AddressText'=> $address.' '.$address3.' '.$address2,                       
            'ContactPerson' => $numeclient,
            'PhoneNumber' => $phone,
            'Email' => $mail_client,
            'CodPostal' => $codpostal,
            'CountryId'=> 0,
            
        ),
        'Parcels' => 0,
        'Envelopes' => 1,
        'TotalWeight' => $greutate,
        'DeclaredValue' => 0,
        'BankRepayment' => $bankRepayment,
        'OpenPackage' => false,
        'PriceTableId' => 120606,
        'ShipmentPayer' => 1,
        'ServiceId' => 34,
        'MorningDelivery' => false,
        'SaturdayDelivery' => $sambata,
        'PackageContent' => "Produs cadou",
        'ParcelCodes' => array(   
            array(         
              'Code' => '0',
              'Type' => 0,
              'Weight' => 0.0,
              'Length' => 0,
              'Width' => 0,
              'Height' => 0
            ),         
        ),
    );

    $cod_bara = $urgent->CallMethod('Awbs', $fields, 'POST', $token);
    $jsonAwb = array();
    $jsonAwb[] = $cod_bara;
    $jsonAwb = json_encode($jsonAwb);
    $print = $urgent->CallMethod('AwbDocuments?barCodes='.$jsonAwb.'&type=HTML&format=0', array(), 'GET', $token);

    header('Content-type:text/html');
    echo base64_decode($print);

    // $write = $resource->getConnection('core_write');

    // $timestamp=(new \DateTime('now', new \DateTimeZone('Europe/Bucharest')))->format('YmdHis');
    // $query = 'INSERT INTO `tracking_cargus` (`increment_id`, `awb`, `time_stamp`, `status`)'
    //         ."VALUES ('".$order_id."', '".$cod_bara."', '".$timestamp."', '0')";
    //$write->query($query);

    die();
} else {
	echo "Wrong parameters ...";
}

?>

