<?php
/*
 * 快递鸟物流接口类
 * QwqOffice
 * 2018-04-26
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class W2W_Shipping_Track_KDN {
	
	private $name = 'kdn';
	
	public function __construct() {
		
		add_filter( 'w2w_logistics_providers', array( $this, 'add_provider' ) );
		add_filter( 'w2w_query_shipping_response_' . $this->name, array( $this, 'query_shipping' ), 10, 3 );
	}
	
	public function add_provider( $providers ) {
		
		$providers[ $this->name ] = array(
			'label' => '快递鸟',
			'fields' => array(
				array(
					'type' => 'text',
					'name' => 'userid',
					'label' => '快递鸟 用户ID',
					'required' => true
				),
				array(
					'type' => 'text',
					'name' => 'apikey',
					'label' => '快递鸟 API KEY',
					'required' => true
				)
			)
		);
		
		return $providers;
	}
	
	public function query_shipping( $value, $shipper, $code ) {
		
		$provider_settings = W2W()->shipping_track->get_provider_settings( $this->name );
		
		$url = 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
		$data = array(
			'ShipperCode' => $shipper,
			'LogisticCode' => $code
		);
		$response = wp_remote_post( $url, array(
			'headers' => array( 'Content-type' => 'application/x-www-form-urlencoded;charset=UTF-8' ),
			'body' => array(
				'EBusinessID' => $provider_settings['userid'],
				'RequestType' => '1002',
				'RequestData' => urlencode( json_encode( $data ) ),
				'DataType' => '2',
				'DataSign' => urlencode( base64_encode( md5( json_encode( $data ) . $provider_settings['apikey'] ) ) )
			)
		) );
		
		if( ! is_wp_error( $response ) ) {
			
			$shipping_data = json_decode( $response['body'], true );
			
			if( $shipping_data['Success'] ) {
				
				return $shipping_data;
			}else {
				
				W2W()->log( 'warning', '接口请求出错: ' . json_encode( $shipping_data ) );
			}
		}else {
			
			W2W()->log( 'warning', '接口请求出错: ' . json_encode( $response ) );
		}
		
		return false;
		
	}
}

$GLOBALS['w2w_shipping_track_kdn'] = new W2W_Shipping_Track_KDN();