<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: eWayModel.php, v 1.0 2011/06/14 20:52:11

//
class blueEx extends Shipping
{
	public function orderAPI($resOrders,$resOrderItems,$languageIDs,$acIDs='')
	{
		set_time_limit(0);                 
                //define('blueEx', "http://bluekart.com/api/live/order/v2/order_api.php");
                define('blueEx', "http://bluekart.com/api/live/console-orders/orders/order_api.php");//http://bluekart.com/api/test/v2/sub-accounts/subaccount/order/order_api.php
               // <api_code>KHujdgetrbcnhgsw</api_code>
              //  <acno>KHI-88888</acno>
               // <userid>subaccounts</userid>
               //            <password>subaccounts</password>
                $bI 			= unserialize($resOrders['billingAddress']);
                $sI 			= unserialize($resOrders['shippingAddress']);
                $payment_type           = ($resOrders['paymentSettingsGroupID']==18)?'COD':'CC';
                $ObjCountry             = new CountryModel();
                $countryDet             = $ObjCountry->getCountryDetails($resOrderItems[0]['locCountryID'],$languageIDs);
                $shipCountryDet         = $ObjCountry->getCountryDetails($sI['shippingCountryID'],$languageIDs);
                $shipCountryDet['countryIsoA2'] = 'PK';
                $sI['shippingCity'] = 'KHI';
                $resOrderItems[0]['locCity'] = 'KHI';
                if($bI['billingPhone']=='') {
                    $bI['billingPhone'] = '123456';
                }
                
                $xml = '<?xml version="1.0" encoding="utf-8"?>
                            <BenefitDocument>
                            <AccessRequest>
                            <DocumentType>1</DocumentType>
                            <Orderdetail>
                                  <api_code>KHujdgetrbcnhgsw</api_code>
                                  <acno>LHE-00737</acno>
                           <testbit>y</testbit>
                           <userid>dukanone</userid>
                           <password>123456</password>
                           <cn_generate>y</cn_generate>
                 

                <shipper_name>'.$resOrderItems[0]['businessName'].'</shipper_name>  
                <shipper_email>'.$resOrderItems[0]['businessEmail'].'</shipper_email>    
                <shipper_contact>'.$resOrderItems[0]['businessPhone'].'</shipper_contact>
                <shipper_address>'.$resOrderItems[0]['locAddress1']." ".$resOrderItems[0]['locAddress2'].'</shipper_address> 
                <shipper_city>'.$resOrderItems[0]['locCity'].'</shipper_city> 
                <shipper_country>'.$countryDet['countryIsoA2'].'</shipper_country>  
                <billing_name>'.$sI['shippingFname']." ".$sI['shippingLname'].'</billing_name>  
                <bill_email>'.$bI['billingEmail'].'</bill_email>
                <billing_contact>'.$sI['shippingPhone'].'</billing_contact> 
                <billing_address>'.$sI['shippingAddress']." ".$sI['shippingAddress2'].'</billing_address>    
                <billing_city>'.$sI['shippingCity'].'</billing_city>    
                <billing_country>'.$shipCountryDet['countryIsoA2'].'</billing_country>  
                <order_status>B</order_status>  
                <credit_card>NC</credit_card>  
                <customer_comment>custmer comments</customer_comment>  
                <staff_comment>staff comments</staff_comment>  
                <shipping_charges>'.$resOrders['shippingAmount'].'</shipping_charges>  
                <payment_type>'.$payment_type.'</payment_type>  
                <current_currency>PKR</current_currency>  
                <currency_code>'.$resOrders['purchasedCurrency'].'</currency_code>  
                <total_amount>'.$resOrders['orderTotalAmount'].'</total_amount>	    
                <all_products>';
                $subItem    =   1;
                $prevbusID  =   '';
                $busArr     =   array();
                $ordArr     =   array();
                if(!empty($resOrderItems)) {
                    foreach($resOrderItems as $item) {
                        
                        $sub_account_id = $item['api_id'];// $acIDs;
                        
                        if(empty($busArr) || (!in_array($item['businessID'],$busArr) && !empty($busArr))) {
                            $busArr[]                             = $item['businessID'];
                            $ordArr[]                             = $item['masterOrderID'];
                        }
                      /* if($prevbusID!=$item['businessID'] && $item['businessID']!='' && $prevbusID!='') {
                            
                            $subItem = $subItem + 1;
                            $sub_account_id = 'KHI-8880'.$subItem;
                           
                        }*/
                        $item['productOptionName'] = substr($item['productOptionName'],0,25);
                        //$item['productOptionName'] = str_replace(array("[","]"),'',$item['productOptionName']);
                        
                        $xml .= '<products_detail>  

                                <product_code>'.$item['optionSKU'].'</product_code>           

                                <product_name>'.$item['productOptionName'].'</product_name>  

                                <product_price>'.$item['orderItemPrice'].'</product_price>  

                                <product_quantity>'.$item['orderItemQuantity'].'</product_quantity>  

                                <product_variations>1</product_variations>  
                                
                                <sub_account_id>'.$sub_account_id.'</sub_account_id>

                </products_detail>';
                        $prevbusID = $item['businessID'];
                    }
                    
                }
                
                
                $xml .= ' </all_products>     
                        </Orderdetail>
                        </AccessRequest>
                        </BenefitDocument>';
                
                 //echo $xml;exit;
                 $c = curl_init();
                 curl_setopt($c, CURLOPT_URL, blueEx );
                // curl_setopt($ch, CURLOPT_HEADER, false);
                 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );
                 curl_setopt($c, CURLOPT_USERPWD, "KHI-99999:42yBhX5RX20ucJw74Gr9");
                 //curl_setopt($c, CURLOPT_USERPWD, "apitest:1234567890");
                 curl_setopt($c, CURLOPT_POST, 1 );
                 curl_setopt($c, CURLOPT_POSTFIELDS, array(xml=>$xml) );                 
                 //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                 //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                 curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/text+xml',
                'charset=utf-8'));

                
                 $result = curl_exec ($c);
                 
                /*$result = '<?xml version="1.0" encoding="utf-8"?>
<result>
<status>1</status>
<order_code>16657</order_code><PickupCn>
    <merchantDetail>
    <ac_code>158963</ac_code>
    <cn>5000691292</cn>
    <printCN>http://benefit.blue-ex.com/customerportal/inc/cnprnb.php?5000691292</printCN>
    </merchantDetail>
    <merchantDetail>
    <ac_code>160993</ac_code>
    <cn>5000691293</cn>
    <printCN>http://benefit.blue-ex.com/customerportal/inc/cnprnb.php?5000691293</printCN>
    </merchantDetail>
</PickupCn><DeliveryCn>5000691294</DeliveryCn>
<printCN>http://benefitx.blue-ex.com/customerportal/inc/cnprnb.php?5000691294</printCN>
</result>             
                   ';*/
                 
                 $xmlParse =  new SimpleXMLElement(stripslashes(trim($result)));
                 $resp = array();
                 $resp['status']     = $xmlParse->status;
                 $resp['order_code'] = $xmlParse->order_code;  
                 $cnExists = 0;
                 for($cim=0;$cim<count($ordArr);$cim++) {
                    if($xmlParse->PickupCn->merchantDetail[$cim]->cn!='') {
                        $resp['cn'][$ordArr[$cim]]         = $xmlParse->PickupCn->merchantDetail[$cim]->cn;
                        $cnExists = 1;
                    }
                 }
                 $resp['DeliveryCn'] = $xmlParse->DeliveryCn;
                 if($cnExists<=0) {
                     $resp['cn'][$ordArr[0]] = $resp['DeliveryCn'];
                 }
                 //$sxml = simplexml_load_string($result);
                 //echo $cnno=$sxml->row->cnno;
                 //echo "<pre>";print_r($resp);exit;
                 return $resp;  
      
  
	}
        public function orderAPIBeta($resOrders,$resOrderItems,$languageIDs,$acIDs='')
	{
		set_time_limit(0);                 
                //define('blueEx', "http://bluekart.com/api/live/order/v2/order_api.php");
                define('blueEx', "http://bluekart.com/api/test/multiplecn/order_api.php");//http://bluekart.com/api/test/v2/sub-accounts/subaccount/order/order_api.php
               // <api_code>KHujdgetrbcnhgsw</api_code>
              //  <acno>KHI-88888</acno>
               // <userid>subaccounts</userid>
               //            <password>subaccounts</password>
                $bI 			= unserialize($resOrders['billingAddress']);
                $sI 			= unserialize($resOrders['shippingAddress']);
                $payment_type           = ($resOrders['paymentSettingsGroupID']==18)?'COD':'CC';
                $ObjCountry             = new CountryModel();
                $countryDet             = $ObjCountry->getCountryDetails($bI['billingCountry'],$languageIDs);
                $shipCountryDet         = $ObjCountry->getCountryDetails($sI['shippingCountryID'],$languageIDs);
                $shipCountryDet['countryIsoA2'] = 'PK';
                $sI['shippingCity'] = 'KHI';
                if($bI['billingPhone']=='') {
                    $bI['billingPhone'] = '123456';
                }
                
                $xml = '<?xml version="1.0" encoding="utf-8"?>
                            <BenefitDocument>
                            <AccessRequest>
                            <DocumentType>1</DocumentType>
                            <Orderdetail>
                                  <api_code>KHujdgetrbcnhgsw</api_code>
                                  <acno>LHE-00737</acno>
                           <testbit>y</testbit>
                           <userid>dukanone</userid>
                           <password>123456</password>
                           <cn_generate>y</cn_generate>
                 

                <shipper_name>'.$sI['shippingFname']." ".$sI['shippingLname'].'</shipper_name>  
                <shipper_email>'.$bI['billingEmail'].'</shipper_email>    
                <shipper_contact>'.$bI['billingPhone'].'</shipper_contact>
                <shipper_address>'.$sI['shippingAddress1']." ".$sI['shippingAddress2'].'</shipper_address> 
                <shipper_city>'.$sI['shippingCity'].'</shipper_city> 
                <shipper_country>'.$shipCountryDet['countryIsoA2'].'</shipper_country>  
                <billing_name>'.$bI['billingFirstName']." ".$bI['billingLastName'].'</billing_name>  
                <bill_email>'.$bI['billingEmail'].'</bill_email>
                <billing_contact>'.$bI['billingPhone'].'</billing_contact> 
                <billing_address>'.$bI['billingAddress1']." ".$bI['billingAddress2'].'</billing_address>    
                <billing_city>'.$bI['billingCity'].'</billing_city>    
                <billing_country>'.$countryDet['countryIsoA2'].'</billing_country>  
                <order_status>B</order_status>  
                <credit_card>NC</credit_card>  
                <customer_comment>custmer comments</customer_comment>  
                <staff_comment>staff comments</staff_comment>  
                <shipping_charges>'.$resOrders['shippingAmount'].'</shipping_charges>  
                <payment_type>'.$payment_type.'</payment_type>  
                <current_currency>PKR</current_currency>  
                <currency_code>'.$resOrders['purchasedCurrency'].'</currency_code>  
   
                <all_products>';
                $subItem    =   1;
                $prevbusID  =   '';
                if(!empty($resOrderItems)) {
                    foreach($resOrderItems as $item) {
                        
                        $sub_account_id = $acIDs;//'KHI-88801';
                        
                       /* if($prevbusID!=$item['businessID'] && $item['businessID']!='' && $prevbusID!='') {
                            
                            $subItem = $subItem + 1;
                            $sub_account_id = 'KHI-8880'.$subItem;
                           
                        }*/
                     
                        $xml .= '<products_detail>  

                                <product_code>'.$item[optionSKU].'</product_code>           

                                <product_name>'.$item['productOptionName'].'</product_name>  

                                <product_price>'.$item['orderItemPrice'].'</product_price>  

                                <product_quantity>'.$item['orderItemQuantity'].'</product_quantity>  

                                <product_variations>1</product_variations>  
                                
                                <sub_account_id>'.$sub_account_id.'</sub_account_id>

                </products_detail>';
                        $prevbusID = $item['businessID'];
                    }
                    
                }
                
                
                $xml .= ' </all_products>  
   
</Orderdetail>
</AccessRequest>
</BenefitDocument>';
                
                
                 $c = curl_init();
                 curl_setopt($c, CURLOPT_URL, blueEx );
                // curl_setopt($ch, CURLOPT_HEADER, false);
                 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );
                 curl_setopt($c, CURLOPT_USERPWD, "apitest:1234567890");
                 curl_setopt($c, CURLOPT_POST, 1 );
                 curl_setopt($c, CURLOPT_POSTFIELDS, array('xml'=>$xml) );                 
                 //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                 //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                 curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/text+xml',
                'charset=utf-8'));

                
                 $result = curl_exec ($c);
                
                 $xmlParse =  new SimpleXMLElement(stripslashes(trim($result)));
                 $resp = array();
                 $resp['status']     = $xmlParse->status;
                 $resp['order_code'] = $xmlParse->order_code;                
                 $resp['cn']         = $xmlParse->PickupCn->merchantDetail->cn;
                 $resp['DeliveryCn'] = $xmlParse->DeliveryCn;

                 return $resp;  
      
  
	}
        public function merchantAccountAPI($resOrderItems) {
            set_time_limit(0); 
            
            $merchantAddress = $resOrderItems['locAddress1'];
            if($resOrderItems['locAddress2']!='') {
                $merchantAddress .= ", ".$resOrderItems['locAddress2'];
            }
            
           
            define('blueEx', "http://bluekart.com/api/test/merchants/benefit_sub_account.php"); 
            $xml = '<?xml version="1.0" encoding="utf-8"?>  
            <BenefitDocument>  
             <AccessRequest>  
             <DocumentType>9</DocumentType>             
                <api_code>KHujdgetrbcnhgsw</api_code>
                <userid>dukanone</userid>
                <password>123456</password>
                <AccountCode>LHE-00737</AccountCode>
                <MerchantName>'.$resOrderItems['businessName'].'</MerchantName>
                <MerchantAddress>'.$merchantAddress.'</MerchantAddress>
                <MerchantContact>'.$resOrderItems['businessPhone'].'</MerchantContact>
                <MerchantEmail>'.$resOrderItems['businessEmail'].'</MerchantEmail>
                <CityCode>KHI</CityCode>          
            </AccessRequest>  
            </BenefitDocument>';  
            
         
            $c = curl_init();  

            curl_setopt($c, CURLOPT_URL, blueEx );  

            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );

            curl_setopt($c, CURLOPT_POST, 1 );  

            curl_setopt($c, CURLOPT_POSTFIELDS, array('xml'=>$xml) );  

            curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/soap+xml', 'charset=utf-8'));  
  
            $result = curl_exec ($c);  
            //echo $result;
            //exit;
            $xmlParse =  new SimpleXMLElement(stripslashes(trim($result)));
            $resp = array();
            
            if($xmlParse->status>0) {
                $resp['account_id']     = $xmlParse->message;
                
            } else {
                $resp['account_id'] = '';
                
            }
            return $resp['account_id'];  
        }
        public function trackShippingAPI($cnNumber) {
            set_time_limit(0); 
            
            define('blueEx', "http://bluekart.com/api/live/console-orders/tracking/tracking_api.php"); 
            $xml = '<?xml version="1.0" encoding="utf-8"?>  
            <BenefitDocument>  
             <AccessRequest>  
             <DocumentType>1</DocumentType>  
            <Tracking_detail>  
                <api_code>KHujdgetrbcnhgsw</api_code>
                <account_number>LHE-00737</account_number>  
                <userid>dukanone</userid>
                <password>123456</password>
                <order_number>'.$cnNumber.'</order_number>
          </Tracking_detail> 
          </AccessRequest> 
          </BenefitDocument>';  
  
            $c = curl_init();  

            curl_setopt($c, CURLOPT_URL, blueEx );  

            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );  

            curl_setopt($c, CURLOPT_USERPWD, "apitest:1234567890");  

            curl_setopt($c, CURLOPT_POST, 1 );  

            curl_setopt($c, CURLOPT_POSTFIELDS, array('xml'=>$xml) );  

            curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/soap+xml', 'charset=utf-8'));   
  
            $apiResponse = curl_exec ($c);  
            //echo $apiResponse;
            //exit;
             /*$apiResponse = '<?xml version="1.0" encoding="utf-8"?>  
                <result>  
                <status>1</status>  
                <tracking_detail>  
                <Consignment_Detail>
                <cn_number>5000562308</cn_number>
                <message>Consignment Note # : 5000562308</message>
                <message>Dear Arsalan Perwaiz,</message>
                <message>Dear Arsalan Perwaiz111,</message>
                </Consignment_Detail>
                <Consignment_Detail>
                <cn_number>10</cn_number>
                <message>Consignment Note # : 5000562308</message>
                <message>Dear Arsalan Perwaiz,</message>

                </Consignment_Detail>
                </tracking_detail>  

                </result> ';*/
                     $xmlParse              = new SimpleXMLElement(stripslashes($apiResponse));
                    
                     $message = '';
                     if(!empty($xmlParse) && count($xmlParse->status)>0) {
                        for($ci=0;$ci<count($xmlParse->status);$ci++) {
                            if($xmlParse->status[$ci]->shipmentnumber!='') {
                                $message = ($message=='') ? 'Shipment Number: '.$xmlParse->status[$ci]->shipmentnumber:$message."<br>".'Shipment Number: '.$xmlParse->status[$ci]->shipmentnumber;
                                //$resp['Consignment_Detail'][$ci]['cn'] = $xmlParse->tracking_detail->Consignment_Detail[$ci]->cn_number;                         
                                for($cim=0;$cim<count($xmlParse->status[$ci]->statusrow);$cim++) {                                
                                 $message = ($message=='') ? $xmlParse->status[$ci]->statusrow[$cim]->statusdate.' '.$xmlParse->status[$ci]->statusrow[$cim]->statustime.' : '.stripslashes($xmlParse->status[$ci]->statusrow[$cim]->statusmessage):$message."<br>".$xmlParse->status[$ci]->statusrow[$cim]->statusdate.' '.$xmlParse->status[$ci]->statusrow[$cim]->statustime.' : '.stripslashes($xmlParse->status[$ci]->statusrow[$cim]->statusmessage);
                                }
                            }
                        }
                     }
                     $resp['msg'] = $message;                    
                     return $resp;  
        }
         public function trackShippingAPIBeta($cnNumber) {
            set_time_limit(0); 
              //5000999999
            /*<api_code>X5RXJw74Gr42yBh920uc</api_code>  
  
                <account_number>KHI-99999</account_number> */ 

            //define('blueEx', "http://bluekart.com/api/live/tracking/v2/tracking_api.php"); 
           // define('blueEx', "http://bluekart.com/api/tracking/tracking_api.php"); 
            define('blueEx', "http://bluekart.com/api/test/v2/sub-accounts/subaccount/tracking/tracking_api.php"); 
            $xml = '<?xml version="1.0" encoding="utf-8"?>  
            <BenefitDocument>  
             <AccessRequest>  
             <DocumentType>1</DocumentType>  
            <Tracking_detail>  
                <api_code>KHujdgetrbcnhgsw</api_code>
                <account_number>LHE-00737</account_number>                
                <order_number>'.$cnNumber.'</order_number>
          </Tracking_detail> 
          </AccessRequest> 
          </BenefitDocument>';  
  
            $c = curl_init();  

            curl_setopt($c, CURLOPT_URL, blueEx );  

            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );  

            curl_setopt($c, CURLOPT_USERPWD, "apitest:1234567890");  

            curl_setopt($c, CURLOPT_POST, 1 );  

            curl_setopt($c, CURLOPT_POSTFIELDS, array('xml'=>$xml) );  

            curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/soap+xml', 'charset=utf-8'));   
  
            $apiResponse = curl_exec ($c);  
             /*$apiResponse = '<?xml version="1.0" encoding="utf-8"?>  
<result>  
<status>1</status>  
<tracking_detail>  
<Consignment_Detail>
<cn_number>5000562308</cn_number>
<message>Consignment Note # : 5000562308</message>
<message>Dear Arsalan Perwaiz,</message>
<message>Dear Arsalan Perwaiz111,</message>
</Consignment_Detail>
<Consignment_Detail>
<cn_number>10</cn_number>
<message>Consignment Note # : 5000562308</message>
<message>Dear Arsalan Perwaiz,</message>

</Consignment_Detail>
</tracking_detail>  
  
</result> ';*/
                     $xmlParse              = new SimpleXMLElement(stripslashes($apiResponse));
                     $message = '';
                     if(!empty($xmlParse) && count($xmlParse->tracking_detail->Consignment_Detail)>0) {
                        for($ci=0;$ci<count($xmlParse->tracking_detail->Consignment_Detail);$ci++) {
                            //$resp['Consignment_Detail'][$ci]['cn'] = $xmlParse->tracking_detail->Consignment_Detail[$ci]->cn_number;                         
                            for($cim=0;$cim<count($xmlParse->tracking_detail->Consignment_Detail[$ci]->message);$cim++) {                                
                                $message = ($message=='') ? $xmlParse->tracking_detail->Consignment_Detail[$ci]->message[$cim]:$message."<br>".$xmlParse->tracking_detail->Consignment_Detail[$ci]->message[$cim];
                            }
                        }
                     }
                     $resp['msg'] = $message;
                     
            return $resp;  
        }
        public function checkShippingAPI() {
            set_time_limit(0);  
  
            define('blueEx', "http://bluekart.com/api/shipping/shipping_api.php");  
  
            $xml = '<?xml version="1.0" encoding="utf-8"?>  

            <BenefitDocument>  

             <AccessRequest>  

             <DocumentType>1</DocumentType>  

            <Shipdetail>  
  
            <api_code>X5RXJw74Gr42yBh920uc</api_code>                
            <account_number>KHI-99999</account_number>          
            <service_code>BS</service_code>  
            <destination_country>PK</destination_country >  
            <weight>5</weight>   

            </Shipdetail>  

            </AccessRequest>  

            </BenefitDocument>';  



            $c = curl_init();  

            curl_setopt($c, CURLOPT_URL, blueEx );  

            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1 );  

            curl_setopt($c, CURLOPT_USERPWD, "apitest:1234567890");  

            curl_setopt($c, CURLOPT_POST, 1 );  

            curl_setopt($c, CURLOPT_POSTFIELDS, array('xml'=>$xml) );  

            curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type=application/soap+xml',  

           'charset=utf-8'));  

            $result = curl_exec ($c);  
  
            return $result;  
  
        }
}