<?php
/**
 * Settings class for Voice Logica AI for WooCommerce plugin
 *
 * @package VoiceLogica_AI_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class VoiceLogica_AI_Settings
 */
class VoiceLogica_AI_Settings {

	/**
	 * Option names
	 */
	const OPTION_CONNECTED   = 'voicelogica_ai_connected';
	const OPTION_WEBHOOK_URL = 'voicelogica_ai_webhook_url';
	const OPTION_FEATURES    = 'voicelogica_ai_features';

	/**
	 * Feature keys
	 */
	const FEATURE_CREATE_ORDER        = 'create_order';
	const FEATURE_GET_PRODUCT_BY_CODE = 'get_product_by_code';
	const FEATURE_GET_PRODUCT_BY_NAME = 'get_product_by_name';
	const FEATURE_GET_CUSTOMER_ORDERS = 'get_customer_orders';

	const FEATURE_GET_ORDER_BY_ID = 'get_order_by_id';

	/**
	 * Additional field keys
	 */
	const FIELD_PRODUCT_CODE_TYPE               = 'product_code_type';
	const FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION = 'notify_emails_on_order_creation';

	/**
	 * Default features.
	 */
	const DEFAULT_FEATURES = array(
		self::FEATURE_CREATE_ORDER                  => false,
		self::FEATURE_GET_PRODUCT_BY_CODE           => false,
		self::FEATURE_GET_PRODUCT_BY_NAME           => false,
		self::FEATURE_GET_CUSTOMER_ORDERS           => false,

		self::FEATURE_GET_ORDER_BY_ID               => false,
		self::FIELD_PRODUCT_CODE_TYPE               => '',
		self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION => array(),
	);

	/**
	 * API Client instance
	 *
	 * @var VoiceLogica_AI_API_Client
	 */
	private $api_client;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->api_client = new VoiceLogica_AI_API_Client();

		add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
	}

	/**
	 * Add admin menu
	 */
	public function add_admin_menu() {
		add_submenu_page(
			'woocommerce',
			__( 'Voice Logica AI', 'voicelogica-ai-for-woocommerce' ),
			__( 'Voice Logica AI', 'voicelogica-ai-for-woocommerce' ),
			'manage_woocommerce',
			'voicelogica-ai-for-woocommerce',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Handle connect and feature update actions
	 */
	public function handle_actions() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		// Connect action.
		if ( isset( $_POST['voicelogica_ai_connect'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['voicelogica_ai_nonce'] ?? '' ) ), 'voicelogica_ai_connect' ) ) {
			$connect_url = $this->get_default_webhook_url();
			$result      = $this->api_client->connect_store( $connect_url );

			if ( is_wp_error( $result ) ) {
				add_settings_error(
					'voicelogica_ai',
					'connect_failed',
					$result->get_error_message(),
					'error'
				);
				return;
			}

			// Response always contains 'success' and 'message' fields.
			$success = isset( $result['success'] ) && true === $result['success'];
			$message = isset( $result['message'] ) ? $result['message'] : '';

			if ( ! $success ) {
				// Show error message from server.
				add_settings_error(
					'voicelogica_ai',
					'connect_failed',
					! empty( $message ) ? $message : __( 'Connection failed. Server did not return success.', 'voicelogica-ai-for-woocommerce' ),
					'error'
				);
				return;
			}

			// Success case - save connection and show feature settings.
			update_option( self::OPTION_WEBHOOK_URL, $connect_url );
			update_option( self::OPTION_CONNECTED, true );
			update_option( self::OPTION_FEATURES, self::DEFAULT_FEATURES );

			// Do not add server message; only the static "Connected" notice in the view will be shown.
			return;
		}

		// Save features action.
		if ( isset( $_POST['voicelogica_ai_save_features'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['voicelogica_ai_features_nonce'] ?? '' ) ), 'voicelogica_ai_save_features' ) ) {
			$submitted_features = isset( $_POST['features'] ) && is_array( $_POST['features'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['features'] ) ) : array();
			$features           = self::DEFAULT_FEATURES;

			// Update features based on submitted checkboxes.
			foreach ( array_keys( $features ) as $feature_key ) {
				if ( in_array( $feature_key, array( self::FEATURE_CREATE_ORDER, self::FEATURE_GET_PRODUCT_BY_CODE, self::FEATURE_GET_PRODUCT_BY_NAME, self::FEATURE_GET_CUSTOMER_ORDERS, self::FEATURE_GET_ORDER_BY_ID ), true ) ) {
					$features[ $feature_key ] = isset( $submitted_features[ $feature_key ] ) && '1' === $submitted_features[ $feature_key ];
				}
			}

			// Handle product_code_type field (only if get_product_by_code is checked); default to 'sku' when empty.
			if ( ! empty( $submitted_features[ self::FEATURE_GET_PRODUCT_BY_CODE ] ) ) {
				$code_type = isset( $submitted_features[ self::FIELD_PRODUCT_CODE_TYPE ] ) ? sanitize_text_field( $submitted_features[ self::FIELD_PRODUCT_CODE_TYPE ] ) : '';
				if ( in_array( $code_type, array( 'id', 'sku', 'global_unique_id' ), true ) ) {
					$features[ self::FIELD_PRODUCT_CODE_TYPE ] = $code_type;
				} else {
					$features[ self::FIELD_PRODUCT_CODE_TYPE ] = 'sku';
				}
			} else {
				$features[ self::FIELD_PRODUCT_CODE_TYPE ] = '';
			}

			// Handle notify_emails_on_order_creation field (only if create_order is checked).
			if ( ! empty( $submitted_features[ self::FEATURE_CREATE_ORDER ] ) && isset( $submitted_features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ] ) ) {
				$emails = $submitted_features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ];
				if ( is_string( $emails ) ) {
					// Handle comma-separated string.
					$emails = array_map( 'trim', explode( ',', $emails ) );
				}
				if ( is_array( $emails ) ) {
					$valid_emails = array();
					foreach ( $emails as $email ) {
						$email = sanitize_email( trim( $email ) );
						if ( ! empty( $email ) && is_email( $email ) ) {
							$valid_emails[] = $email;
						}
					}
					$features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ] = $valid_emails;
				}
			} else {
				$features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ] = array();
			}

			update_option( self::OPTION_FEATURES, $features );

			// Send webhook to VoiceLogica.
			$webhook_url = get_option( self::OPTION_WEBHOOK_URL, '' );
			if ( ! empty( $webhook_url ) ) {
				$result = $this->api_client->send_features_updated( $webhook_url, $features );
				if ( is_wp_error( $result ) ) {
					add_settings_error(
						'voicelogica_ai',
						'features_update_failed',
						/* translators: %s: Error message returned from the webhook/API */
						sprintf( __( 'Settings saved, but failed to notify Voice Logica AI: %s', 'voicelogica-ai-for-woocommerce' ), $result->get_error_message() ),
						'error'
					);
					return;
				}
			}

			add_settings_error(
				'voicelogica_ai',
				'features_saved',
				__( 'Settings saved successfully!', 'voicelogica-ai-for-woocommerce' ),
				'success'
			);
			return;
		}

		// Disconnect action.
		if ( isset( $_POST['voicelogica_ai_disconnect'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['voicelogica_ai_disconnect_nonce'] ?? '' ) ), 'voicelogica_ai_disconnect' ) ) {
			$this->disconnect_store();

			add_settings_error(
				'voicelogica_ai',
				'disconnect_success',
				__( 'Successfully disconnected from Voice Logica AI. All connection data and API keys have been removed.', 'voicelogica-ai-for-woocommerce' ),
				'success'
			);
		}
	}

	/**
	 * Default VoiceLogica webhook URL.
	 *
	 * @return string
	 */
	private function get_default_webhook_url() {
		/**
		 * Filters the default VoiceLogica API connect/webhook URL.
		 *
		 * @since 1.0.0
		 */
		return apply_filters(
			'voicelogica_ai_connect_url',
			defined( 'VOICELOGICA_AI_CONNECT_URL' ) ? VOICELOGICA_AI_CONNECT_URL : 'https://api.voicelogica.ai/api/woocommerce'
		);
	}

	/**
	 * Disconnect store from VoiceLogica.
	 */
	private function disconnect_store() {
		// Delete WooCommerce API key.
		$this->api_client->delete_woocommerce_api_key();

		// Delete all connection options.
		delete_option( self::OPTION_CONNECTED );
		delete_option( self::OPTION_WEBHOOK_URL );
		delete_option( self::OPTION_FEATURES );
		delete_option( 'voicelogica_ai_webhook_secret' );
		delete_option( 'voicelogica_ai_api_key_id' );
		delete_option( 'voicelogica_ai_api_consumer_key' );
		delete_option( 'voicelogica_ai_api_consumer_secret' );
	}


	/**
	 * Enqueue admin styles and assets (only on our settings page).
	 *
	 * @param string $hook_suffix Current admin page hook.
	 */
	public function enqueue_admin_assets( $hook_suffix ) {
		if ( 'woocommerce_page_voicelogica-ai-for-woocommerce' !== $hook_suffix ) {
			return;
		}
		$url     = defined( 'VOICELOGICA_AI_WC_PLUGIN_URL' ) ? VOICELOGICA_AI_WC_PLUGIN_URL : plugin_dir_url( __DIR__ );
		$version = defined( 'VOICELOGICA_AI_WC_VERSION' ) ? VOICELOGICA_AI_WC_VERSION : '1.0.0';

		wp_enqueue_style(
			'voicelogica-ai-admin',
			$url . 'assets/css/admin.css',
			array(),
			$version
		);

		wp_enqueue_script(
			'voicelogica-ai-admin-settings',
			$url . 'assets/js/admin-settings.js',
			array(),
			$version,
			true
		);
	}

	/**
	 * Get URL to VoiceLogica logo for admin header.
	 * Looks for logo.svg, logo.png, or logo.jpg in assets/images/.
	 * All assets are included locally within the plugin (no remote calls).
	 *
	 * @return string Logo URL or empty string if no file found.
	 */
	public function get_logo_url() {
		$base_url  = defined( 'VOICELOGICA_AI_WC_PLUGIN_URL' ) ? VOICELOGICA_AI_WC_PLUGIN_URL : plugin_dir_url( __DIR__ );
		$base_path = defined( 'VOICELOGICA_AI_WC_PLUGIN_DIR' ) ? VOICELOGICA_AI_WC_PLUGIN_DIR : plugin_dir_path( __DIR__ );
		$images    = array( 'logo.svg', 'logo.png', 'logo.jpg' );
		$logo_url  = '';
		foreach ( $images as $file ) {
			$path = $base_path . 'assets/images/' . $file;
			if ( is_readable( $path ) ) {
				$logo_url = $base_url . 'assets/images/' . $file;
				break;
			}
		}
		/**
		 * Filters the URL to the VoiceLogica logo in the admin header.
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'voicelogica_ai_logo_url', $logo_url );
	}

	/**
	 * Render settings page
	 */
	public function render_settings_page() {
		$connected = (bool) get_option( self::OPTION_CONNECTED, false );
		$features  = wp_parse_args( get_option( self::OPTION_FEATURES, array() ), self::DEFAULT_FEATURES );
		$logo_url  = $this->get_logo_url();

		// Ensure array fields are arrays.
		if ( ! is_array( $features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ] ) ) {
			$features[ self::FIELD_NOTIFY_EMAILS_ON_ORDER_CREATION ] = array();
		}

		$view_file = defined( 'VOICELOGICA_AI_WC_PLUGIN_DIR' ) ? VOICELOGICA_AI_WC_PLUGIN_DIR . 'admin/views/settings-page.php' : dirname( __DIR__ ) . '/admin/views/settings-page.php';
		if ( is_readable( $view_file ) ) {
			include $view_file;
		}
	}
}
