<?php

namespace wp_opieka_globkurier;

class GlobKurierInpost extends GlobKurier
{
	protected $productId = 0;
	protected $label = 'PACZKOMAT';
	
	private function _convert($content)
	{
		if (! mb_check_encoding($content, 'UTF-8')
			|| ! ($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32'))) {
			$content = mb_convert_encoding($content, 'UTF-8');
		}
		
		return $content;
	}
	
	public function getPoints($paramsIn)
	{
		$function = 'points';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		$this->getProductId();
		
		// check if inpost code exist
		$params[ 'id' ]        = strtoupper($this->_convert($_POST[ 'city' ] ?? ''));
		$params[ 'productId' ] = $this->productId;
		
		$response = $this->api()->getResponse($function, $token, $params, $method);
		
		if ($response[ 'code' ] != 200 || empty($response[ 'data' ])) {
			$params = [];
			
			$params[ 'productId' ]                     = $this->productId;
			$params[ 'isCashOnDeliveryAddonSelected' ] = 'false';
			$params[ 'city' ]                          = $this->_convert($_POST[ 'city' ] ?? '');
			
			$response = $this->api()->getResponse($function, $token, $params, $method);
		}
		
		$points = apply_filters('globkurier_inpost_points', $response[ 'data' ]);
		
		$pointsResponse = [];
		
		if ($response[ 'code' ] == 200 && count($response[ 'data' ]) > 0) {
			foreach ($points as $point) {
				$pointsResponse[] = [
					'id'           => $point[ 'id' ],
					'label'        => $point[ 'city' ].', '.$point[ 'address' ].' ['.$point[ 'id' ].']',
					'value'        => $point[ 'city' ].', '.$point[ 'address' ].' ['.$point[ 'id' ].']',
					'latitude'     => $point[ 'latitude' ],
					'longitude'    => $point[ 'longitude' ],
					'city'         => $point [ 'city' ],
					'address'      => $point [ 'address' ],
					'openingHours' => $point [ 'openingHours' ],
				];
			}
		} else {
			$pointsResponse[] = [
				'id'           => ' ',
				'value'        => ' ',
				'label'        => __('Brak wyników', 'globkurier'),
				'latitude'     => 0,
				'longitude'    => 0,
				'city'         => ' ',
				'address'      => ' ',
				'openingHours' => ' ',
			];
		}
		
		return json_encode($pointsResponse);
		
		do_action('globkurier_after_get_inpost_points', $response, $points, $pointsResponse);
		
		return $points;
	}
	
	public function getPointsSelect2($paramsIn)
	{
		$function = 'points';
		$method   = 'GET';
		
		$allPoints = $this->getAllPoints();
		$search    = strtolower($paramsIn[ 'city' ] ?? '');
		
		$points = [];
		foreach ($allPoints as $point) {
			if (
				mb_stripos($point[ 'id' ], $search) !== false
				|| mb_stripos($point[ 'city' ], $search) !== false
			) {
				$points[] = $point;
			}
		}
		$pointsResponse = apply_filters('globkurier_inpost_points', $points);
		
		do_action('globkurier_after_get_inpost_points', $points, $pointsResponse);
		
		return json_encode($pointsResponse);
	}
	
	public function getAllPoints($update = false)
	{
		$inpostPointsValidTime = apply_filters('globkurier_inpost_points_valid_time',
			get_option('gkStoreInpostPointsValidTime', DAY_IN_SECONDS)
		);
		
		$inpostPointsValidTimeChecker = apply_filters('globkurier_inpost_points_valid_time_checker_is_active',
			get_option('globkurier')[ 'inpost_points_valid_time_checker_is_active' ] ?? false
		);
		
		if ($inpostPointsValidTimeChecker && $inpostPointsValidTime < $this->getTimeSincePointsDownloaded()) {
			$update = true;
		}
		
		$storeInpostPointsInFile = apply_filters('globkurier_store_inpost_points_in_file',
			get_option('globkurier')[ 'storeInpostPointsInFile' ] ?? false
		);
		
		$oldPoints = null;
		if (! $update) {
			if ($storeInpostPointsInFile) {
				$oldPoints = $this->loadPointsFromFile();
			} else {
				$oldPoints = get_option('gkInPostPoints', null);
			}
		}
		
		if (! $update && $oldPoints !== null) {
			return $oldPoints;
		}
		
		$function = 'points';
		$method   = 'GET';

//		$token = $this->api()->getToken();
		
		$this->getProductId();
		
		$params = [];
		
		$params[ 'productId' ]                     = $this->productId;
		$params[ 'isCashOnDeliveryAddonSelected' ] = 'false';
		
		$response = $this->api()->getResponse($function, null, $params, $method);
		
		$points = apply_filters('globkurier_inpost_points', $response[ 'data' ]);
		
		$pointsResponse = [];
		
		if ($response[ 'code' ] == 200 && count($response[ 'data' ]) > 0) {
			foreach ($points as $point) {
				$pointsResponse[] = [
					'id'           => $point[ 'id' ],
					'label'        => $point[ 'city' ].', '.$point[ 'address' ].' ['.$point[ 'id' ].']',
					'value'        => $point[ 'city' ].', '.$point[ 'address' ].' ['.$point[ 'id' ].']',
					'latitude'     => $point[ 'latitude' ],
					'longitude'    => $point[ 'longitude' ],
					'city'         => $point[ 'city' ],
					'address'      => $point[ 'address' ],
					'openingHours' => $point[ 'openingHours' ],
				];
			}
		}
		
		if (count($pointsResponse) == 0) {
			return;
//			wp_send_json_error('Brak paczkomatów do zapisu');
		}
		
		if ($storeInpostPointsInFile) {
			$filePath = apply_filters('globkurier_store_inpost_points_file_path',
				__DIR__.'/inpost.json'
			);
			
			try{
				$inpostFileJsonContent = apply_filters('globkurier_inpost_file_json_content',
					json_encode($pointsResponse, JSON_THROW_ON_ERROR)
				);
				
				file_put_contents($filePath, $inpostFileJsonContent);
				delete_option('gkInPostPoints');
			} catch (\JsonException $e){
				return;
//				wp_send_json_error('Błąd podczas zapisu do pliku');
			}
		} else {
			update_option('gkInPostPoints', $pointsResponse);
		}
		
		update_option('gkInPostPointsDownloadedAt', time());
		
		return $pointsResponse;
	}
	
	public function loadPointsFromFile($raw = false, $updated = false)
	{
		$filePath = apply_filters('globkurier_store_inpost_points_file_path',
			__DIR__.'/inpost.json'
		);
		
		if (! file_exists($filePath)) {
			if ($updated) {
				return null;
			} else {
				$this->update();
				
				return $this->loadPointsFromFile($raw, true);
			}
		}
		
		$inpostFileJsonContent = apply_filters(
			'globkurier_store_inpost_points_json_content',
			file_get_contents($filePath)
		);
		
		return $raw
			? $inpostFileJsonContent
			: json_decode($inpostFileJsonContent, true, 512, JSON_THROW_ON_ERROR);
	}
	
	public function getTimeSincePointsDownloaded()
	{
		$downloadedAt = get_option('gkInPostPointsDownloadedAt', 0);
		
		return absint(time() - $downloadedAt);
	}
	
	public function update()
	{
		$this->getAllPoints(true);
	}
	
	public function getProductId()
	{
		global $globKurier;
		
		$products = $globKurier->product()->get([
			'height'                        => '1',
			'width'                         => '1',
			'length'                        => '1',
			'weight'                        => '1',
			'quantity'                      => '1',
			'receiverCountryId'             => '1',
			'receiverPostCode'              => '87-100',
			'senderCountryId'               => '1',
			'senderPostCode'                => '87-100',
			'globkurier_show_all_providers' => 'true',
			'globkurier_is_pickup_active'   => 'true',
			'globkurier_pickup_type'        => '',
		], false);
		
		foreach ($products[ 'results' ] as $product) {
			if ($product[ 'carrierName' ] === 'inPost-Paczkomaty') {
				$this->productId = $product[ 'id' ];
			}
		}
	}
}