<?php
namespace TeknoTok\AiTranslator\Integrations;

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

use TeknoTok\AiTranslator\Utils\Logger;

/**
 * Manager class to interact with TeknoTok License API.
 */
class LicenseManager {
	/**
	 * Get stored license options.
	 *
	 * @return array
	 */
	public static function get_license_data() {
		return get_option( 'teknotok_ait_license_status', array(
			'license_key' => '',
			'status'      => 'free',
			'expires_at'  => '',
			'last_check'  => 0,
			'error_count' => 0
		) );
	}

	/**
	 * Check if premium capability is authorized (with grace period support).
	 *
	 * @return bool
	 */
	public static function is_premium_active() {
		$license = self::get_license_data();
		$status  = $license['status'] ?? 'inactive';

		if ( 'active' === $status ) {
			$expires_at = $license['expires_at'] ?? '';
			if ( ! empty( $expires_at ) && strtotime( $expires_at ) < time() ) {
				return false;
			}
			return true;
		}

		// Grace period check (48 hours)
		$last_check = (int) ( $license['last_check'] ?? 0 );
		$error_count = (int) ( $license['error_count'] ?? 0 );
		
		if ( $error_count > 0 && $last_check > 0 ) {
			$delta = time() - $last_check;
			if ( $delta < 172800 ) { // 48 hours in seconds
				return true;
			}
		}

		return false;
	}

	/**
	 * Determine whether an inactive premium license should pause premium queue work.
	 *
	 * @return bool True when a saved Pro license exists but is not currently active.
	 */
	public static function has_inactive_premium_license() {
		$license = self::get_license_data();
		$key     = trim( (string) ( $license['license_key'] ?? '' ) );
		$status  = $license['status'] ?? 'inactive';

		if ( '' === $key || in_array( $status, array( 'free', 'inactive' ), true ) ) {
			return false;
		}

		return ! self::is_premium_active();
	}

	/**
	 * Register hook actions.
	 *
	 * @return void
	 */
	public function init_hooks() {
		add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_plugin_updates' ) );
		add_filter( 'plugins_api', array( $this, 'plugin_api_info' ), 20, 3 );
	}

	/**
	 * Request License API helper.
	 *
	 * @param string $endpoint Endpoint slug (e.g. 'activate', 'check', 'deactivate').
	 * @param array  $body     Optional extra payload.
	 * @return array|\WP_Error Response object array or WP_Error.
	 */
	private function make_request( $endpoint, $body = array() ) {
		$license = self::get_license_data();
		$key     = $body['license_key'] ?? ( $license['license_key'] ?? '' );

		// Local mock response for test licenses
		if ( 0 === strpos( $key, 'TEKNOTOK-TEST-' ) ) {
			$mock_body = array(
				'success'    => true,
				'status'     => 'active',
				'message'    => 'License active (Test Mode).',
				'expires_at' => date( 'c', strtotime( '+1 year' ) ),
			);
			return array(
				'response' => array( 'code' => 200 ),
				'body'     => json_encode( $mock_body ),
			);
		}

		$payload = array(
			'license_key'    => $key,
			'product_slug'   => TEKNOTOK_AIT_PRODUCT_SLUG,
			'site_url'       => get_site_url(),
			'plugin_version' => TEKNOTOK_AIT_VERSION,
		);

		$url = TEKNOTOK_AIT_LICENSE_API . $endpoint;

		if ( self::can_use_local_gateway() ) {
			$response = self::request_local_gateway( $endpoint, $payload );
			if ( $response ) {
				return $response;
			}
		}

		$response = wp_remote_post(
			$url,
			array(
				'body'    => $payload,
				'timeout' => 15,
			)
		);

		return $response;
	}

	/**
	 * Check whether the License Manager REST gateway is on this WordPress install.
	 *
	 * @return bool True when local REST dispatch is available.
	 */
	private static function can_use_local_gateway() {
		if ( ! class_exists( '\WP_REST_Request' ) || ! function_exists( 'rest_do_request' ) ) {
			return false;
		}

		$gateway = wp_parse_url( TEKNOTOK_AIT_GATEWAY_BASE_URL );
		$home    = wp_parse_url( home_url() );

		if ( empty( $gateway['host'] ) || empty( $home['host'] ) || strtolower( $gateway['host'] ) !== strtolower( $home['host'] ) ) {
			return false;
		}

		$gateway_port = isset( $gateway['port'] ) ? (int) $gateway['port'] : null;
		$home_port    = isset( $home['port'] ) ? (int) $home['port'] : null;

		return $gateway_port === $home_port;
	}

	/**
	 * Dispatch a same-site gateway request internally to avoid loopback timeouts.
	 *
	 * @param string $endpoint Endpoint slug.
	 * @param array  $payload  Request payload.
	 * @return array|null HTTP-like response, or null when dispatch is unavailable.
	 */
	private static function request_local_gateway( $endpoint, $payload ) {
		$request = new \WP_REST_Request( 'POST', '/teknotok-license/v1/' . sanitize_key( $endpoint ) );

		foreach ( $payload as $key => $value ) {
			$request->set_param( $key, $value );
		}

		$response = rest_do_request( $request );
		if ( ! $response instanceof \WP_REST_Response ) {
			return null;
		}

		return array(
			'response' => array( 'code' => $response->get_status() ),
			'body'     => wp_json_encode( $response->get_data() ),
		);
	}

	/**
	 * Activate a license key.
	 *
	 * @param string $key License Key.
	 * @return bool|\WP_Error True on success, WP_Error on failure.
	 */
	public function activate( $key ) {
		if ( empty( $key ) ) {
			return new \WP_Error( 'missing_key', __( 'Please enter a license key.', 'teknotok-ai-translator-pro' ) );
		}

		$response = $this->make_request( 'activate', array( 'license_key' => $key ) );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 !== $code ) {
			$msg = $body['message'] ?? __( 'Activation failed. Please check your key.', 'teknotok-ai-translator-pro' );
			return new \WP_Error( 'activation_error', $msg );
		}

		$expires_at = $body['expires_at'] ?? '';

		$data = array(
			'license_key' => $key,
			'status'      => 'active',
			'expires_at'  => $expires_at,
			'last_check'  => time(),
			'error_count' => 0
		);

		update_option( 'teknotok_ait_license_status', $data, false );
		return true;
	}

	/**
	 * Deactivate the currently active license key.
	 *
	 * @return bool|\WP_Error True on success, WP_Error on failure.
	 */
	public function deactivate() {
		$license = self::get_license_data();
		$key = $license['license_key'] ?? '';

		if ( empty( $key ) ) {
			return true;
		}

		$response = $this->make_request( 'deactivate' );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 !== $code ) {
			$msg = $body['message'] ?? __( 'Deactivation failed.', 'teknotok-ai-translator-pro' );
			return new \WP_Error( 'deactivation_error', $msg );
		}

		$data = array(
			'license_key' => '',
			'status'      => 'free',
			'expires_at'  => '',
			'last_check'  => time(),
			'error_count' => 0
		);

		update_option( 'teknotok_ait_license_status', $data, false );
		return true;
	}

	/**
	 * Perform license validation check.
	 *
	 * @return bool|\WP_Error True on success, WP_Error on failure.
	 */
	public function check() {
		$license = self::get_license_data();
		$key = $license['license_key'] ?? '';

		if ( empty( $key ) ) {
			return new \WP_Error( 'no_key', __( 'No license key entered.', 'teknotok-ai-translator-pro' ) );
		}

		$response = $this->make_request( 'check' );

		if ( is_wp_error( $response ) ) {
			// Increment error count, trigger grace period validation
			$license['error_count'] = (int) ( $license['error_count'] ?? 0 ) + 1;
			update_option( 'teknotok_ait_license_status', $license, false );
			return $response;
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 !== $code ) {
			$license['status']      = 'free';
			$license['error_count'] = 0;
			update_option( 'teknotok_ait_license_status', $license, false );
			$msg = $body['message'] ?? __( 'License is invalid or expired. Switched to Free tier.', 'teknotok-ai-translator-pro' );
			return new \WP_Error( 'check_error', $msg );
		}

		$license['status']      = 'active';
		$license['expires_at']  = $body['expires_at'] ?? '';
		$license['last_check']  = time();
		$license['error_count'] = 0;

		update_option( 'teknotok_ait_license_status', $license, false );
		return true;
	}

	/**
	 * Get free translation usage stats from the central server.
	 *
	 * @return array|\WP_Error
	 */
	public function get_free_usage() {
		$cache = get_transient( 'teknotok_ait_free_usage_cache' );
		if ( false !== $cache ) {
			return $cache;
		}

		$response = $this->make_request( 'free-usage' );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 !== $code ) {
			return new \WP_Error( 'free_usage_error', $body['message'] ?? __( 'Failed to fetch free usage details.', 'teknotok-ai-translator-pro' ) );
		}

		set_transient( 'teknotok_ait_free_usage_cache', $body, 15 );

		return $body;
	}

	/**
	 * Daily cron check callback.
	 *
	 * @return void
	 */
	public function daily_check() {
		$license = self::get_license_data();
		$key = $license['license_key'] ?? '';

		if ( empty( $key ) ) {
			// Unlicensed/Free version: register/ping the server so the admin knows the domain is active
			wp_remote_post(
				TEKNOTOK_AIT_LICENSE_API . 'register-free',
				array(
					'method'      => 'POST',
					'timeout'     => 15,
					'redirection' => 5,
					'httpversion' => '1.0',
					'blocking'    => false,
					'headers'     => array(
						'Content-Type' => 'application/json',
					),
					'body'        => wp_json_encode( array(
						'product_slug' => TEKNOTOK_AIT_PRODUCT_SLUG,
						'site_url'     => get_site_url(),
					) ),
				)
			);
		} else {
			$this->check();
		}
	}

	/**
	 * Check for updates from the licensing server.
	 *
	 * @param object $transient Plugins update transient.
	 * @return object
	 */
	public function check_plugin_updates( $transient ) {
		if ( empty( $transient->checked ) ) {
			return $transient;
		}

		$license = self::get_license_data();
		$key = $license['license_key'] ?? '';

		if ( empty( $key ) ) {
			return $transient;
		}

		// GET update-check
		$url = add_query_arg(
			array(
				'license_key'    => $key,
				'product_slug'   => TEKNOTOK_AIT_PRODUCT_SLUG,
				'site_url'       => get_site_url(),
				'plugin_version' => TEKNOTOK_AIT_VERSION,
			),
			TEKNOTOK_AIT_LICENSE_API . 'update-check'
		);

		$response = wp_remote_get( $url, array( 'timeout' => 15 ) );

		if ( is_wp_error( $response ) ) {
			return $transient;
		}

		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			return $transient;
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( ! empty( $body['new_version'] ) && version_compare( TEKNOTOK_AIT_VERSION, $body['new_version'], '<' ) ) {
			$plugin_file = TEKNOTOK_AIT_BASENAME;
			$item = (object) array(
				'id'            => 'teknotok-ai-translator-pro',
				'slug'          => 'teknotok-ai-translator-pro',
				'new_version'   => $body['new_version'],
				'url'           => 'https://soft.teknotok.com',
				'package'       => $body['package_url'] ?? '',
				'tested'        => $GLOBALS['wp_version'],
				'requires_php'  => '7.4',
			);
			$transient->response[ $plugin_file ] = $item;
		}

		return $transient;
	}

	/**
	 * Inject custom plugin API information.
	 *
	 * @param object|bool $result
	 * @param string      $action
	 * @param object      $args
	 * @return object|bool
	 */
	public function plugin_api_info( $result, $action, $args ) {
		if ( 'plugin_information' !== $action || 'teknotok-ai-translator-pro' !== $args->slug ) {
			return $result;
		}

		$license = self::get_license_data();
		$key = $license['license_key'] ?? '';

		if ( empty( $key ) ) {
			return $result;
		}

		$url = add_query_arg(
			array(
				'license_key'    => $key,
				'product_slug'   => TEKNOTOK_AIT_PRODUCT_SLUG,
				'site_url'       => get_site_url(),
				'plugin_version' => TEKNOTOK_AIT_VERSION,
			),
			TEKNOTOK_AIT_LICENSE_API . 'update-check'
		);

		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) ) {
			return $result;
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		return (object) array(
			'name'          => 'TeknoTok AI Translator Pro',
			'slug'          => 'teknotok-ai-translator-pro',
			'version'       => $body['new_version'] ?? TEKNOTOK_AIT_VERSION,
			'author'        => 'TeknoTok Soft',
			'homepage'      => 'https://soft.teknotok.com',
			'download_link' => $body['package_url'] ?? '',
			'sections'      => array(
				'description' => 'One-click AI translation plugin for WordPress and WooCommerce.',
				'changelog'   => $body['sections']['changelog'] ?? '',
			),
		);
	}
}
