<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and hooks for enqueuing
 * the admin-specific stylesheet and JavaScript.
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/admin
 * @author     Edu Brazeal <contact@edubrazeal.com>
 */
class Aitnb_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param    string    $plugin_name       The name of this plugin.
	 * @param    string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;

		add_action( 'update_option_aitnb_settings', array( $this, 'handle_settings_update' ), 10, 2 );
		add_action( 'admin_init', array( $this, 'process_settings_actions' ) );
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 * @param    string    $hook_suffix    The current admin page.
	 */
	public function enqueue_styles( $hook_suffix ) {
	$pages = array( 'toplevel_page_aitnb-main', 'ai-try-n-buy_page_aitnb-analytics', 'post.php', 'post-new.php' );

		if ( in_array( $hook_suffix, $pages, true ) ) {
			wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/css/admin-styles.css', array(), $this->version, 'all' );
		}
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 * @param    string    $hook_suffix    The current admin page.
	 */
	public function enqueue_scripts( $hook_suffix ) {
	$script_pages = array( 'toplevel_page_aitnb-main', 'post.php', 'post-new.php', 'ai-try-n-buy_page_aitnb-analytics' );

		if ( ! in_array( $hook_suffix, $script_pages, true ) ) {
			return;
		}

		if ( 'post.php' === $hook_suffix || 'post-new.php' === $hook_suffix ) {
			wp_enqueue_media();
		}

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/js/admin-scripts.js', array( 'jquery' ), $this->version, true );

	if ( 'toplevel_page_aitnb-main' === $hook_suffix || 'ai-try-n-buy_page_aitnb-analytics' === $hook_suffix ) {
			wp_localize_script(
				$this->plugin_name,
				'aitnb_admin_params',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'aitnb_api_test_nonce' ),
					'i18n'     => array(
						'apiKeyMissing'          => __( 'API key is missing.', 'virtual-ai-fit-and-style-assistant' ),
						'requestFailed'          => __( 'Request failed.', 'virtual-ai-fit-and-style-assistant' ),
						'geminiApiKeyMissing'    => __( 'Gemini API key is missing.', 'virtual-ai-fit-and-style-assistant' ),
						'modelsFetchedSuccess'   => __( 'Models fetched successfully!', 'virtual-ai-fit-and-style-assistant' ),
						'errorPrefix'          => __( 'Error: ', 'virtual-ai-fit-and-style-assistant' ),
						'selectFitModel'         => __( 'Please select a Fit Recommendation Model to test.', 'virtual-ai-fit-and-style-assistant' ),
						'consentError'           => __( 'You must consent to data transmission to use this feature.', 'virtual-ai-fit-and-style-assistant' ),
						'permissionDenied'       => __( 'Permission denied.', 'virtual-ai-fit-and-style-assistant' ),
						'invalidApiType'         => __( 'Invalid API type specified.', 'virtual-ai-fit-and-style-assistant' ),
						'noModelsInResponse'     => __( 'Could not find models in API response.', 'virtual-ai-fit-and-style-assistant' ),
					),
				)
			);
		}
	}


	/**
	 * Add the top-level admin menu and its sub-pages.
	 *
	 * @since    1.0.0
	 */
	public function add_plugin_admin_menu() {
			add_menu_page(
				__( 'AI Try n Buy', 'virtual-ai-fit-and-style-assistant' ),
				__( 'AI Try n Buy', 'virtual-ai-fit-and-style-assistant' ),
				'manage_options',
				'aitnb-main',
				array( $this, 'display_plugin_settings_page' ),
				'dashicons-camera-alt',
				58
			);

			add_submenu_page(
				'aitnb-main',
				__( 'AI Try n Buy Settings', 'virtual-ai-fit-and-style-assistant' ),
				__( 'Settings', 'virtual-ai-fit-and-style-assistant' ),
				'manage_options',
				'aitnb-main',
				array( $this, 'display_plugin_settings_page' )
			);
	}


	/**
	 * Render the settings page for the plugin.
	 *
	 * @since    1.0.0
	 */
	public function display_plugin_settings_page() {
		require_once plugin_dir_path( __FILE__ ) . 'views/settings-page-view.php';
	}

	/**
	 * Register the plugin's settings with the Settings API.
	 *
	 * @since    1.0.0
	 */
	public function register_settings() {
		register_setting(
			'aitnb_option_group',
			'aitnb_settings',
			array( $this, 'sanitize_settings_input' )
		);
	}

	/**
	 * Sanitize each setting field as it is saved.
	 *
	 * @since    1.0.0
	 * @param    array     $input    Contains all settings fields as array keys.
	 * @return   array               Returns the sanitized settings.
	 */
	public function sanitize_settings_input( $input ) {
		$sanitized_input = get_option( 'aitnb_settings', array() );

		if ( isset( $input['google_api_key'] ) ) {
			$sanitized_input['google_api_key'] = sanitize_text_field( $input['google_api_key'] );
		}

		if ( isset( $input['gemini_api_key'] ) ) {
			$sanitized_input['gemini_api_key'] = sanitize_text_field( $input['gemini_api_key'] );
		}

		if ( isset( $input['gemini_fit_model'] ) ) {
			$sanitized_input['gemini_fit_model'] = sanitize_text_field( $input['gemini_fit_model'] );
		}

		if ( isset( $input['gemini_style_model'] ) ) {
			$sanitized_input['gemini_style_model'] = sanitize_text_field( $input['gemini_style_model'] );
		}

		if ( isset( $input['style_assistant_frequency'] ) ) {
			$allowed_frequencies = array( 'daily', 'twicedaily', 'weekly', 'twoweekly', 'monthly', 'manual' );
			if ( in_array( $input['style_assistant_frequency'], $allowed_frequencies, true ) ) {
				$sanitized_input['style_assistant_frequency'] = $input['style_assistant_frequency'];
			}
		}

		if ( isset( $input['product_page_hook'] ) ) {
			$allowed_hooks = array(
				'woocommerce_after_single_product_summary',
				'woocommerce_product_meta_end',
				'woocommerce_after_single_product',
			);
			if ( in_array( $input['product_page_hook'], $allowed_hooks, true ) ) {
				$sanitized_input['product_page_hook'] = $input['product_page_hook'];
			}
		}

		$sanitized_input['delete_data_on_uninstall'] = isset( $input['delete_data_on_uninstall'] ) && ( 1 === (int) $input['delete_data_on_uninstall'] );
		$sanitized_input['api_data_consent']         = isset( $input['api_data_consent'] ) && ( 1 === (int) $input['api_data_consent'] );

		return $sanitized_input;
	}

	/**
	 * Handles actions after plugin settings are updated.
	 *
	 * @since    1.4.0
	 * @param    array    $old_value    The old option value.
	 * @param    array    $new_value    The new option value.
	 */
	public function handle_settings_update( $old_value, $new_value ) {
		if ( class_exists( 'Aitnb_Style_Assistant_Cron' ) ) {
			Aitnb_Style_Assistant_Cron::reschedule_event();
		}
	}


	/**
	 * Registers the AJAX handlers for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function register_ajax_handlers() {
		add_action( 'wp_ajax_aitnb_test_api_connection', array( $this, 'ajax_test_api_connection' ) );
		add_action( 'wp_ajax_aitnb_fetch_gemini_models', array( $this, 'ajax_fetch_gemini_models' ) );
	}

	/**
	 * Handles the AJAX request for testing an API connection.
	 *
	 * @since    1.0.0
	 */
	public function ajax_test_api_connection() {
		check_ajax_referer( 'aitnb_api_test_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$options = get_option( 'aitnb_settings' );
		if ( ! isset( $options['api_data_consent'] ) || true !== $options['api_data_consent'] ) {
			wp_send_json_error( array( 'message' => __( 'You must consent to data transmission to use this feature.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$api_type = isset( $_POST['api_type'] ) ? sanitize_text_field( wp_unslash( $_POST['api_type'] ) ) : '';
		$api_key  = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';

		$allowed_api_types = array( 'google_vision', 'gemini' );
		if ( ! in_array( $api_type, $allowed_api_types, true ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid API type specified.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'API Key is required.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$response = new WP_Error( 'invalid_api', __( 'Invalid API type specified.', 'virtual-ai-fit-and-style-assistant' ) );

		switch ( $api_type ) {
			case 'google_vision':
				require_once plugin_dir_path( dirname( __FILE__ ) ) . 'services/class-google-vision-service.php';
				$service      = new Aitnb_Google_Vision_Service( $api_key );
				$test_image   = base64_decode( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' );
				$response     = $service->detect_face( $test_image );
				break;

			case 'gemini':
				$model_name = isset( $_POST['model_name'] ) ? sanitize_text_field( wp_unslash( $_POST['model_name'] ) ) : '';
				if ( empty( $model_name ) ) {
					wp_send_json_error( array( 'message' => __( 'Please select a Fit Recommendation Model to test.', 'virtual-ai-fit-and-style-assistant' ) ) );
				}
				require_once plugin_dir_path( dirname( __FILE__ ) ) . 'services/class-gemini-fit-service.php';
				$service  = new Aitnb_Gemini_Fit_Service( $api_key, $model_name );
				$response = $service->get_fit_recommendation(
					array( 'height' => 'test' ),
					array( 'size' => 'test' )
				);
				break;
		}

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => esc_html( $response->get_error_message() ) ) );
		}

		wp_send_json_success( array( 'message' => __( 'Connection successful!', 'virtual-ai-fit-and-style-assistant' ) ) );
	}

	/**
	 * Handles the AJAX request for fetching available Gemini models.
	 *
	 * @since    1.3.0
	 */
	public function ajax_fetch_gemini_models() {
		check_ajax_referer( 'aitnb_api_test_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$options = get_option( 'aitnb_settings' );
		if ( ! isset( $options['api_data_consent'] ) || true !== $options['api_data_consent'] ) {
			wp_send_json_error( array( 'message' => __( 'You must consent to data transmission to use this feature.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'API Key is required.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$request_url = 'https://generativelanguage.googleapis.com/v1/models?key=' . urlencode( $api_key );
		$response    = wp_remote_get(
			$request_url,
			array(
				'timeout' => 20,
				'headers' => array(
					'Content-Type' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => esc_html( $response->get_error_message() ) ) );
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );
		$data          = json_decode( $response_body, true );

		if ( 200 !== $response_code ) {
			$message = __( 'API Error', 'virtual-ai-fit-and-style-assistant' );
			if ( isset( $data['error']['message'] ) ) {
				$message = sanitize_text_field( $data['error']['message'] );
			}
			wp_send_json_error( array( 'message' => esc_html( $message ) ) );
		}

		if ( ! isset( $data['models'] ) || ! is_array( $data['models'] ) ) {
			wp_send_json_error( array( 'message' => __( 'Could not find models in API response.', 'virtual-ai-fit-and-style-assistant' ) ) );
		}

		$filtered_models = array();
		foreach ( $data['models'] as $model ) {
			if ( isset( $model['supportedGenerationMethods'] ) && 
			     is_array( $model['supportedGenerationMethods'] ) && 
			     in_array( 'generateContent', $model['supportedGenerationMethods'], true ) ) {
				$filtered_models[] = array(
					'id'   => isset( $model['name'] ) ? sanitize_text_field( $model['name'] ) : '',
					'name' => isset( $model['displayName'] ) ? sanitize_text_field( $model['displayName'] ) : '',
				);
			}
		}

		set_transient( 'aitnb_gemini_models_list', $filtered_models, DAY_IN_SECONDS );

		wp_send_json_success( array( 'models' => $filtered_models ) );
	}

	/**
	 * Processes settings import and export actions.
	 *
	 * @since 1.5.0
	 */
	public function process_settings_actions() {

		if ( isset( $_GET['aitnb_action'] ) && 'export_settings' === $_GET['aitnb_action'] ) {
			if ( ! isset( $_GET['aitnb_export_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['aitnb_export_nonce'] ), 'aitnb_export_action' ) ) {
				wp_die( esc_html__( 'Security check failed.', 'virtual-ai-fit-and-style-assistant' ) );
			}
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_die( esc_html__( 'You do not have permission to export settings.', 'virtual-ai-fit-and-style-assistant' ) );
			}

			$settings = get_option( 'aitnb_settings' );
			$filename = 'aitnb-settings-export-' . gmdate( 'Y-m-d-H-i-s' ) . '.json';

			header( 'Content-Disposition: attachment; filename=' . $filename );
			header( 'Content-Type: application/json; charset=utf-8' );
			header( 'Pragma: no-cache' );
			header( 'Expires: 0' );

			echo wp_json_encode( $settings, JSON_PRETTY_PRINT );
			exit;
		}

		if ( isset( $_POST['aitnb_import_settings'] ) ) {
			if ( ! isset( $_POST['aitnb_import_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aitnb_import_nonce'] ) ), 'aitnb_import_action' ) ) {
				wp_die( esc_html__( 'Security check failed.', 'virtual-ai-fit-and-style-assistant' ) );
			}
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_die( esc_html__( 'You do not have permission to import settings.', 'virtual-ai-fit-and-style-assistant' ) );
			}

			if ( ! isset( $_FILES['aitnb_import_file'] ) || ! isset( $_FILES['aitnb_import_file']['error'] ) || UPLOAD_ERR_OK !== (int) $_FILES['aitnb_import_file']['error'] ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Error uploading file. Please try again.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			if ( ! isset( $_FILES['aitnb_import_file']['size'] ) || $_FILES['aitnb_import_file']['size'] > ( 1 * 1024 * 1024 ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'File is too large. Please upload a file smaller than 1MB.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			if ( ! isset( $_FILES['aitnb_import_file']['tmp_name'] ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'File upload failed.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			$tmp_name = sanitize_text_field( wp_unslash( $_FILES['aitnb_import_file']['tmp_name'] ) );
			if ( ! is_uploaded_file( $tmp_name ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'File upload verification failed.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			if ( ! isset( $_FILES['aitnb_import_file']['name'] ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'File name is missing.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			$file_type = wp_check_filetype( basename( sanitize_file_name( wp_unslash( $_FILES['aitnb_import_file']['name'] ) ) ) );
			if ( 'json' !== $file_type['ext'] ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Invalid file type. Please upload a .json file.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			$finfo = finfo_open( FILEINFO_MIME_TYPE );
			$mime_type = finfo_file( $finfo, $tmp_name );
			finfo_close( $finfo );

			$allowed_mime_types = array( 'application/json', 'text/plain' );
			if ( ! in_array( $mime_type, $allowed_mime_types, true ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Invalid file MIME type. Please upload a valid JSON file.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			if ( ! function_exists( 'WP_Filesystem' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			WP_Filesystem();
			global $wp_filesystem;

			$json_data = $wp_filesystem->get_contents( $tmp_name );
			
			if ( false === $json_data ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Could not read the uploaded file.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			$settings = json_decode( $json_data, true );

			if ( null === $settings || json_last_error() !== JSON_ERROR_NONE ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Error decoding JSON file. Please check the file format.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			if ( ! is_array( $settings ) ) {
				add_settings_error( 'aitnb_settings', 'import_error', __( 'Invalid settings format in JSON file.', 'virtual-ai-fit-and-style-assistant' ), 'error' );
				return;
			}

			$sanitized_settings = $this->sanitize_settings_input( $settings );
			update_option( 'aitnb_settings', $sanitized_settings );

			add_settings_error( 'aitnb_settings', 'import_success', __( 'Settings imported successfully.', 'virtual-ai-fit-and-style-assistant' ), 'updated' );
		}
	}
}