<?php
require_once dirname(__DIR__) . '/common.php';
$soapClient = new SoapClient(SITE_LINK.'shipping_api/aramex/shipping-services.wsdl');
// echo '<pre>';
//var_dump($soapClient);
//print_r($soapClient->__getFunctions());
//die('ok');
$invoices_array = array();
$shippment_added = $shippment_not_added = array();
$invoices_to_be_updated = array();
$shipping_company_query = $db->query_execute('select * from tbl_shipping_company where shipping_company_id = "'.$_POST['shipping_company_id'].'"');
$shipping_company_data = $db->query_fetch($shipping_company_query);
$shipping_account_data = json_decode($shipping_company_data['note'],true);
$query_invoices = $db->query_execute('select inv.Invoice_ID_Auto,
                                             concat_ws("",inv.invoice_prefix,inv.Invoice_ID) as invoice_nb,
                                             concat_ws("",inv.invoice_prefix,inv.Invoice_ID) as Reference,
                                             (inv.Invoice_Shipping+ inv.Invoice_Net_Total) as Collection,
                                             inv.Invoice_Currency,
                                             cust_cities.Name as customer_city_name,
                                             cust_cities.District as cust_city_state,
                                             cust.Customer_ID,
                                             cust.Customer_Name,
                                             cust.Customer_Email,
                                             address.shipping_street as customer_street,
                                             address.shipping_building  as customer_building,
                                             address.shipping_address as Customer_Address,
                                             country.Code2 as customer_country_code,
                                             cust.Customer_Mobile,
                                             cust.Customer_Lat,
                                             cust.Customer_Lng,
                                             shipping.pick_up_date,
                                             shipping.drop_off_date,
                                             shipping.shipping_status_id,
                                             shipping.api_shipping_id as DBNumber,
                                             shipping.api_other_response,
                                             currency.Currency_Code
                                      from tbl_invoices inv
                                      inner join tbl_customers cust on cust.Customer_ID = inv.Customer_ID
                                      left join tbl_customer_shipping_address address on address.shipping_address_id =  inv.address_id
                                      inner join tbl_all_cities cust_cities on cust_cities.ID = address.city_id
                                      inner join tbl_all_countries country on country.Code =  cust_cities.CountryCode
                                      inner join tbl_common_currency currency on currency.Currency_ID = inv.Invoice_Currency
                                      left join tbl_invoice_shipping shipping on shipping.Invoice_ID_Auto = inv.Invoice_ID_Auto
                                      where inv.Invoice_ID_Auto in ('.implode(",",$_POST['invoices']).')
                                      and (shipping.api_shipping_id is null or  shipping.api_shipping_id <> 0)
                                      ');
while ($invoice_row = $db->query_fetch($query_invoices)){
    $invoice_row['quantity'] = getTotalItems($invoice_row['Invoice_ID_Auto'],$db);
    $invoices_array[$invoice_row['Invoice_ID_Auto']] = $invoice_row;
}
$client_info = array(
    'AccountCountryCode'	=>$shipping_account_data['AccountCountryCode'],
    'AccountEntity'		 	=>$shipping_account_data['AccountEntity'],
    'AccountNumber'		 	=>$shipping_account_data['AccountNumber'],
    'AccountPin'		 	=>$shipping_account_data['AccountPin'],
    'UserName'			 	=>$shipping_company_data['user_name'],
    'Password'			 	=>$shipping_company_data['password'], 
    'Version'		 	    =>$shipping_company_data['api_version'],
);
$transaction = array(
    'Reference1'			=> '001'
);
$shipper =  array(
    'AccountNumber' => $shipping_account_data['AccountNumber'],
    'PartyAddress'	=> array(
        'Line1'					=> 'MAIN ROAD Beirut Central District',
        'City'					=> 'Beirut',
        'StateOrProvinceCode'	=> 'BEIRUT',
        'CountryCode'			=> 'LB'
    ),
    'Contact'		=> array(
        'PersonName'			=> $_POST['from_location'] == 1 ? 'Megara' : ($_POST['from_location'] == 2 ? 'Jouri' : ($_POST['from_location'] == 3 ? 'K boutique' : 'Lamaritta')),
        'CompanyName'			=> $_POST['from_location'] == 1 ? 'Megara' : ($_POST['from_location'] == 2 ? 'Jouri' : ($_POST['from_location'] == 3 ? 'K boutique' : 'Lamaritta')), 
        'PhoneNumber1'			=> $_POST['from_location'] == 1 ? '71144627' : ($_POST['from_location'] == 2 ? '76055537' : ($_POST['from_location'] == 3 ? '76885332' : '70689703')),
        'CellPhone'				=> $_POST['from_location'] == 1 ? '71144627' : ($_POST['from_location'] == 2 ? '76055537' : ($_POST['from_location'] == 3 ? '76885332' : '70689703')),
        'EmailAddress'			=> $_POST['from_location'] == 1 ? 'myrnazein@hotmail.com' : ($_POST['from_location'] == 2 ? 'topmodel_2004_3@hotmail.com' : ($_POST['from_location'] == 3 ? 'manarina.namimo@gmail.com' : 'nanamimo.2505@gmail.com')),
    ),
);
//echo '<pre>';
foreach($invoices_array as $invoice){
    $error_message = '';
    try {
        $consignee  = array(
            'AccountNumber' => $shipping_account_data['AccountNumber'],
            'PartyAddress'	=> array(
                'Line1'					=> ($invoice['Customer_Address'].' '.$invoice['customer_street'].' '.$invoice['customer_building']),
                'City'					=> $invoice['customer_city_name'],
                'CountryCode'			=> $invoice['customer_country_code'],
                'StateOrProvinceCode'	=> $invoice['cust_city_state']
            ),
            'Contact'		=> array(
                'PersonName'			=> $invoice['Customer_Name'],
                'CompanyName'			=> $invoice['Customer_Name'],
                'PhoneNumber1'			=> $invoice['Customer_Mobile'],
                'CellPhone'				=> $invoice['Customer_Mobile'],
                'EmailAddress'			=> $invoice['Customer_Email']
            ),
        );
        $params = array(
            'Shipments' => array(
                'Shipment' => array(
                    'Shipper'	=> $shipper,
                    'Consignee'	=> $consignee,
                    'ShippingDateTime' 			=> $_POST['pick_up_due_date'],
                    'DueDate' 			        => $_POST['pick_up_due_date'],
                    'ForeignHAWB'               => ('INVOICE'.$invoice['Invoice_ID_Auto']),
                    'Details' => array(
                        'NumberOfPieces'		=> $invoice['quantity'],
                        'ActualWeight' => array(
                            'Value'					=> 0.5,
                            'Unit'					=> 'Kg'
                        ),
                        'ProductGroup' 			=> 'DOM', // EXP:Express,DOM:Domestic
                        'ProductType'			=> 'CDA',
                        'PaymentType'			=> 'P',
                        'Services'              => 'CODS',
                        'DescriptionOfGoods' 	=> 'Clothes',
                        'GoodsOriginCountry' 	=> 'TR',
                        // 'CollectAmount'			=> array(
                        //     'Value'					=> $invoice['Collection'],
                        //     'CurrencyCode'			=> $invoice['Currency_Code']
                        // ),
                        'CashOnDeliveryAmount' 	=> array(
                            'Value'					=> $invoice['Collection'],
                            'CurrencyCode'			=> $invoice['Currency_Code']
                        ),
                        'Items' 				=> array()
                    )
                )
            ),
            'ClientInfo' => $client_info,
            'Transaction' => $transaction
        );
        // echo '<pre>';
        // print_r($params);
        //  die('ok');
        $auth_call = $soapClient->CreateShipments($params);// fetch cities 
        // print_r($auth_call);
        if(!$auth_call->HasErrors){
            $response = $auth_call->Shipments->ProcessedShipment;
            $invoice['DBNumber'] = $response->ID;
            $shippment_added = $invoice['Invoice_ID_Auto'];
            $invoices_to_be_updated[$invoice['Invoice_ID_Auto']] = $invoice;
        }else{
            if(!empty($auth_call->Shipments->ProcessedShipment->Notifications->Notification)){
                $returned_notifications = $auth_call->Shipments->ProcessedShipment->Notifications->Notification;
                if(is_array($returned_notifications)){
                    foreach($returned_notifications as $errors){
                        $error_message .= ($error_message == '' ? '' : ',').$errors->Message;
                    }
                }else{
                    $error_message =  $returned_notifications->Message;
                }
            }else{
                $tmp = (array)$auth_call->Notifications->Notification;
                if(!empty($auth_call->Notifications->Notification->Message)){
                    $error_message = $auth_call->Notifications->Notification->Message;
                }else{
                    if(!empty($tmp)){
                        foreach($auth_call->Notifications->Notification as $current_errors){
                            $error_message .= ($error_message == '' ? '' : ',').$current_errors->Message;
                        }
                    }
                }
            }
            $shippment_not_added[$invoice['Invoice_ID_Auto']] = $error_message. '(For invoice: '.$invoice['invoice_nb'].')';
        }
    } catch (SoapFault $fault) {
        $shippment_not_added[$invoice['Invoice_ID_Auto']] =  $fault->faultstring. '(For invoice: '.$invoice['invoice_nb'].')';
    }
} 
if(empty($invoices_to_be_updated))
    die(json_encode(array('error_type'=>'danger','error_message'=>implode("<br>",$shippment_not_added))));

foreach($invoices_to_be_updated as $invoices){
    $updated_invoices =  $db->query_execute('Insert into tbl_invoice_shipping (Invoice_ID_Auto,pick_up_date,drop_off_date,shipping_status_id,api_shipping_id,from_address_id)
    VALUES(?,?,?,2,?,?)',[&$invoices['Invoice_ID_Auto'],&$_POST['pick_up_due_date'],
                          &$_POST['pick_up_due_date'],&$invoices['DBNumber'],&$_POST['from_location']]);
     $db->query_execute('update tbl_invoices 
    set pick_up_date = ?,drop_off_date = ?, shipping_status_id = 2 where Invoice_ID_Auto = ?',[&$_POST['pick_up_due_date'],&$_POST['pick_up_due_date'],&$invoices['Invoice_ID_Auto']]);
}
$message = '';
$message .= !empty($shippment_not_added) ? ('Not Added'.'<br>'.(implode("<br>",$shippment_not_added))) : '';
die(json_encode(array('error_type'=>'success','error_message'=>CommonLanguage::getMessage('Submitted_Successfully').'<br>'.$message)));
