<?php

namespace Inspire_Labs\Alsendo_Connect;

use Alsendo\AlsendoWrapper\Model\Pickup;
use Alsendo\AlsendoWrapper\Model\Cod;
use Alsendo\AlsendoWrapper\Model\Notification;
use Alsendo\AlsendoWrapper\Model\NotificationDetail;
use Alsendo\AlsendoWrapper\Model\Contact;
use Alsendo\AlsendoWrapper\Model\Order\OrderRequest;
use Alsendo\AlsendoWrapper\Model\Shipment;
use DateTimeImmutable;
use Exception;
use Inspire_Labs\Alsendo_Connect\Global_Settings_Integration;
use WP_Error;
use Alsendo\AlsendoWrapper\ApiClientFactory;
use Alsendo\AlsendoWrapper\Model\Address;


if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}


// Wrapper autoload.
require_once __DIR__ . '../../vendor/alsendo-wrapper/vendor/autoload.php';

/**
 * Alsendo_API
 */
class Alsendo_API {

	/**
	 * @var self
	 */
	protected static $instance;

	/**
	 * API_URL
	 */
	const API_URL = 'https://www.apaczka.pl/api/v2/';

	/**
	 * SIGN_ALGORITHM
	 */
	const SIGN_ALGORITHM = 'sha256';

	/**
	 * EXPIRES
	 */
	const EXPIRES = '+20min';


	/**
	 * API TYPE FIELD
	 */
	const API_TYPE_FIELD = 'alsendo_connect_settings_general_apaczka_api_type';

	/**
	 * SECONDS_24H
	 */
	const SECONDS_24H = 86400;

	/**
	 * SERVICE_STRUCTURE_CACHE_OPTION
	 */
	const SERVICE_STRUCTURE_CACHE_OPTION = Plugin::APP_PREFIX . '_SC_CACHE';

	/**
	 * SERVICE_STRUCTURE_CACHE_TIMESTAMP_OPTION
	 */
	const SERVICE_STRUCTURE_CACHE_TIMESTAMP_OPTION = Plugin::APP_PREFIX . '_SC_CACHE_TIMESTAMP';


	/**
	 * App id
	 *
	 * @var false|mixed|null
	 */
	public $app_id;

	/**
	 *  App secret
	 *
	 * @var false|mixed|null
	 */
	public $app_secret;

	/**
	 * Cache period
	 *
	 * @var float|int
	 */
	protected $cache_period = DAY_IN_SECONDS;


	/**
	 * API type
	 *
	 * @var false|mixed|null
	 */
	private $api_type;


	/**
	 * Contstructor
	 */
	public function __construct() {
		$this->app_id     = trim( Plugin::get_option( 'app_id' ) );
		$this->app_secret = trim( Plugin::get_option( 'app_secret' ) );
		$this->api_type   = alsendo_connect()->get_main_settings_api();
	}

	/**
	 * WP remote post
	 *
	 * @param string $route $route.
	 * @param mixed  $data $data.
	 *
	 * @throws Exception Exception.
	 */
	private function wp_remote_post( $route, $data = null ) {

		$result = wp_remote_post(
			self::API_URL . $route,
			array(
				'body'      => http_build_query( $this->build_request( $route, $data ) ),
				'method'    => 'POST',
				'sslverify' => true,
				'timeout'   => 30,
			)
		);

		if ( ! $result || $result instanceof WP_Error ) {
			$error_msg = $result->get_error_message();
			throw new Exception( esc_html( $error_msg ) );
		}

		return wp_remote_retrieve_body( $result );
	}

	/**
	 * Request
	 *
	 * @param string $route $route.
	 * @param mixed  $data $data.
	 *
	 * @return mixed
	 */
	private function request( $route, $data = null ) {

		try {

			$response = $this->wp_remote_post( $route . '/', $data );

		} catch ( Exception $e ) {

			if ( function_exists( 'wc_get_logger' ) ) {
				$logger = wc_get_logger();

				$logger->log(
					'debug',
					'SOME_ERROR_ON_REQUEST',
					array(
						'source'       => 'alsendo-apaczka-api-request-log',
						'route'        => $route,
						'error'        => $e->getMessage(),
						'request_data' => $data,
					)
				);
			}

			( new Alerts() )->add_error(
				$this->prepare_error_message(
					sanitize_text_field( $route ),
					$e->getMessage()
				),
				$route
			);

			return false;
		}

		$response_decoded = json_decode( $response );

		if ( ! is_object( $response_decoded )
			|| ! property_exists( $response_decoded, 'status' )
			|| ! property_exists( $response_decoded, 'message' )
			|| ! property_exists( $response_decoded, 'response' ) ) {

			$debug_extra_info = '';

			( new Alerts() )->add_error(
				$this->prepare_error_message(
					$route,
					'Response cannot be decoded' . $debug_extra_info
				),
				$route
			);

			return 'Some error is occured when we try to get label.';
		}

		$status = (int) $response_decoded->status;

		if ( 200 !== $status ) {

			if ( function_exists( 'wc_get_logger' ) ) {
				$logger = wc_get_logger();
				$logger->log(
					'debug',
					'SOME_ERROR_ON_REQUEST: status code is not 200',
					array(
						'source'       => 'alsendo-apaczka-api-request-log',
						'status'       => $status,
						'route'        => $route,
						'error'        => $response_decoded->message,
						'request_data' => $data,
					)
				);
			}

			if ( function_exists( 'wc_get_logger' ) ) {
				$logger = wc_get_logger();

				$logger->log(
					'debug',
					'SOME_ERROR_ON_REQUEST',
					array(
						'source'             => 'apaczka-api-status-log',
						'additional_context' => array(
							'expires_value_min'       => self::EXPIRES,
							'expires_value_timestamp' => strtotime( self::EXPIRES ),
							'current_timestamp'       => time(),
							'timestamp_diff'          => ( strtotime( self::EXPIRES ) - time() ),
						),
						'route'              => $route,
						'error'              => $response_decoded->message,
						'request_data'       => $data,
					)
				);
			}

			return $response_decoded;
		}

		return $response_decoded->response;
	}

	/**
	 * Prepare error message
	 *
	 * @param string $route $route.
	 * @param string $message $message.
	 *
	 * @return string
	 */
	public function prepare_error_message( $route, $message ): string {
		return sprintf(
			'[%s] [route: %s] %s',
			gmdate( 'Y-m-d H:i:s' ) . ' UTC',
			$route,
			$message
		);
	}


	/**
	 * Build request
	 *
	 * @param string $route $route.
	 * @param array  $data $data.
	 * @return array
	 */
	private function build_request( $route, $data = array() ) {
		$data    = wp_json_encode( $data );
		$expires = strtotime( self::EXPIRES );

		$system = 'WooCommerce APIv2 iLabs';

		return array(
			'app_id'    => $this->app_id,
			'request'   => $data,
			'expires'   => $expires,
			'signature' => $this->getSignature(
				$this->stringToSign(
					$this->app_id,
					$route,
					$data,
					$expires
				),
				$this->app_secret
			),
		);
	}



	/**
	 * Get order
	 *
	 * @param mixed $id $id.
	 * @return false|mixed
	 */
	public function apaczka_get_order_direct( $id ) {
		return $this->request( 'order/' . $id );
	}


	/**
	 * Get order
	 *
	 * @param mixed $id $id.
	 * @return false|mixed
	 */
	public function get_order_details_apaczka( $id ) {

		$response = null;

		if ( 'apaczka' === $this->api_type ) {

			$api_type_wrapper = null;

			$api_type = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return false;
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			try {
				$response = $api_client->getOrder( $id );
			} catch ( Exception $e ) {
				$response['error'] = $e->getMessage();
			}
		}

		return $response;
	}



	/**
	 * Retrieves waybill from Apaczka API.
	 *
	 * Creates an appropriate Apaczka API client based on environment settings
	 * and fetches the waybill for the specified shipment ID. Handles API errors
	 * and exceptions.
	 *
	 * @param string $id           The Apaczka shipment ID to get waybill for.
	 * @param int    $wc_order_id  The WooCommerce order ID (unused in current implementation).
	 *
	 * @return mixed Waybill data on success, array with error message on failure, or false if invalid API type.
	 */
	public function waybill( $id ) {

		$response = null;

		if ( 'apaczka' === $this->api_type ) {

			$api_type_wrapper = null;

			$api_type = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return false;
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			// $id = 602797138500704122133602;

			try {
				$response = $api_client->getWayBill( $id );
			} catch ( Exception $e ) {
				$response['error'] = $e->getMessage();
			}
		}

		return $response;
	}

	/**
	 * Pickup hours
	 *
	 * @param mixed $postal_code $postal_code.
	 * @param mixed $service_id $service_id.
	 * @return false|mixed
	 */
	public function pickup_hours( $postal_code, $service_id = false ) {
		return $this->request(
			__FUNCTION__,
			array(
				'postal_code' => $postal_code,
				'service_id'  => $service_id,
			)
		);
	}


	/**
	 * Order valuation
	 *
	 * @param $order
	 * @return false|mixed
	 */
	public function apaczka_order_valuation_direct( $order ) {
		return $this->request(
			'order_valuation',
			array(
				'order' => $order,
			)
		);
	}


	/**
	 * Order valuation
	 *
	 * @param array $order $order.
	 * @return false|mixed
	 */
	public function order_valuation( $order ) {

		if ( 'ecolet' === $this->api_type ) {
			$ecolet   = new Ecolet();
			$response = $ecolet->order_valuation( $order );
		}

		if ( 'apaczka' === $this->api_type ) {

			//            $res = $this->apaczka_order_valuation_direct( $order );
			//            \wc_get_logger()->debug( 'DIRECT: ', array( 'source' => 'order_valuation_direct' ) );
			//            \wc_get_logger()->debug( print_r( $res, true), array( 'source' => 'order_valuation_direct' ) );

			$api_type_wrapper = null;

			$api_type = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return false;
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			try {

				$order_request = $this->prepare_apaczka_order_valuation_request( $order );

				$response = $api_client->getOrderValuation( $order_request );

			} catch ( Exception $e ) {
				$response['error'] = $e->getMessage();
			}
		}

		if ( 'zaslat' === $this->api_type ) {
			$zaslat   = new Zaslat();
			$response = $zaslat->get_rates( $order );
		}

		return $response;
	}


	/**
	 * Send order
	 *
	 * @param array $order $order.
	 * @return false|mixed
	 */
	public function order_send( $order ) {

		if ( 'ecolet' === $this->api_type ) {
			$ecolet   = new Ecolet();
			$response = $ecolet->send_order( $order );
		}

		if ( 'zaslat' === $this->api_type ) {
			$zaslat   = new Zaslat();
			$response = $zaslat->create_shipment( $order );
		}

		if ( 'apaczka' === $this->api_type ) {

			$api_type_wrapper = null;

			$api_type = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return false;
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			try {

				$order_request = $this->prepare_apaczka_order_valuation_request( $order );
				$response      = $api_client->sendOrder( $order_request );

			} catch ( Exception $e ) {
				$response['error'] = str_replace( "\\u2019", "'", $e->getMessage() );

			}
		}

		return $response;
	}



	/**
	 * Cancel order
	 *
	 * @param mixed $id $id.
	 * @return false|mixed
	 */
	public function cancel_order( $id ) {

		$response = null;

		if ( 'apaczka' === $this->api_type ) {

			$api_type_wrapper = null;

			$api_type = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return false;
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			try {

				$response = $api_client->cancelOrder( $id );

				$response['cancelled'] = 'ok';

			} catch ( Exception $e ) {
				$response['error'] = $e->getMessage();
			}
		}

		return $response;
	}


	/**
	 * Turn in
	 *
	 * @param array $order_ids $order_ids.
	 * @return false|mixed
	 */
	public function turn_in( $order_ids = array() ) {

		$response = null;

		$api_type_wrapper = null;

		$api_type = get_option( self::API_TYPE_FIELD );
		if ( 'prod' === $api_type ) {
			$api_type_wrapper = ApiClientFactory::APACZKA;
		} elseif ( 'stage' === $api_type ) {
			$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
		}

		if ( ! $api_type_wrapper ) {
			return false;
		}

		$api_client = ( new ApiClientFactory() )->create(
			$api_type_wrapper,
			array(
				'app_id'     => $this->app_id,
				'app_secret' => $this->app_secret,
			)
		);

		try {

			$response = $api_client->getTurnInList( $order_ids );

		} catch ( Exception $e ) {
			$response['exception'] = $e->getMessage();
		}

		return $response;
	}


	/**
	 * Points
	 *
	 * @param mixed $type $type.
	 * @return false|mixed
	 */
	public function points( $type = null ) {
		return $this->request( __FUNCTION__ . '/' . $type . '/' );
	}



	/**
	 * Generates HMAC signature for authentication string.
	 *
	 * Creates a hash-based message authentication code using the configured
	 * signing algorithm and provided secret key.
	 *
	 * @param string $string The string to be signed.
	 * @param string $key The secret key for signing.
	 * @return string The generated HMAC signature.
	 */
	public function getSignature( $string, $key ) {
		return hash_hmac( self::SIGN_ALGORITHM, $string, $key );
	}


	/**
	 * Creates a string to be signed for authentication purposes.
	 *
	 * Concatenates app ID, route, data, and expiration timestamp with colons
	 * to form a signature string for API authentication.
	 *
	 * @param string $appId The application identifier.
	 * @param string $route The API route or endpoint.
	 * @param string $data The request data.
	 * @param string $expires The expiration timestamp.
	 * @return string The formatted string ready for signing.
	 */
	public function stringToSign( $appId, $route, $data, $expires ) {
		return sprintf( '%s:%s:%s:%s', $appId, $route, $data, $expires );
	}


	/**
	 * Translate error
	 *
	 * @param string $error $error.
	 * @return mixed
	 */
	public function translate_error( $error ) {
		$errors = array(
			'receiver_email' => esc_html__(
				'Recipient e-mail',
				'alsendo-connect'
			),
		);

		if ( isset( $errors[ $error ] ) ) {
			return $errors[ $error ];
		}

		return $error;
	}



	/**
	 * Prepares an Apaczka order request object from order data array.
	 *
	 * Transforms the order data into an OrderRequest object with all necessary
	 * components including addresses, shipment details, COD information, pickup
	 * settings, notifications, and parcel specifications for the Apaczka API.
	 *
	 * @param array $data The order data array containing service ID, addresses, shipment, pickup, and COD information.
	 *
	 * @return OrderRequest The prepared order request object ready for API submission.
	 */
	private function prepare_apaczka_order_valuation_request( $data ) {

		$order            = new OrderRequest();
		$order->serviceId = ! empty( $data['service_id'] ) ? $data['service_id'] : 0;

		$order->address = new Address(
			new Contact(
				$data['address']['sender']['country_code'],
				$data['address']['sender']['name'],
				$data['address']['sender']['line1'],
				$data['address']['sender']['line2'],
				$data['address']['sender']['postal_code'],
				'',
				$data['address']['sender']['city'],
				$data['address']['sender']['is_residential'],
				$data['address']['sender']['contact_person'],
				$data['address']['sender']['email'],
				$data['address']['sender']['phone'],
				$data['address']['sender']['foreign_address_id'],
				0,
				'',
				'',
				'',
				'',
				'',
				'',
				0,
				0,
			),
			new Contact(
				$data['address']['receiver']['country_code'],
				$data['address']['receiver']['name'],
				$data['address']['receiver']['line1'],
				$data['address']['receiver']['line2'],
				$data['address']['receiver']['postal_code'],
				'',
				$data['address']['receiver']['city'],
				$data['address']['receiver']['is_residential'],
				$data['address']['receiver']['contact_person'],
				$data['address']['receiver']['email'],
				$data['address']['receiver']['phone'],
				$data['address']['receiver']['foreign_address_id'],
				0,
				'',
				'',
				'',
				'',
				'',
				'',
				0,
				0,
			),
		);
		$order->option  = array(
			/*
			'31'  => 0, // powiadomienie sms.
			'11 ' => 0, // rod.
			'19'  => 0, // dostawa w sobotę.
			'25'  => 0, // dostawa w godzinach.
			'58'  => 0, // ostrożnie.
			*/
		);
		$order->notification  = new Notification(
			new NotificationDetail(
				0,
				0,
				0
			),
			new NotificationDetail(
				0,
				0,
				0
			),
			new NotificationDetail(
				0,
				0,
				0
			),
			new NotificationDetail(
				0,
				0,
				0
			),
		);
		$order->shipmentValue = (int) ( ( (float) $data['shipment_value'] ) * 100 );

		$order->cod              = new Cod();
		$order->cod->amount      = ! empty( $data['cod']['amount'] ) ? $data['cod']['amount'] : 0;
		$order->cod->bankaccount = ! empty( $data['cod']['bankaccount'] ) ? $data['cod']['bankaccount'] : '';

		$order->pickup            = new Pickup();
		$order->pickup->type      = $data['pickup']['type'];
		$order->pickup->date      = ( new DateTimeImmutable( $data['pickup']['date'] ) )->format( 'Y-m-d' );
		$order->pickup->hoursFrom = $data['pickup']['hours_from'];
		$order->pickup->hoursTo   = $data['pickup']['hours_to'];

		foreach ( $data['shipment'] as $parcel ) {
			$shipment                   = new Shipment();
			$shipment->dimension1       = (int) $parcel['dimension1'];
			$shipment->dimension2       = (int) $parcel['dimension2'];
			$shipment->dimension3       = (int) $parcel['dimension3'];
			$shipment->weight           = $parcel['weight'];
			$shipment->isNstd           = $parcel['is_nstd'];
			$shipment->shipmentTypeCode = $parcel['shipment_type_code'];
			$order->shipment[]          = $shipment;
		}

		$order->comment = $data['comment'];
		$order->content = $data['content'];
		$order->isZebra = 0;

		$current_plugin_version = alsendo_connect()->get_plugin_version();
		//$order->source = 'WooCommerce Alsendo Connect ver:' . $current_plugin_version;
		//$order->source = 'WooCommerce Alsendo Connect';
		//$order->system = 'WooCommerce Alsendo Connect: param in PLUGIN code'; // error: Property not existing system in Alsendo\AlsendoWrapper\Model\Order\OrderRequest

		return $order;
	}


	/**
	 * Retrieves the Apaczka service structure as an array.
	 *
	 * Fetches available Apaczka services and returns them as an associative array
	 * with service IDs as keys and service names as values. Validates API credentials
	 * and handles exceptions by displaying admin notices.
	 *
	 * @return array Associative array of service ID => service name pairs, or empty array on failure.
	 */
	public function get_service_structure_apaczka( $forced = false ): array {

		static $is_request_running = false;
		$services                  = array();

		$api_type = alsendo_connect()->get_main_settings_api();
		if ( 'apaczka' !== $api_type ) {
			return array();
		}

		if ( empty( $this->app_id ) || empty( $this->app_secret ) ) {
			return array();
		}

		$can_update_services = is_admin() && ( current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' ) );
		if ( ! $can_update_services ) {
			$apaczka_services = get_option( self::SERVICE_STRUCTURE_CACHE_OPTION );
			return is_array( $apaczka_services ) ? $apaczka_services : array();
		}

		if ( $forced || ( time() - (int) get_option( self::SERVICE_STRUCTURE_CACHE_TIMESTAMP_OPTION ) > self::SECONDS_24H )
		) {

			if ( $forced ) {
				delete_option( 'apaczka_pl_api_returned_error' );
			}

			$maybe_timeout = get_option( 'apaczka_pl_api_returned_error' );
			$now           = time();
			if ( $maybe_timeout && $maybe_timeout > $now ) {
				return array();
			} else {
				delete_option( 'apaczka_pl_api_returned_error' );
			}

			$apaczka_services = array();
			$api_type_wrapper = null;
			$api_type         = get_option( self::API_TYPE_FIELD );
			if ( 'prod' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA;
			} elseif ( 'stage' === $api_type ) {
				$api_type_wrapper = ApiClientFactory::APACZKA_TEST;
			}

			if ( ! $api_type_wrapper ) {
				return array();
			}

			$api_client = ( new ApiClientFactory() )->create(
				$api_type_wrapper,
				array(
					'app_id'     => $this->app_id,
					'app_secret' => $this->app_secret,
				)
			);

			if ( ! $is_request_running ) {

				$is_request_running = true;

				try {

					$services = $api_client->getServiceStructure();

				} catch ( Exception $e ) {
					$services           = $e->getMessage();
					$is_request_running = false;
				}
			}

			if ( ! is_object( $services ) || ! property_exists( $services, 'services' ) || ! array( $services->services ) || empty( $services->services ) ) {

				$current_timestamp = time();
				$timeout           = $current_timestamp + 300;
				update_option( 'apaczka_pl_api_returned_error', $timeout );

				( new Alerts() )->add_error(
					$this->prepare_error_message(
						__FUNCTION__,
						'Alsendo Connect: service_structure object from Apaczka API cannot be parsed'
					)
				);

				$is_request_running = false;

				return array();
			}

			foreach ( $services->services as $service ) {
				$apaczka_services[ $service->service_id ]['name'] = property_exists( $service, 'name' ) ? $service->name : '';

				if ( property_exists( $service, 'domestic' ) ) {
					if ( '0' === $service->domestic ) {
						if ( false === strpos( $apaczka_services[ $service->service_id ]['name'], 'Zagranica' )
							&&
							false === strpos( $apaczka_services[ $service->service_id ]['name'], 'International' ) ) {
							$apaczka_services[ $service->service_id ]['name'] .= ' ' . esc_html__( 'International', 'alsendo-connect' );
						}
					}
				}

				$apaczka_services[ $service->service_id ]['supplier']       = property_exists( $service, 'supplier' ) ? $service->supplier : '';
				$apaczka_services[ $service->service_id ]['pickup_courier'] = property_exists( $service, 'pickup_courier' ) ? $service->pickup_courier : '';
			}

			update_option( self::SERVICE_STRUCTURE_CACHE_OPTION, $apaczka_services );
			update_option( self::SERVICE_STRUCTURE_CACHE_TIMESTAMP_OPTION, time() );

			( new Alerts() )->clean_errors();

			$is_request_running = false;

		} else {
			$apaczka_services = get_option( self::SERVICE_STRUCTURE_CACHE_OPTION );
		}

		return is_array( $apaczka_services ) ? $apaczka_services : array();
	}
}
