<?php
/**
 * Admin functionality
 *
 * @package TrylyAI
 * @since   1.0.0
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin class.
 *
 * @since 1.0.0
 */
class Tryly_Admin {

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_action( 'wp_ajax_tryly_save_connection', array( $this, 'ajax_save_connection' ) );
		add_action( 'wp_ajax_tryly_disconnect', array( $this, 'ajax_disconnect' ) );
		add_action( 'wp_ajax_tryly_check_connection', array( $this, 'ajax_check_connection' ) );
		add_action( 'wp_ajax_tryly_get_state', array( $this, 'ajax_get_state' ) );
		add_action( 'admin_init', array( $this, 'maybe_redirect_after_activation' ) );
		add_action( 'admin_init', array( $this, 'handle_connection_callback' ), 1 );
	}

	/**
	 * Add admin menu.
	 *
	 * @since 1.0.0
	 */
	public function add_admin_menu() {
		add_menu_page(
			esc_html__( 'Tryly.ai Virtual Try-On', 'tryly-ai-virtual-try-on-for-woocommerce' ),
			esc_html__( 'Tryly.ai', 'tryly-ai-virtual-try-on-for-woocommerce' ),
			'manage_options',
			'tryly-ai',
			array( $this, 'render_admin_page' ),
			'dashicons-visibility',
			30
		);
	}

	/**
	 * Handle connection callbacks early before any output
	 *
	 * @since 1.0.14
	 */
	public function handle_connection_callback() {
		// Only process on our admin page
		if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'tryly-ai' ) {
			return;
		}
		
		// NEW FLOW: Handle tryly_data callback
		if ( isset( $_GET['tryly_data'] ) && isset( $_GET['status'] ) && $_GET['status'] === 'success' ) {
			// CRITICAL: Verify CSRF state token (required)
			if ( ! isset( $_GET['state'] ) ) {
				set_transient( 'tryly_connection_error', 
					'Security verification failed. Missing state token.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=csrf' ) );
				exit;
			}
			
			$provided_state = sanitize_text_field( wp_unslash( $_GET['state'] ) );
			$stored_state = get_transient( 'tryly_oauth_state_' . get_current_user_id() );
			
			if ( ! $stored_state || $stored_state !== $provided_state ) {
				set_transient( 'tryly_connection_error', 
					'Security verification failed. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=csrf' ) );
				exit;
			}
			
			// State verified, delete it
			delete_transient( 'tryly_oauth_state_' . get_current_user_id() );
			
			// Safe decode without sanitization
			$encoded_data = wp_unslash( $_GET['tryly_data'] );
			
			// Handle URL encoding of base64 padding
			if ( strpos( $encoded_data, '%' ) !== false ) {
				$encoded_data = rawurldecode( $encoded_data );
			}
			
			// Normalize spaces that might have been converted
			$encoded_data = str_replace( ' ', '+', $encoded_data );
			
			// Strict base64 decode
			$json_data = base64_decode( $encoded_data, true );
			
			if ( $json_data === false ) {
				// Set error notice and redirect
				set_transient( 'tryly_connection_error', 
					'Could not read the response from Tryly. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=decode' ) );
				exit;
			}
			
			$payload = json_decode( $json_data, true );
			
			if ( ! $payload || ! isset( $payload['merchant_key'] ) ) {
				set_transient( 'tryly_connection_error', 
					'Invalid response from Tryly. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=invalid' ) );
				exit;
			}
			
			// Validate merchant key format (flexible pattern)
			if ( ! preg_match( '/^tryon_[a-z0-9]+$/', $payload['merchant_key'] ) ) {
				set_transient( 'tryly_connection_error', 
					'Invalid merchant key format. Please contact support.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=key' ) );
				exit;
			}
			
			// Save all data
			update_option( 'tryly_connected', true );
			update_option( 'tryly_merchant_key', sanitize_text_field( $payload['merchant_key'] ) );
			
			if ( isset( $payload['user_email'] ) ) {
				update_option( 'tryly_user_email', sanitize_email( $payload['user_email'] ) );
			}
			
			if ( isset( $payload['disconnect_token'] ) ) {
				update_option( 'tryly_disconnect_token', sanitize_text_field( $payload['disconnect_token'] ) );
			}
			
			// Save widget settings if provided
			if ( isset( $payload['settings'] ) && is_array( $payload['settings'] ) ) {
				foreach ( $payload['settings'] as $key => $value ) {
					// Convert booleans to strings for consistency
					if ( is_bool( $value ) ) {
						$value = $value ? 'true' : 'false';
					}
					update_option( 'tryly_' . $key, sanitize_text_field( $value ) );
				}
			}
			
			// Clear the correct cache
			delete_transient( 'tryly_settings_' . md5( $payload['merchant_key'] ) );
			
			// Log connection event
			$this->log_event( 'connected', array(
				'merchant_key' => $payload['merchant_key'],
				'user_email'   => isset( $payload['user_email'] ) ? $payload['user_email'] : '',
				'flow'         => 'new'
			) );
			
			// Redirect to clean URL
			wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&connected=1' ) );
			exit;
		}
		
		// OLD FLOW: Handle legacy merchant_key callback for backward compatibility
		elseif ( isset( $_GET['merchant_key'] ) && isset( $_GET['status'] ) && $_GET['status'] === 'success' ) {
			// Verify state token for CSRF protection
			if ( ! isset( $_GET['state'] ) ) {
				set_transient( 'tryly_connection_error', 
					'Security verification failed. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=state' ) );
				exit;
			}
			
			$provided_state = sanitize_text_field( wp_unslash( $_GET['state'] ) );
			$stored_state = get_transient( 'tryly_oauth_state_' . get_current_user_id() );
			
			if ( ! $stored_state || $stored_state !== $provided_state ) {
				set_transient( 'tryly_connection_error', 
					'Security verification failed. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=state' ) );
				exit;
			}
			
			// State is valid, delete it
			delete_transient( 'tryly_oauth_state_' . get_current_user_id() );
			
			$merchant_key = sanitize_text_field( wp_unslash( $_GET['merchant_key'] ) );
			$user_email   = isset( $_GET['user_email'] ) ? sanitize_email( wp_unslash( $_GET['user_email'] ) ) : '';
			
			if ( empty( $merchant_key ) ) {
				set_transient( 'tryly_connection_error', 
					'No merchant key received. Please try connecting again.', 30 );
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&error=nokey' ) );
				exit;
			}
			
			// Save connection data
			update_option( 'tryly_connected', true );
			update_option( 'tryly_merchant_key', $merchant_key );
			
			if ( ! empty( $user_email ) ) {
				update_option( 'tryly_user_email', $user_email );
			}
			
			// Clear the correct cache
			delete_transient( 'tryly_settings_' . md5( $merchant_key ) );
			
			// Log connection event
			$this->log_event( 'connected', array(
				'merchant_key' => $merchant_key,
				'user_email'   => $user_email,
				'flow'         => 'legacy'
			) );
			
			// Redirect to clean URL
			wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai&connected=1' ) );
			exit;
		}
	}

	/**
	 * Redirect to settings page after activation.
	 *
	 * @since 1.0.0
	 */
	public function maybe_redirect_after_activation() {
		if ( get_option( 'tryly_activation_redirect', false ) ) {
			delete_option( 'tryly_activation_redirect' );
			if ( ! isset( $_GET['activate-multi'] ) ) {
				wp_safe_redirect( admin_url( 'admin.php?page=tryly-ai' ) );
				exit;
			}
		}
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @since 1.0.0
	 * @param string $hook Current admin page.
	 */
	public function enqueue_admin_assets( $hook ) {
		if ( 'toplevel_page_tryly-ai' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'tryly-admin',
			TRYLY_PLUGIN_URL . 'assets/admin.css',
			array(),
			TRYLY_VERSION
		);

		wp_enqueue_script(
			'tryly-admin',
			TRYLY_PLUGIN_URL . 'assets/admin.js',
			array( 'jquery' ),
			TRYLY_VERSION,
			true
		);

		wp_localize_script(
			'tryly-admin',
			'tryly_admin',
			array(
				'ajax_url'     => admin_url( 'admin-ajax.php' ),
				'nonce'        => wp_create_nonce( 'tryly_admin_nonce' ),
				'api_url'      => TRYLY_API_URL,
				'callback_url' => admin_url( 'admin.php?page=tryly-ai' ),
				'site_url'     => get_site_url(),
				'admin_email'  => get_option( 'admin_email' ),
				'strings'      => array(
					'connecting'    => esc_html__( 'Connecting...', 'tryly-ai-virtual-try-on-for-woocommerce' ),
					'connected'     => esc_html__( 'Connected!', 'tryly-ai-virtual-try-on-for-woocommerce' ),
					'error'         => esc_html__( 'Connection failed. Please try again.', 'tryly-ai-virtual-try-on-for-woocommerce' ),
					'disconnected'  => esc_html__( 'Disconnected successfully.', 'tryly-ai-virtual-try-on-for-woocommerce' ),
					'confirm_disconnect' => esc_html__( 'Are you sure you want to disconnect from Tryly.ai?', 'tryly-ai-virtual-try-on-for-woocommerce' ),
				),
			)
		);
	}

	/**
	 * Render admin page.
	 *
	 * @since 1.0.0
	 */
	public function render_admin_page() {
		// Display any connection errors
		$error_message = get_transient( 'tryly_connection_error' );
		if ( $error_message ) {
			?>
			<div class="notice notice-error is-dismissible">
				<p><?php echo esc_html( $error_message ); ?></p>
			</div>
			<?php
			delete_transient( 'tryly_connection_error' );
		}
		
		$connected    = get_option( 'tryly_connected', false );
		$merchant_key = get_option( 'tryly_merchant_key', '' );
		$user_email   = get_option( 'tryly_user_email', '' );
		?>
		<div class="wrap tryly-admin-wrap">
			<div class="tryly-admin-container">
				<div class="tryly-admin-header">
					<img src="<?php echo esc_url( TRYLY_API_URL ); ?>/logo.svg" 
					     alt="Tryly.ai" 
					     class="tryly-logo" 
					     width="120" 
					     height="45" />
				</div>
				
				<div class="tryly-admin-content">
					<?php if ( isset( $_GET['connected'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['connected'] ) ) ) : ?>
						<div class="notice notice-success is-dismissible">
							<p><?php esc_html_e( 'Successfully connected to Tryly.ai!', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?></p>
						</div>
					<?php endif; ?>
					
					<?php if ( ! $connected ) : ?>
						<div class="tryly-connect-section">
							<p><?php esc_html_e( 'Connect your store to enable virtual try-on for your customers', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?></p>
							
							<button type="button" id="tryly-connect-btn" class="tryly-connect-button">
								<?php esc_html_e( 'Connect with Tryly.ai', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?>
							</button>
						</div>
					<?php else : ?>
						<div class="tryly-connected-section">
							<div class="tryly-status">
								<span class="tryly-status-indicator"></span>
								<span class="tryly-status-text"><?php esc_html_e( 'Connected', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?></span>
							</div>
							
							<?php if ( $user_email ) : ?>
							<div class="tryly-account-info">
								<?php echo esc_html( $user_email ); ?>
							</div>
							<?php endif; ?>
							
							<div class="tryly-actions">
								<a href="<?php echo esc_url( TRYLY_API_URL . '/dashboard' ); ?>" target="_blank" class="tryly-button tryly-button-primary">
									<?php esc_html_e( 'Dashboard', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?>
								</a>
								<a href="<?php echo esc_url( TRYLY_API_URL . '/dashboard/settings' ); ?>" target="_blank" class="tryly-button">
									<?php esc_html_e( 'Settings', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?>
								</a>
								<button type="button" id="tryly-disconnect-btn" class="tryly-button tryly-button-secondary">
									<?php esc_html_e( 'Disconnect', 'tryly-ai-virtual-try-on-for-woocommerce' ); ?>
								</button>
							</div>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * AJAX handler for saving connection.
	 *
	 * @since 1.0.0
	 */
	public function ajax_save_connection() {
		// Verify nonce.
		if ( ! check_ajax_referer( 'tryly_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( esc_html__( 'Security check failed', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		// Check capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'Insufficient permissions', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		$merchant_key = isset( $_POST['merchant_key'] ) ? sanitize_text_field( wp_unslash( $_POST['merchant_key'] ) ) : '';
		$user_email   = isset( $_POST['user_email'] ) ? sanitize_email( wp_unslash( $_POST['user_email'] ) ) : '';

		if ( empty( $merchant_key ) ) {
			wp_send_json_error( esc_html__( 'Invalid merchant key', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		// Save connection data.
		update_option( 'tryly_connected', true );
		update_option( 'tryly_merchant_key', $merchant_key );
		update_option( 'tryly_user_email', $user_email );
		delete_transient( 'tryly_settings_' . md5( $merchant_key ) );

		// Log connection event.
		$this->log_event( 'connected', array(
			'merchant_key' => $merchant_key,
			'user_email'   => $user_email,
		) );

		wp_send_json_success(
			array(
				'message' => esc_html__( 'Connected successfully!', 'tryly-ai-virtual-try-on-for-woocommerce' ),
			)
		);
	}

	/**
	 * AJAX handler for disconnection.
	 *
	 * @since 1.0.0
	 */
	public function ajax_disconnect() {
		// Verify nonce.
		if ( ! check_ajax_referer( 'tryly_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( esc_html__( 'Security check failed', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		// Check capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'Insufficient permissions', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		// Get merchant key before deleting
		$merchant_key = get_option( 'tryly_merchant_key' );

		// Log disconnection event.
		$this->log_event( 'disconnected', array(
			'merchant_key' => $merchant_key,
		) );

		// Clear the correct cache BEFORE deleting options
		if ( $merchant_key ) {
			delete_transient( 'tryly_settings_' . md5( $merchant_key ) );
		}

		// Clear connection data.
		update_option( 'tryly_connected', false );
		delete_option( 'tryly_merchant_key' );
		delete_option( 'tryly_user_email' );

		wp_send_json_success(
			array(
				'message' => esc_html__( 'Disconnected successfully', 'tryly-ai-virtual-try-on-for-woocommerce' ),
			)
		);
	}

	/**
	 * AJAX handler for checking connection.
	 *
	 * @since 1.0.0
	 */
	public function ajax_check_connection() {
		// Verify nonce.
		if ( ! check_ajax_referer( 'tryly_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( esc_html__( 'Security check failed', 'tryly-ai-virtual-try-on-for-woocommerce' ) );
		}

		$connected    = get_option( 'tryly_connected', false );
		$merchant_key = get_option( 'tryly_merchant_key', '' );

		wp_send_json_success(
			array(
				'connected'    => $connected,
				'merchant_key' => $connected ? $merchant_key : '',
			)
		);
	}

	/**
	 * Generate and return state token for OAuth
	 *
	 * @since 1.0.8
	 */
	public function ajax_get_state() {
		if ( ! check_ajax_referer( 'tryly_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( 'Security check failed' );
		}
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Insufficient permissions' );
		}
		
		$state = wp_generate_password( 32, false );
		set_transient( 'tryly_oauth_state_' . get_current_user_id(), $state, 600 );
		
		wp_send_json_success( array( 'state' => $state ) );
	}

	/**
	 * Log events to database.
	 *
	 * @since 1.0.0
	 * @param string $event_type Event type.
	 * @param array  $event_data Event data.
	 */
	private function log_event( $event_type, $event_data = array() ) {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'tryly_events';
		
		// Check if table exists before inserting.
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) === $table_name ) {
			$wpdb->insert(
				$table_name,
				array(
					'event_type' => $event_type,
					'event_data' => wp_json_encode( $event_data ),
				),
				array( '%s', '%s' )
			);
		}
	}
}