<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

if ( ! defined( 'TRUEBE_LICENSE_ENDPOINT' ) ) {
	define( 'TRUEBE_LICENSE_ENDPOINT', 'https://truebe.io/api/connect/verify' );
}

class Truebe_License {

	const STATUS_OPTION = 'truebe_license_status';
	const CRON_HOOK     = 'truebe_license_daily_ping';

	public static function init() {
		add_action( self::CRON_HOOK, array( __CLASS__, 'ping' ) );
		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time() + 300, 'daily', self::CRON_HOOK );
		}
	}

	public static function is_valid() {
		$status = get_option( self::STATUS_OPTION, array() );
		if ( empty( $status ) || ! isset( $status['state'] ) ) {
			return true; // not yet verified — fail open
		}
		if ( 'invalid' === $status['state'] ) {
			return false;
		}
		return true;
	}

	public static function status_label() {
		$status = get_option( self::STATUS_OPTION, array() );
		if ( empty( $status['state'] ) ) { return __( 'Not verified', 'truebe-fact-based-ai-chatbot' ); }
		switch ( $status['state'] ) {
			case 'valid':       return __( 'Active', 'truebe-fact-based-ai-chatbot' );
			case 'invalid':     return __( 'Invalid license', 'truebe-fact-based-ai-chatbot' );
			case 'unreachable': return __( 'Could not reach truebe.io', 'truebe-fact-based-ai-chatbot' );
			default:            return __( 'Unknown', 'truebe-fact-based-ai-chatbot' );
		}
	}

	public static function ping() {
		$token = '';
		if ( class_exists( 'Truebe_Setup' ) ) {
			$token = Truebe_Setup::get_permission_token();
		}

		// No token yet — not connected, stay fail-open.
		if ( '' === $token ) {
			update_option( self::STATUS_OPTION, array( 'state' => 'valid', 'checked' => time(), 'note' => 'no token' ) );
			return;
		}

		$resp = wp_remote_post( TRUEBE_LICENSE_ENDPOINT, array(
			'timeout' => 15,
			'body'    => array(
				'permission_token' => $token,
				'site'             => home_url(),
				'version'          => defined( 'TRUEBE_VERSION' ) ? TRUEBE_VERSION : '',
			),
		) );

		if ( is_wp_error( $resp ) ) {
			update_option( self::STATUS_OPTION, array( 'state' => 'unreachable', 'checked' => time() ) );
			return;
		}

		$code = (int) wp_remote_retrieve_response_code( $resp );
		if ( 404 === $code || $code >= 500 || 0 === $code ) {
			update_option( self::STATUS_OPTION, array( 'state' => 'unreachable', 'checked' => time(), 'code' => $code ) );
			return;
		}

		$body = json_decode( wp_remote_retrieve_body( $resp ), true );
		if ( is_array( $body ) && isset( $body['valid'] ) ) {
			update_option( self::STATUS_OPTION, array(
				'state'   => $body['valid'] ? 'valid' : 'invalid',
				'checked' => time(),
				'expires' => isset( $body['expires'] ) ? $body['expires'] : '',
			) );
			self::sync_plan( $body );
			return;
		}

		update_option( self::STATUS_OPTION, array( 'state' => 'unreachable', 'checked' => time() ) );
	}

	/**
	 * Sync plan tier and purchased doc packs from a valid verify response.
	 * 'starter' on truebe.io maps to the plugin's 'pro' tier. An invalid
	 * or inactive account drops the site back to free and clears packs.
	 */
private static function sync_plan( $body ) {
		if ( empty( $body['valid'] ) ) {
			update_option( 'truebe_plan', 'free' );
			update_option( 'truebe_doc_packs', 0 );
			if ( isset( $body['doc_limit'] ) ) {
				update_option( 'truebe_doc_limit', max( 0, (int) $body['doc_limit'] ) );
			}
			return;
		}
		$remote = isset( $body['plan'] ) ? (string) $body['plan'] : '';
		$plan   = 'free';
		if ( 'enterprise' === $remote ) {
			$plan = 'enterprise';
		} elseif ( in_array( $remote, array( 'starter', 'pro', 'professional', 'practice' ), true ) ) {
			$plan = 'pro';
		}
		update_option( 'truebe_plan', $plan );
		update_option( 'truebe_doc_packs', isset( $body['doc_packs'] ) ? max( 0, (int) $body['doc_packs'] ) : 0 );
		if ( isset( $body['doc_limit'] ) ) {
			update_option( 'truebe_doc_limit', max( 0, (int) $body['doc_limit'] ) );
		}
	}

	public static function verify_now() {
		self::ping();
		return self::status_label();
	}
}