<?php
/**
 * Plugin activation and subscription management.
 *
 * @package MindWebConcierge
 */

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

require_once __DIR__ . '/mindweco_db.php';
require_once __DIR__ . '/mindweco_config.php';

/**
 *
 * @return array<string,string>
 */
function mindweco_load_config() {
	return array(
		'rag_url'       => MINDWECO_RAG_URL,
		'notebooks_url' => MINDWECO_NOTEBOOKS_URL,
		'stripe_url'    => MINDWECO_STRIPE_URL,
		'prod_id'       => MINDWECO_PROD_ID,
	);
}

/**
 * Sanitize every string value inside a subscription data array.
 *
 * @param  mixed $subscription_data Raw API response.
 * @return mixed Sanitized array, or the original value if not an array.
 */
function mindweco_validate_subscription_status( $subscription_data ) {
	if ( ! is_array( $subscription_data ) || empty( $subscription_data ) ) {
		return $subscription_data;
	}

	return array_map(
		function ( $value ) {
			return is_string( $value ) ? sanitize_text_field( $value ) : $value;
		},
		$subscription_data
	);
}

/**
 * Runs on plugin activation.
 *
 * @see mindweco_plugin_do_activation_setup()
 */
function mindweco_plugin_on_activate() {
	if ( ! get_option( 'mindweco_plugin_guid' ) ) {
		$guid        = wp_generate_uuid4();
		$expiry_date = gmdate( 'Y-m-d H:i:s', strtotime( '+7 days' ) );
		update_option( 'mindweco_plugin_guid', $guid );
		update_option( 'mindweco_plugin_expiry_date', $expiry_date );
	}

	update_option( 'mindweco_plugin_run_setup', true );
	update_option( 'mindweco_plugin_redirect_after_activation', true );
	update_option(
		'mindweco_plugin_agent_role',
		'AI-Powered Customer Support, Documentation, and Knowledge Base Assistant'
	);

	update_option(
		'mindweco_plugin_agent_goal',
		'Help users quickly find information, answer questions based on indexed content, explain products and services, troubleshoot common issues, and provide clear, reliable, and conversational assistance while maintaining a professional user experience.'
	);
}

add_action( 'admin_init', 'mindweco_plugin_do_activation_setup', 1 );

function mindweco_plugin_do_activation_setup() {
	if ( ! get_option( 'mindweco_plugin_run_setup' ) ) {
		return;
	}

	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	delete_option( 'mindweco_plugin_run_setup' );

	$cfg        = mindweco_load_config();
	$stripe_url = esc_url_raw( isset( $cfg['stripe_url'] ) ? $cfg['stripe_url'] : '' );
	$prod_id    = sanitize_text_field( isset( $cfg['prod_id'] ) ? $cfg['prod_id'] : '' );
	$base_url   = esc_url_raw( isset( $cfg['rag_url'] ) ? $cfg['rag_url'] : '' );

	$site_base_url  = get_option( 'siteurl' );
	$title          = $site_base_url;
	$customer_email = wp_get_current_user()->user_email;

	mindweco_items_table();
	mindweco_create_conversations();
	mindweco_create_questions();
	mindweco_create_responses();
	mindweco_products_indexed_table();
	mindweco_media_files_indexed_table();

	$guid = get_option( 'mindweco_plugin_guid', '' );

	$response = mindweco_stripe_add_trial( $stripe_url, $guid, $prod_id, $customer_email, $title, $site_base_url );

	$subscription = isset( $response['subscription'] ) ? $response['subscription'] : array();

	if ( ! empty( $subscription ) ) {
		$subscription = mindweco_validate_subscription_status( $subscription );
	}

	update_option( 'mindweco_trial_response', $subscription );

	$api_guid = isset( $response['subscription']['appGUID'] )
		? sanitize_text_field( $response['subscription']['appGUID'] )
		: $guid;

	if ( $api_guid !== $guid ) {
		update_option( 'mindweco_plugin_guid', $api_guid );
	}

	if ( ! empty( $subscription ) ) {
		update_option( 'mindweco_trial_start',         sanitize_text_field( isset( $subscription['currentPeriodStart'] ) ? $subscription['currentPeriodStart'] : '' ) );
		update_option( 'mindweco_trial_end',           sanitize_text_field( isset( $subscription['currentPeriodEnd'] )  ? $subscription['currentPeriodEnd']  : '' ) );
		update_option( 'mindweco_subscription_id',     sanitize_text_field( isset( $subscription['id'] )                ? $subscription['id']                : '' ) );
		update_option( 'mindweco_customer_email',      sanitize_email( isset( $subscription['customerEmail'] )          ? $subscription['customerEmail']      : '' ) );
		update_option( 'mindweco_subscription_status', sanitize_text_field( isset( $subscription['status'] )            ? $subscription['status']            : '' ) );
		update_option( 'mindweco_subscription_type',   sanitize_text_field( isset( $subscription['type'] )              ? $subscription['type']              : '' ) );
	}

	if ( isset( $response['newUserData']['user'] ) ) {
		$user     = $response['newUserData']['user'];
		$indexing = isset( $response['newUserData']['indexing'] ) ? $response['newUserData']['indexing'] : array();
		update_option( 'mindweco_plugin_indexing', $indexing );
		$login_result = mindweco_plugin_api_login( $base_url, $user['email'], $user['password'] );

		$access_token = isset( $login_result['access_token'] ) ? $login_result['access_token']
			: ( isset( $login_result['data']['token'] ) ? $login_result['data']['token']
			: ( isset( $login_result['token'] )         ? $login_result['token']
			: '' ) );

		if ( empty( $access_token ) ) {
			return;
		}

		update_option( 'mindweco_plugin_access_token', mindweco_encrypt_api_key( sanitize_text_field( $access_token ) ) );

		update_option(
			'mindweco_plugin_options',
			array(
				'base_url' => esc_url_raw( $base_url ),
				'username' => sanitize_text_field( $user['email'] ),
				'password' => mindweco_encrypt_api_key( $user['password'] ),
			)
		);
	}

	$raw_token    = get_option( 'mindweco_plugin_access_token', '' );
	$access_token = mindweco_decrypt_api_key( $raw_token );
	if ( ! empty( $access_token ) ) {
		$category    = get_option( 'mindweco_plugin_category', array() );
		$stored_guid = isset( $category['name'] ) ? $category['name'] : '';

		if ( $api_guid !== $stored_guid || empty( $category['id'] ) ) {
			$sitemap_xml = mindweco_get_sitemap_xml();
			$language    = mindweco_get_locale_code();
			

			$new_category = mindweco_plugin_api_create_category(
				$base_url,
				$access_token,
				$api_guid,
				isset( $response['newUserData']['indexing']['id'] ) ? $response['newUserData']['indexing']['id'] : null,
				$sitemap_xml,
				$language,
				0
			);

			if ( isset( $new_category['category_id'] ) ) {
				update_option(
					'mindweco_plugin_category',
					array(
						'id'   => absint( $new_category['category_id'] ),
						'name' => sanitize_text_field( $api_guid ),
					)
				);

				if ( isset( $new_category['summary'] ) ) {
					update_option( 'mindweco_summary', sanitize_textarea_field( $new_category['summary'] ) );
				}
			}
		}
	}
}


add_action( 'admin_init', 'mindweco_plugin_do_activation_redirect' );

function mindweco_plugin_do_activation_redirect() {
	if ( ! get_option( 'mindweco_plugin_redirect_after_activation' ) ) {
		return;
	}

	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	delete_option( 'mindweco_plugin_redirect_after_activation' );
	wp_safe_redirect( admin_url( 'admin.php?page=mind-web' ) );
	exit;
}

add_action( 'admin_init', 'mindweco_periodic_subscription_check', 5 );

function mindweco_periodic_subscription_check() {
	if ( ! is_admin() ) {
		return;
	}
	if ( get_transient( 'mindweco_subscription_last_check' ) ) {
		return;
	}

	if ( get_transient( 'mindweco_subscription_checking' ) ) {
		return;
	}

	set_transient( 'mindweco_subscription_checking', true, 60 );

	try {
		$app_guid = get_option( 'mindweco_plugin_guid', '' );
		if ( empty( $app_guid ) ) {
			return;
		}

		$stored_subscription = get_option( 'mindweco_trial_response', array() );
		if ( empty( $stored_subscription ) ) {
			return;
		}

		$cfg             = mindweco_load_config();
		$stripe_base_url = esc_url_raw( ! empty( $cfg['stripe_url'] ) ? $cfg['stripe_url'] : get_option( 'mindweco_stripe_base_url', '' ) );

		if ( empty( $stripe_base_url ) ) {
			return;
		}

		$api_response = mindweco_stripe_active_subscription( $stripe_base_url, $app_guid );

		if ( isset( $api_response['error'] ) || empty( $api_response ) ) {
			return;
		}

		$old_status = isset( $stored_subscription['status'] )           ? $stored_subscription['status']           : null;
		$new_status = sanitize_text_field( isset( $api_response['status'] )           ? $api_response['status']           : '' );

		$old_type = isset( $stored_subscription['type'] )               ? $stored_subscription['type']               : null;
		$new_type = sanitize_text_field( isset( $api_response['type'] )               ? $api_response['type']               : '' );

		$old_end = isset( $stored_subscription['currentPeriodEnd'] )    ? $stored_subscription['currentPeriodEnd']    : null;
		$new_end = sanitize_text_field( isset( $api_response['currentPeriodEnd'] )    ? $api_response['currentPeriodEnd']    : '' );

		$needs_update = ( $old_status !== $new_status )
		             || ( $old_type   !== $new_type )
		             || ( $old_end    !== $new_end );

		if ( $needs_update ) {
			$sanitized_response = $api_response;

			array_walk_recursive(
				$sanitized_response,
				function ( &$value ) {
					if ( is_string( $value ) ) {
						$value = sanitize_text_field( $value );
					}
				}
			);

			update_option( 'mindweco_trial_response',      $sanitized_response );
			update_option( 'mindweco_subscription_status', $new_status );
			update_option( 'mindweco_subscription_type',   $new_type );
			update_option( 'mindweco_trial_end',           $new_end );
		}
	} catch ( Exception $e ) {	
		// Subscription check failed silently to avoid disrupting admin flow.
    	// Errors are non-critical; the next scheduled check will retry.
	} finally {
		delete_transient( 'mindweco_subscription_checking' );
		set_transient( 'mindweco_subscription_last_check', true, 30 * MINUTE_IN_SECONDS );
	}
}
