<?php
/**
 * 
 * MindWebConcierge AJAX Handlers
 *
 * @package MindWebConcierge
 */

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

require_once __DIR__ . '/mindweco_config.php';

/**
 * Return the plugin configuration array stored in WP options.
 *
 * @return array
 */
function mindweco_spaces_load_config() {
	return array(
		'rag_url'       => MINDWECO_RAG_URL,
		'notebooks_url' => MINDWECO_NOTEBOOKS_URL,
		'stripe_url'    => MINDWECO_STRIPE_URL,
		'prod_id'       => MINDWECO_PROD_ID,
	);
}

add_action( 'wp_ajax_mindweco_knowledge_repository_login', 'mindweco_knowledge_repository_login' );

function mindweco_knowledge_repository_login() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$config = mindweco_spaces_load_config();
	$username = isset( $_POST['username'] ) ? sanitize_text_field( wp_unslash( $_POST['username'] ) ) : '';

	$password = isset( $_POST['password'] ) ? wp_unslash( $_POST['password'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

	$base_url = isset( $_POST['base_url'] )
		? esc_url_raw( wp_unslash( $_POST['base_url'] ) )
		: $config['notebooks_url'];

	$indexing_options = get_option( 'mindweco_plugin_indexing', array() );
	$indexing_id      = isset( $indexing_options['id'] ) ? $indexing_options['id'] : null;
	$indexing_name    = isset( $indexing_options['title'] ) ? $indexing_options['title'] : null;
	$external_id      = $indexing_id;
	$external_name    = $indexing_name;
	$type             = 0;

	if ( ! $base_url || ! $username || ! $password ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Please fill in all fields.', 'mind-web-concierge' ) ) );
		return;
	}

	if ( ! filter_var( $base_url, FILTER_VALIDATE_URL ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid base URL format.', 'mind-web-concierge' ) ) );
		return;
	}

	$login_result = mindweco_plugin_knowledge_repository_login_with_cookie(
		$base_url,
		$username,
		$password,
		$external_id,
		$external_name,
		$type
	);

	if ( isset( $login_result['error'] ) ) {
		wp_send_json_error( array( 'message' => esc_html( $login_result['error'] ) ) );
		return;
	}

	$token = isset( $login_result['data']['token'] ) ? $login_result['data']['token'] : null;
	if ( ! $token ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Login failed, token not returned.', 'mind-web-concierge' ) ) );
		return;
	}

	update_option( 'mindweco_logged_status', 1 );
	$full_result = isset( $login_result['data'] ) ? $login_result['data'] : array();
	unset( $full_result['token'] );
	update_option(
		'mindweco_knowledge_repository_options',
		array(
			'base_url'    => esc_url_raw( $base_url ),
			'username'    => $username,
			'password'    => mindweco_encrypt_api_key( $password ),
			'token'       => mindweco_encrypt_api_key( sanitize_text_field( $token ) ), 
			'full_result' => $full_result,
		)
	);

	wp_send_json_success( array(
		'message' => esc_html__( 'Login successful!', 'mind-web-concierge' ),
	) );
}

add_action( 'wp_ajax_mindweco_get_notebooks', 'mindweco_get_notebooks' );

function mindweco_get_notebooks() {
	$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
	if ( ! wp_verify_nonce( $nonce, 'mindweco_login_nonce' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Security check failed.', 'mind-web-concierge' ) ), 403 );
		return;
	}

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$options  = get_option( 'mindweco_knowledge_repository_options', array() );
	$token = isset( $options['token'] ) ? mindweco_decrypt_api_key( $options['token'] ) : '';
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';

	if ( ! $token || ! $base_url ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Not logged in. Please login first.', 'mind-web-concierge' ) ) );
		return;
	}

	$response = mindweco_plugin_get_notebooks( $base_url, $token );

	if ( isset( $response['status'] ) && 401 === (int) $response['status'] ) {
		$new_token = mindweco_plugin_knowledge_repository_refresh_token();
		if ( ! $new_token ) {
			delete_option( 'mindweco_knowledge_repository_options' );
			wp_send_json_error( array( 'message' => esc_html__( 'Session expired. Please login again.', 'mind-web-concierge' ) ) );
			return;
		}
		$response = mindweco_plugin_get_notebooks( $base_url, $new_token );
		if ( isset( $response['status'] ) && 401 === (int) $response['status'] ) {
			delete_option( 'mindweco_knowledge_repository_options' );
			wp_send_json_error( array( 'message' => esc_html__( 'Authentication failed. Please login again.', 'mind-web-concierge' ) ) );
			return;
		}
	}

	if ( isset( $response['error'] ) ) {
		wp_send_json_error( array( 'message' => esc_html( $response['error'] ) ) );
		return;
	}

	wp_send_json_success( array(
		'notebooks' => isset( $response['notebooks'] ) ? $response['notebooks'] : array(),
		'message'   => esc_html__( 'Fetched notebooks successfully', 'mind-web-concierge' ),
	) );
}

add_action( 'wp_ajax_mindweco_get_saved_page_based', 'mindweco_get_saved_page_based' );

function mindweco_get_saved_page_based() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$pages = get_posts( array(
		'post_type'      => array( 'post', 'page' ),
		'post_status'    => 'publish',
		'posts_per_page' => -1,
		'orderby'        => 'title',
		'order'          => 'ASC',
	) );

	$result = array();
	foreach ( $pages as $page ) {
		$result[] = array(
			'id'      => absint( $page->ID ),
			'title'   => esc_html( $page->post_title ),
			'url'     => esc_url( get_permalink( $page->ID ) ),
			'excerpt' => esc_html(
				wp_trim_words(
					! empty( $page->post_excerpt ) ? $page->post_excerpt : $page->post_content,
					20
				)
			),
		);
	}

	wp_send_json_success( $result );
}

add_action( 'wp_ajax_mindweco_get_page_notebooks', 'mindweco_get_page_notebooks' );

function mindweco_get_page_notebooks() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$page_id = absint( isset( $_POST['page_id'] ) ? $_POST['page_id'] : 0 );
	if ( ! $page_id ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid page ID.', 'mind-web-concierge' ) ) );
		return;
	}

	$data = get_option( 'mindweco_page_based_notebooks', array() );

	wp_send_json_success( array(
		'notebooks'  => isset( $data[ $page_id ]['notebooks'] ) ? $data[ $page_id ]['notebooks'] : array(),
		'page_title' => esc_html( get_the_title( $page_id ) ),
	) );
}


add_action( 'wp_ajax_mindweco_save_page_notebooks', 'mindweco_save_page_notebooks' );

function mindweco_save_page_notebooks() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'No permission.', 'mind-web-concierge' ) ) );
		return;
	}

	$page_id   = absint( isset( $_POST['page_id'] ) ? $_POST['page_id'] : 0 );
	$notebooks = isset( $_POST['notebook_ids'] )
		? array_values( array_unique( array_map( 'absint', (array) $_POST['notebook_ids'] ) ) )
		: array();

	if ( ! $page_id ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid page ID.', 'mind-web-concierge' ) ) );
		return;
	}

	$data = get_option( 'mindweco_page_based_notebooks', array() );

	$data[ $page_id ] = array(
		'title'     => sanitize_text_field( get_the_title( $page_id ) ),
		'notebooks' => $notebooks,
	);

	update_option( 'mindweco_page_based_notebooks', $data );

	wp_send_json_success( array(
		'message' => esc_html__( 'Saved.', 'mind-web-concierge' ),
		'page_id' => $page_id,
	) );
}

add_action( 'wp_ajax_mindweco_get_all_page_notebooks', 'mindweco_get_all_page_notebooks' );

function mindweco_get_all_page_notebooks() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	wp_send_json_success( get_option( 'mindweco_page_based_notebooks', array() ) );
}

add_action( 'wp_ajax_mindweco_remove_page_notebooks', 'mindweco_remove_page_notebooks' );

function mindweco_remove_page_notebooks() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$page_id = absint( isset( $_POST['page_id'] ) ? $_POST['page_id'] : 0 );
	if ( ! $page_id ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid page ID.', 'mind-web-concierge' ) ) );
		return;
	}

	$data = get_option( 'mindweco_page_based_notebooks', array() );
	unset( $data[ $page_id ] );
	update_option( 'mindweco_page_based_notebooks', $data );

	wp_send_json_success( array( 'page_id' => $page_id ) );
}

add_action( 'wp_ajax_mindweco_remove_all_page_notebooks', 'mindweco_remove_all_page_notebooks' );

function mindweco_remove_all_page_notebooks() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	update_option( 'mindweco_page_based_notebooks', array() );

	wp_send_json_success( array( 'message' => esc_html__( 'All page notebooks removed.', 'mind-web-concierge' ) ) );
}

add_action( 'wp_ajax_mindweco_knowledge_repository_logout', 'mindweco_knowledge_repository_logout' );

function mindweco_knowledge_repository_logout() {
	check_ajax_referer( 'mindweco_login_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Access denied.', 'mind-web-concierge' ) ) );
		return;
	}

	$config = mindweco_spaces_load_config();
	$base_url = isset( $_POST['base_url'] )
		? esc_url_raw( wp_unslash( $_POST['base_url'] ) )
		: $config['notebooks_url'];

	$indexing_options = get_option( 'mindweco_plugin_indexing', array() );
	$external_app_id  = isset( $indexing_options['id'] ) ? $indexing_options['id'] : null;

	$knowledge_options = get_option( 'mindweco_knowledge_repository_options', array() );
	$full_result       = isset( $knowledge_options['full_result'] ) ? $knowledge_options['full_result'] : array();
	$user_id           = isset( $full_result['user']['id'] ) ? $full_result['user']['id'] : null;

	if ( ! $external_app_id || ! $user_id ) {
		delete_option( 'mindweco_knowledge_repository_options' );
		update_option( 'mindweco_logged_status', 0 );
		wp_send_json_success( array( 'message' => esc_html__( 'You have been logged out successfully.', 'mind-web-concierge' ) ) );
		return;
	}

	$response = mindweco_plugin_knowledge_repository_logout( $base_url, $external_app_id, $user_id );

	update_option( 'mindweco_logged_status', 0 );

	$success = ( true === $response )
		|| ( is_array( $response ) && isset( $response['http_code'] ) && 200 === (int) $response['http_code'] );

	delete_option( 'mindweco_knowledge_repository_options' );
	wp_send_json_success( array( 'message' => esc_html__( 'You have been logged out successfully.', 'mind-web-concierge' ) ) );
}