<?php
header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

require __DIR__.'/../../need.php';

class kuaidi
{
	private $info = [];
	private $Cookie;
	private $token;

	public function __construct(array $array)
	{
		$this->info = $array;
		$this->process();
	}

	private function process()
	{
		if (!$this->info['id']) {
			$this->output(['code' => -1, 'text' => '请输入需要查询的快递单号']);
			return;
		}
		if (!preg_match('/^[a-z0-9]+$/im', $this->info['id'])) {
			$this->output(['code' => -1, 'text' => '请输入需要查询的快递单号']);
			return;
		}

		try {
			$this->getCookie();
			$this->queryExpress();
		} catch (Exception $e) {
			$this->output(['code' => -3, 'text' => $e->getMessage()]);
		}
	}

	private function getCookie()
	{
		$url = 'https://m.kuaidi100.com/result.jsp?nu=' . $this->info['id'];
		$response = need::teacher_curl($url, ['GetCookie' => true]);
		
		if (!isset($response['Cookie']) || !isset($response['Cookie'][1])) {
			throw new Exception('获取Cookie失败');
		}

		$this->Cookie = implode('; ', $response['Cookie'][1]);
		if (!preg_match('/token=(.+?);/i', $this->Cookie, $matches)) {
			throw new Exception('获取Token失败');
		}
		$this->token = $matches[1];
	}

	private function getExpressType()
	{
		$autoUrl = 'https://m.kuaidi100.com/apicenter/kdquerytools.do?method=autoComNum&text=' . $this->info['id'];
		$result = json_decode(need::teacher_curl($autoUrl, [
			'post' => 'token=&platfrom=MWWW',
			'cookie' => $this->Cookie
		]), true);

		if (!isset($result['auto'][0])) {
			throw new Exception('暂不支持该快递');
		}
		return $result['auto'][0]['comCode'];
	}

	private function queryExpress()
	{
		$type = $this->getExpressType();
		$queryUrl = 'https://m.kuaidi100.com/query';
		$rand = lcg_value();
		
		$post = 'postid=' . $this->info['id'] . '&id=1&valicode=&temp=' . $rand . '&type=' . $type . 
				'&phone=&token=' . $this->token . '&platform=MWWW';

		$response = json_decode(need::teacher_curl($queryUrl, [
			'post' => $post,
			'cookie' => $this->Cookie,
			'Header' => [
				'Host: m.kuaidi100.com',
				'Connection: keep-alive',
				'Content-Length: ' . strlen($post),
				'Accept: application/json, text/javascript, */*; q=0.01',
				'X-Requested-With: XMLHttpRequest',
				'User-Agent: Mozilla/5.0 (Linux; Android 7.1.2; OPPO R11t Build/N6F26Q; wv) AppleWebKit/537.36',
				'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
				'Origin: https://m.kuaidi100.com',
				'Sec-Fetch-Site: same-origin',
				'Sec-Fetch-Mode: cors',
				'Sec-Fetch-Dest: empty',
				'Referer: https://m.kuaidi100.com/result.jsp?nu=' . $this->info['id'],
				'Accept-Encoding: gzip, deflate',
				'Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
			],
			'ua' => 'Mozilla/5.0 (Linux; Android 7.1.2; OPPO R11t Build/N6F26Q; wv) AppleWebKit/537.36',
			'refer' => 'https://m.kuaidi100.com/result.jsp?nu=' . $this->info['id']
		]), true);

		if ($response['message'] === 'ok' && isset($response['data'][0])) {
			$textMessage = [];
			foreach ($response['data'] as $item) {
				$textMessage[] = '时间：' . $item['time'] . '-' . $item['ftime'];
				$textMessage[] = '事件：' . $item['context'];
				if (isset($item['local'])) {
					$textMessage[] = '地点：' . $item['local'];
				}
			}
			
			$outputData = [
				'code' => 1,
				'text' => '获取成功',
				'data' => $response['data']
			];

			if ($this->info['type'] === 'text') {
				$this->output(['code' => 1, 'text' => implode("\n", $textMessage)], 'text');
			} else {
				$this->output($outputData, 'json');
			}
		} else {
			$this->output(['code' => -3, 'text' => $response['message'] ?? '查询失败']);
		}
	}

	private function output($data, $type = 'json')
	{
		if ($type === 'text') {
			header('Content-type: text/plain; charset=utf-8');
			echo $data['text'];
		} else {
			header('Content-type: application/json; charset=utf-8');
			echo json_encode($data, JSON_UNESCAPED_UNICODE);
		}
		exit;
	}
}

$request = need::request();
$id = isset($request['id']) ? $request['id'] : false;
$type = isset($request['type']) ? $request['type'] : 'json';
new kuaidi(['id' => $id, 'type' => $type]);
?>