<?php
session_start();
require_once "../../../config.php";
require_once "../../../validation.php";
require_once "../../../Helper.php";

require_once '../../database1.php';
require_once "../../check_admin.php";

require_once '../check_edit_page_ajax.php';

class EditAjax extends database{
	public function getCheckOut($id)
	{
		$where['cl_id'] = $id;
		return $this->fetchRow('tb_checkout',$where);
	}

	public function updateTrackingNumber($trackingNumber, $id)
	{
		$where['cl_id'] = $id;
		$data['cl_tracking_number'] = $trackingNumber;

		return $this->update('tb_checkout',$data, $where);
	}
}

$helper = new Helper();
$validation = new validation();

$obj = new EditAjax();
$shipment = $res = $obj->getCheckOut($id);
if(!$res)
{
	http_response_code(500);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

if(trim($shipment['cl_tracking_number']) != '')
{
	http_response_code(500);
	echo json_encode(array('error_text' => 'Tracking number already found. Please clear it and save form'));
	exit;
}


$courierService = $res['cl_courier_provider'];



if($courierService == 'DPD')
{
	if($shipment['cl_checkout_type'] == 'ind')
	{
		$name = $shipment['cl_fname'] . ' ' . $shipment['cl_surname'];
	}
	else
	{
		$name = $shipment['cl_company_name'] . ', ' . $shipment['cl_registration_number'];	
	}

	$url = 'https://integration.dpd.lv:8443/ws-mapper-rest/createShipment_';
	
	$countryArray = $helper->getCountryCodes();
	//echo $shipment['cl_country'];
	$data = array(
		'username' => DPD_SHIPPING_USERNAME,
		'password' => DPD_SHIPPING_PASSWORD,
		'name1' => $name,
		'street' => $shipment['cl_address'],
		'city' => $shipment['cl_city'],
		'country' => $countryArray[$shipment['cl_country']],
		'pcode' => $shipment['cl_pasta_indeks'],
		'phone' => $shipment['cl_mobile'],
		'idm_sms_number' => $shipment['cl_mobile'],
		'email' => $shipment['cl_email'],
		'parcel_type' => 'D',
		'num_of_parcel' => 1,
		'weight' => 1,
		'order_number' => $shipment['cl_id']
	);

	


	$postvars = '';
  foreach($data as $key=>$value) {
    $postvars .= $key . "=" . $value . "&";
  }

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
	//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$result = curl_exec($ch); 
	

	$result = json_decode($result);
	
	curl_close($ch); 


	if($result->status == 'err')
	{
		http_response_code(400);
		$response['error_text'] = $result->errlog;
		echo json_encode($response);
		exit;
	}
	else if($result->status == 'ok')
	{
		$trackingNumber = $result->pl_number[0];
		$res = $obj->updateTrackingNumber($trackingNumber, $id);
		if(!$res)
		{
			http_response_code(400);
			$response['error_text'] = 'Shipment created. Tracking Number not updated to database. Consider creatng a new shipment';
			echo json_encode($response);
			exit;
		}
		
		http_response_code(200);
		$response['message'] = 'Shipment Created Succesfully. Tracking Number: ' . $trackingNumber;
		$response['tracking_number'] = $trackingNumber;
		echo json_encode($response);
		exit;
	}

	
}
else if($courierService == 'Omniva')
{
	/*use Omniva\Parcel;
	use Omniva\Client;
	use Omniva\Address;
	use Omniva\Service;

	$client = new Client('efix', 'Efix1234');


	//$shipment = $parcel->getShipment();
	//$id = $parcel->getId();

	$omnivaParcel = new Parcel();
	$omnivaParcel
	    ->setWeight($parcel->getWeightInKg())
	    ->setPartnerId($id)
	    ->setComment('')
	;

/*	if ($shipment->getCodAmount()) {
	    $omnivaParcel->setCodAmount($shipment->getCodAmount());
	    $omnivaParcel->addService(Service::COD());
	} */

/*	$sender = new Address();
	$sender
	    ->setName($shipment['cl_fname'] . ' ' . $shipment['cl_surname'])
	    ->setPhone($shipment['cl_mobile'])
	    ->setCountryCode('LV')
	    ->setCity($shipment['cl_city'])
	    ->setStreet($shipment['cl_address'])
	    ->setPostCode($shipment['cl_pasta_indeks'])
	;

//	if ($shipment->getSender()->getEmail()) {
	    $sender->setEmail($shipment['cl_email']);
	//}

	$omnivaParcel->setSender($sender);

	$returnee = clone $sender;
	$omnivaParcel->setReturnee($returnee);


	$receiver = new Address();
	$receiver
	    ->setName($shipment['cl_fname'] . ' ' . $shipment['cl_surname'])
	    ->setCountryCode('LV')
	;

	//if ($shipment->getReceiver()->getEmail()) {
	    $receiver->setEmail($shipment['cl_email']);
	//}

//	if ($shipment->getReceiver()->getPhone()) {
	    $receiver->setPhone($shipment['cl_mobile']);
	//}

	/*if ($shipment->getReceiver()->isTypeTerminal()) {
	    $terminal = $shipment->getReceiver()->getTerminal();

	    $pickupPoint = new PickupPoint($terminal->getIdentifier());
	    $pickupPoint->setType($terminal->isPostOffice() ? PickupPoint::TYPE_POST_OFFICE : PickupPoint::TYPE_TERMINAL);

	    $receiver->setPickupPoint($pickupPoint);

	    if ($shipment->getReceiver()->getPhone()) {
	        $omnivaParcel->addService(Service::SMS());
	    }

	    if ($shipment->getReceiver()->getEmail()) {
	        $omnivaParcel->addService(Service::EMAIL());
	    }
	} else { */
/*	    $receiver
	        ->setCity($shipment['cl_city'])
	        ->setStreet($shipment['cl_address'])
	        ->setPostCode($shipment['cl_pasta_indeks']);
//	}
	$omnivaParcel->setReceiver($receiver);

	$response = $client->createShipment($omnivaParcel);

	$trackingNumber = $response->savedPacketInfo->barcodeInfo->barcode;
	$parcel->setTrackingNumber($trackingNumber);
	$omnivaParcel->setTrackingNumber($trackingNumber);

	$response = $client->getLabel($omnivaParcel);

	$res = $obj->updateTrackingNumber($trackingNumber, $id);
	print_r($res); */
}