<?php
/**
 * Main Chatbot AI plugin coordinator.
 *
 * @package Replyan_AI
 */

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

final class Replyan_AI_Plugin {
	private static $instance = null;

	private $admin;
	private $frontend;
	private $ajax;
	private $dashboard;

	public static function instance(): Replyan_AI_Plugin {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		$this->admin     = new Replyan_AI_Admin();
		$this->frontend  = new Replyan_AI_Frontend();
		$this->ajax      = new Replyan_AI_Ajax();
		$this->dashboard = new Replyan_AI_Dashboard();

		$this->register_hooks();
	}

	private function register_hooks(): void {
		$this->admin->register_hooks();
		$this->frontend->register_hooks();
		$this->ajax->register_hooks();
		$this->dashboard->register_hooks();
		Replyan_AI_Intent_Engine::instance()->register_hooks();

		if ( class_exists( 'Replyan_AI_Context_Awareness' ) ) {
			( new Replyan_AI_Context_Awareness() )->register_hooks();
		}

		if ( class_exists( 'Replyan_AI_Optimization_Instruction' ) ) {
			( new Replyan_AI_Optimization_Instruction() )->register_hooks();
		}

		if ( file_exists( REPLYAN_AI_DIR . 'includes/premium/index.php' ) ) {
			require_once REPLYAN_AI_DIR . 'includes/premium/index.php';
			if ( function_exists( 'replyan_ai_premium_register_hooks' ) ) {
				replyan_ai_premium_register_hooks();
			}
		}

		add_filter( 'script_loader_tag', array( $this, 'add_module_type_to_scripts' ), 10, 3 );
		add_action( 'admin_init', array( $this, 'maybe_create_tables' ) );
		add_action( 'replyan_ai_daily_license_check', array( $this, 'daily_license_check' ) );
	}

	public function daily_license_check(): void {
		$license_key = get_option( 'replyan_ai_license_key', '' );
		if ( empty( $license_key ) ) {
			return;
		}

		$response = wp_remote_post(
			REPLYAN_AI_SAAS_URL . '/licenses/check-subscription',
			array(
				'timeout' => 15,
				'headers' => array(
					'Content-Type' => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'site_url' => site_url(),
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			Replyan_AI_Logs::log( 'Daily license check failed: ' . $response->get_error_message() );
			return;
		}

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

		if ( (200 === $status_code || 201 === $status_code) && isset( $data['data'] ) ) {
			$license_data = $data['data'];
			
			if ( isset( $license_data['status'] ) ) {
				update_option( 'replyan_ai_license_status', sanitize_text_field( $license_data['status'] ) );
			}
			
			if ( isset( $license_data['expires_at'] ) && null !== $license_data['expires_at'] ) {
				update_option( 'replyan_ai_license_expires_at', sanitize_text_field( $license_data['expires_at'] ) );
			}
			
			update_option( 'replyan_ai_license_checked_at', time() );
			
		} else {
			Replyan_AI_Logs::log( 'Daily license check returned unexpected response (' . $status_code . '): ' . $body );
		}
	}

	public function maybe_create_tables(): void {
		$target_db_version = defined( 'REPLYAN_AI_DB_VERSION' ) ? REPLYAN_AI_DB_VERSION : '1.7';
		if ( get_option( 'replyan_ai_db_version', '' ) !== $target_db_version ) {
			Replyan_AI_DB::create_tables();
			
			if ( class_exists( 'Replyan_AI_Context_Awareness_DB' ) ) {
				Replyan_AI_Context_Awareness_DB::create_table();
			}

			if ( function_exists( 'replyan_ai_premium_create_tables' ) ) {
				replyan_ai_premium_create_tables();
			}
			
			add_option( 'replyan_ai_license_key', '' );
			add_option( 'replyan_ai_license_status', 'inactive' );
			add_option( 'replyan_ai_license_plan', 'free' );
			add_option( 'replyan_ai_license_features', array() );
			add_option( 'replyan_ai_license_checked_at', 0 );
			add_option( 'replyan_ai_license_expires_at', 0 );
			
			update_option( 'replyan_ai_db_version', $target_db_version, false );
		}
	}

	public function add_module_type_to_scripts( string $tag, string $handle, string $src ): string {
		if ( in_array( $handle, array( 'replyan-ai-frontend', 'replyan-ai-admin' ), true ) ) {
			if ( false === strpos( $tag, 'type="module"' ) ) {
				$tag = str_replace( '<script ', '<script type="module" ', $tag );
			}
		}

		return $tag;
	}
}
