<?php

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

class W2W_Shipping_Track {
	
	public function __construct() {
		
		// 后台设置项
		add_filter( 'w2w_settings_tabs', array( $this, 'logistics_tab' ), 10 );
		add_action( 'w2w_settings_logistics_tab_content_start', array( $this, 'logistics_tab_content' ) );
		
		if( is_admin() ) {
			// 发货信息
			add_action( 'add_meta_boxes', array( $this, 'add_shipping_meta_box' ) );
			add_action( 'save_post', array( $this, 'save_shipping_meta_box' ), 10, 2 );
			
			// 后台样式
			add_action( 'admin_enqueue_scripts', array( $this, 'shipping_admin_style' ) );
		}
		
		// 订单状态
		add_action( 'init', array( $this, 'register_order_status' ) );
		add_action( 'woocommerce_order_actions', array( $this, 'add_order_meta_box_actions' ) );
		add_filter( 'wc_order_statuses', array( $this, 'add_order_statuses' ) );
	}
	
	// 物流公司
	public function get_shippers() {
		
		$shippers = array(
			'SF' => '顺丰速运',
			'HTKY' => '百世快递',
			'ZTO' => '中通快递',
			'STO' => '申通快递',
			'YTO' => '圆通速递',
			'YD' => '韵达速递',
			'YZPY' => '邮政快递包裹',
			'EMS' => 'EMS',
			'HHTT' => '天天快递',
			'JD' => '京东物流',
			'QFKD' => '全峰快递',
			'GTO' => '国通快递',
			'UC' => '优速快递',
			'DBL' => '德邦',
			'FAST' => '快捷快递',
			'ZJS' => '宅急送'
		);
		
		return apply_filters( 'w2w_shippers', $shippers );
	}
	
	// 获取物流接口提供商
	public function get_logistics_providers() {
		
		return apply_filters( 'w2w_logistics_providers', array() );
	}
	
	// 获取物流接口设置
	public function get_provider_settings( $provider ) {
		
		$settings = get_option( 'w2w-settings' );
		return isset( $settings['logistics'][$provider] ) ? $settings['logistics'][$provider] : false;
	}
	
	// 检查物流接口设置
	public function check_provider_settings( $provider ) {
		
		$logistics_providers = $this->get_logistics_providers();
		$provider_settings = $this->get_provider_settings( $provider );
		
		foreach( (array) $logistics_providers[$provider]['fields'] as $field ) {
			if( isset( $field['required'] ) && $field['required'] == true && empty( $provider_settings[$field['name']] )) {
				return false;
			}
		}
		return true;
	}
	
	// 格式化物流信息
	public function format_shipping_detail( $tracks ) {
		
		foreach( $tracks as $i => $track ) {
			$tracks[$i]['date'] = date( 'm-d', strtotime( $track['AcceptTime'] ) );
			$tracks[$i]['time'] = date( 'H:i', strtotime( $track['AcceptTime'] ) );
		}
		
		return $tracks;
	}
	
	// 后台设置项
	public function logistics_tab( $tabs ) {
		
		$tabs['logistics'] = '物流信息';
		return $tabs;
	}
	
	public function logistics_tab_content( $settings ) {
		
		$logistics_providers = W2W()->shipping_track->get_logistics_providers();
	?>
	<tr>
	<th ><label for="w2w-settings[logistics][provider]">物流接口提供商</label></th>
	<td><select id="w2w-settings[logistics][provider]" name="w2w-settings[logistics][provider]">
		<option value="-1">请选择</option>
		<?php foreach( $logistics_providers as $slug => $provider ): ?>
			<option value="<?php echo $slug ?>" <?php selected( isset( $settings['logistics']['provider'] ) && $slug == $settings['logistics']['provider'] ) ?>><?php echo isset( $provider['label'] ) ? $provider['label'] : '' ?></option>
		<?php endforeach; ?>
	</select></td>
	</tr>
	
	<?php foreach( (array) $logistics_providers as $slug => $provider ): ?>

		<?php foreach( (array) $provider['fields'] as $field ): ?>
			
			<?php if( $field['type'] == 'text' ): ?>
				<tr class="provider-field <?php echo $slug ?>-field <?php if( isset( $settings['logistics']['provider'] ) && $slug == $settings['logistics']['provider'] ) echo 'field-active' ?>">
				<th ><label for="w2w-settings[logistics][<?php echo $slug ?>][<?php echo $field['name'] ?>]"><?php echo $field['label'] ?></label></th>
				<td><input type="text" id="w2w-settings[logistics][<?php echo $slug ?>][<?php echo $field['name'] ?>]" name="w2w-settings[logistics][<?php echo $slug ?>][<?php echo $field['name'] ?>]" value="<?php echo isset( $settings['logistics'][$slug][$field['name']] ) ? esc_attr( $settings['logistics'][$slug][$field['name']] ) : '' ?>" class="regular-text" autocomplete="off"></td>
				</tr>
			<?php endif; ?>
			
		<?php endforeach; ?>
		
	<?php endforeach; ?>
	
	<tr>
	<th ><label for="w2w-settings[logistics][cache]">物流信息缓存时长(小时)</label></th>
	<td>
		<input type="number" id="w2w-settings[logistics][cache]" name="w2w-settings[logistics][cache]" value="<?php echo isset( $settings['logistics']['cache'] ) ? esc_attr( $settings['logistics']['cache'] ) : '' ?>" placeholder="2" autocomplete="off">
		<!--<p class="description">快递鸟建议缓存 4小时</p>-->
	</td>
	</tr>
	
	<script>
	;(function($) {
	$(function() {
	// 物流提供商切换
	$('[id="w2w-settings[logistics][provider]"]').change(function() {
		$('#tab-logistics .settings-table tr.provider-field').addClass('field-active').not('.' + $(this).val() + '-field').removeClass('field-active');
	});
	})
	})(jQuery)
	</script>
	<style>
	#tab-logistics tr.provider-field {
		display: none;
	}
	#tab-logistics tr.provider-field.field-active {
		display: table-row;
	}
	</style>
	<?php
	}
	
	// 为订单填写发货信息
	public function add_shipping_meta_box() {
		add_meta_box( 'w2w-shipping-meta-box', '物流信息', array( $this, 'shipping_meta_box_content' ), 'shop_order', 'side', 'low' );
	}
	
	public function shipping_meta_box_content( $post ) {
		
		$order = wc_get_order( $post );
		$shipping = get_post_meta( $post->ID, 'w2w_shipping', true );
		$shipping_detail = get_post_meta( $post->ID, 'w2w_shipping_detail', true );
		$shippers = $this->get_shippers();
		
		?>
		<?php //if( $order->get_status() == 'processing' || $order->get_status() == 'shipped' || $order->get_status() == 'received' ): ?>
			<input type="hidden" name="w2w_meta_box_nonce" value="<?php echo wp_create_nonce( 'w2w-metabox' ) ?>">
			<table>
			<tr>
				<td><label for="w2w-shipping[shipper]">快递公司</label></td>
				<td><select id="w2w-shipping[shipper]" name="w2w-shipping[shipper]">
					<option value="0">无</option>
				<?php foreach( $shippers as $code => $name ): ?>
					<option value="<?php echo $code ?>" <?php isset( $shipping['shipper'] ) && selected( $shipping['shipper'], $code ) ?>><?php echo $name ?></option>
				<?php endforeach; ?>
				</select></td>
			</tr>
			<tr>
				<td><label for="w2w-shipping[code]">运单号</label></td>
				<td><input type="text" id="w2w-shipping[code]" name="w2w-shipping[code]" value="<?php echo isset( $shipping['code'] ) ? $shipping['code'] : '' ?>"></td>
			</tr>
			</table>
			<?php if( ! empty( $shipping_detail['detail']['Traces'] ) ): ?>
				<table class="shipping-detail-table">
				<?php foreach( array_reverse( $shipping_detail['detail']['Traces'] ) as $trace ): ?>
					<tr>
					<td class="station"><?php echo $trace['AcceptStation'] ?></td>
					<td class="time"><?php echo $trace['AcceptTime'] ?></td>
					</tr>
				<?php endforeach; ?>
				</table>
			<?php endif; ?>
		<?php //endif; ?>
		<style>
		.shipping-detail-table tr {
			display: flex;
			display: -webkit-flex;
			flex-direction: column;
			-webkit-flex-direction: column;
			padding: 10px 0
		}
		.shipping-detail-table .station {
			color: #E91E63;
		}
		.shipping-detail-table .time {
			color: #777;
		}
		</style>
		<?php
	}
	
	// 保存发货信息
	public function save_shipping_meta_box( $post_id ) {
		//验证
		if( ! isset($_POST['w2w_meta_box_nonce']) || ! wp_verify_nonce( $_POST['w2w_meta_box_nonce'], 'w2w-metabox' ) ) {
			return $post_id;
		}

		//自动保存检查
		if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
			return $post_id;
		}

		//检查权限
		if( 'page' == $_POST['post_type'] ) {
			if (!current_user_can('edit_page', $post_id) ) {
				return $post_id;
			}
		}
		elseif( ! current_user_can('edit_post', $post_id) ) {
			return $post_id;
		}
		
		$order = wc_get_order( $post_id );
		$old_shipping = get_post_meta( $post_id, 'w2w_shipping', true );
		$shipping_detail = get_post_meta( $post_id, 'w2w_shipping_detail', true );
		$shipping = $_POST['w2w-shipping'];
		$data = array(
			'shipper' => isset( $shipping['shipper'] ) ? sanitize_text_field( $shipping['shipper'] ) : '',
			'code' => isset( $shipping['code'] ) ? sanitize_text_field( $shipping['code'] ) : '',
			'date_shipped' => date_i18n( 'Y-m-d H:i:s' )
		);
		if( ! $old_shipping || $old_shipping['shipper'] != $data['shipper'] || $old_shipping['code'] != $data['code']
			|| ! $shipping_detail || is_null( $shipping_detail['detail'] ) )
		{
			
			if( ! empty( $data['shipper'] ) && ! empty( $data['code'] ) ) {
				update_post_meta( $post_id, 'w2w_shipping', $data );
				$order->set_status( 'shipped', '订单已发货' );
				do_action( 'w2w_order_shipped', $post_id, $data );
				$this->query_shipping( $order, $data['shipper'], $data['code'], true );
			}
		}
	}
	
	// 物流查询
	public function query_shipping( $order, $shipper, $code, $force = false ) {
		
		$settings = get_option( 'w2w-settings' );
		
		// 缓存检查
		$shipping_cache =  ! empty( $settings['logistics']['cache'] ) ? (int) $settings['logistics']['cache'] : 2;
		$old_shipping_detail = get_post_meta( $order->get_id(), 'w2w_shipping_detail', true );
		if( ! $force && $old_shipping_detail && time() <= $old_shipping_detail['time'] + $shipping_cache * 3600 ) {
			return $old_shipping_detail;
		}
		
		if( ! isset( $settings['logistics']['provider'] ) || $settings['logistics']['provider'] == -1 ) {
			
			W2W()->log( 'warning', '请到设置-物流信息页面选择物流接口提供商' );
			return false;
		}
		
		if( ! $this->check_provider_settings( $settings['logistics']['provider'] ) ) {
			
			W2W()->log( 'warning', '请到设置-物流信息页面填写所有必填字段' );
			return false;
		}
		
		$shipping_data = apply_filters( 'w2w_query_shipping_response_' . $settings['logistics']['provider'], false, $shipper, $code );
		
		// 处理物流信息
		if( $shipping_data ) {
			
			// 已签收
			if( $shipping_data['State'] == 3 ) {

				$order->set_status( 'completed', '订单已签收' );
			}
			
			$order->save();
			$shipping_detail = array( 'time' => time(), 'detail' => $shipping_data );
			update_post_meta( $order->get_id(), 'w2w_shipping_detail', $shipping_detail );
			return $shipping_detail;
			
		}else {
			
			update_post_meta( $order->get_id(), 'w2w_shipping_detail', array( 'time' => 0, 'detail' => null ) );
			W2W()->log( 'warning', '物流接口未正确返回数据' );
			return false;
		}
		
	}
	
	// 订单状态
	public function register_order_status() {
		$statuses = array(
			'wc-shipped' => '已发货',
			'wc-received' => '已签收'
		);
		foreach( $statuses as $slug => $status ) {
			register_post_status( $slug, array(
				'label' => $status,
				'public' => true,
				'exclude_from_search' => false,
				'show_in_admin_all_list' => true,
				'show_in_admin_status_list' => true,
				'label_count' => _n_noop( $status . ' <span class="count">(%s)</span>', $status . ' <span class="count">(%s)</span>' )
			) );
		}
	}
	
	public function add_order_meta_box_actions( $actions ) {
		$actions['w2w_shipped'] = '已发货';
		$actions['w2w_received'] = '已签收';
		return $actions; 
	}
	
	public function add_order_statuses( $order_statuses ) {
		$new_order_statuses = array();
		foreach ( $order_statuses as $key => $status ) {
			$new_order_statuses[ $key ] = $status;
			if ( 'wc-completed' === $key ) {
				$new_order_statuses['wc-shipped'] = '已发货';
				$new_order_statuses['wc-received'] = '已签收';
			}
		}
		return $new_order_statuses;
	}
	
	public function shipping_admin_style() {
	?>
	<style>
	.order-status.status-shipped {
		background: #FFC999;
		color: #B16F35;
	}
	.order-status.status-received {
		background: #CDD9FF;
		color: #3656B5;
	}
	</style>
	<?php
	}
}