<?php
/*
 * KDPT物流接口类
 * QwqOffice
 * 2018-04-26
 */

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

class W2W_Shipping_Track_KDPT {
	
	private $name = 'kdpt';
	
	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' => 'KDPT',
			'fields' => array(
				array(
					'type' => 'text',
					'name' => 'apikey',
					'label' => 'KDPT API密钥',
					'required' => true
				)
			)
		);
		
		return $providers;
	}
	
	public function query_shipping( $value, $shipper, $code ) {
		
		$provider_settings = W2W()->shipping_track->get_provider_settings( $this->name );
		
		$com = $this->get_shipper( $shipper );
		if( ! $com ) {
			W2W()->log( 'warning', '物流接口不支持此快递公司: ' . $shipper );
			return false;
		}
		
		$params = array(
			'id' => $provider_settings['apikey'],
			'com' => $com,
			'nu' => $code,
			'order' => 'asc'
		);
		$url = add_query_arg( $params, 'http://q.kdpt.net/api' );
		$response = wp_remote_post( $url );
		
		if( ! is_wp_error( $response ) ) {
			
			$shipping_data = json_decode( $response['body'], true );
			
			if( in_array( (int) $shipping_data['status'], array( 0, 1 ) ) ) {
				
				return $this->format_shipping_data( $shipping_data );
			}else {
				
				W2W()->log( 'warning', '物流接口请求出错: ' . json_encode( $shipping_data ) );
			}
		}else {
			
			W2W()->log( 'warning', '物流接口请求出错: ' . json_encode( $response ) );
		}
		
		return false;
		
	}
	
	public function get_shipper( $shipper ) {
		
		$map = array(
			'SF' => 'shunfeng',
			'HTKY' => 'huitong',
			'ZTO' => 'zhongtong',
			'STO' => 'shentong',
			'YTO' => 'yuantong',
			'YD' => 'yunda',
			'YZPY' => 'chinapost',
			'EMS' => 'ems',
			'HHTT' => 'tiantian',
			'JD' => 'jingdong',
			'QFKD' => 'quanfeng',
			'GTO' => 'guotong',
			'UC' => 'yousu',
			'DBL' => 'debang',
			'FAST' => 'kjkd',
			'ZJS' => 'zjs'
		);
		
		return isset( $map[$shipper] ) ? $map[$shipper] : false;
	}
	
	public function format_shipping_data( $data ) {
		
		$return = array();
		$return['State'] = $data['state'];
		foreach( $data['data'] as $track ) {
			
			$return['Traces'][] = array(
				'AcceptStation' => $track['context'],
				'AcceptTime' => $track['time']
			);
		}
		return $return;
	}
}

$GLOBALS['w2w_shipping_track_kdpt'] = new W2W_Shipping_Track_KDPT();