<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

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

use Wisewand\Utils\Options;
use Wisewand\Utils\Wisewand_API_Client;
use Wisewand\Logging\Logger;
use Wisewand\Admin\Traits\AJAX_Security;

class Wisewand_API_Settings_Page {

	use AJAX_Security;

	private $options;
	private $logger;

	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;

		// Ensure Wisewand_API_Client class is available
		if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
			$api_client_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			if ( file_exists( $api_client_file ) ) {
				require_once $api_client_file;
			}
		}
	}

	/**
	 * Enqueue scripts and styles for the API Settings page.
	 *
	 * @since 1.0.0
	 */
	private function enqueue_assets() {
		// Enqueue the API settings admin JavaScript
		wp_enqueue_script(
			'wisewand-api-settings-admin',
			WISEWAND_PLUGIN_URL . 'assets/js/admin/wisewand-api-settings-admin.js',
			array( 'jquery' ),
			WISEWAND_PLUGIN_VERSION,
			true
		);

		// Localize script with i18n strings and nonces
		wp_localize_script(
			'wisewand-api-settings-admin',
			'wisewandApiSettings',
			array(
				'i18n'          => array(
					'testing'           => __( 'Testing...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'connectionSuccess' => __( 'API connection successful!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'connectionFailed'  => __( 'API connection failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'networkError'      => __( 'Network error occurred while testing API connection.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'connected'         => __( 'Connected', 'wisewand-ai-content-writer-seo-content-generator' ),
					'error'             => __( 'Error', 'wisewand-ai-content-writer-seo-content-generator' ),
					'rateLimit'         => __( 'Rate Limit:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'availableArticles' => __( 'Available Articles:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'projects'          => __( 'Projects:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'detailedSuccess'   => __( 'Detailed API test completed successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'runDetailedTest'   => __( 'Run Detailed Test', 'wisewand-ai-content-writer-seo-content-generator' ),
					'confirmRemove'     => __( 'Are you sure you want to remove the API key? This will disconnect your WordPress site from Wisewand.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'removeFailed'      => __( 'Failed to remove API key:', 'wisewand-ai-content-writer-seo-content-generator' ),
				),
				'nonce'         => wp_create_nonce( 'wisewand_api_test' ),
				'nonceDetailed' => wp_create_nonce( 'wisewand_api_detailed_test' ),
				'nonceRemove'   => wp_create_nonce( 'wisewand_api_remove' ),
			)
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		// Enqueue assets for this page
		$this->enqueue_assets();

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified inside handle_form_submission() via check_admin_referer()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_form_submission();
		}

		echo '<div class="wrap wisewand-api-settings">';
		echo '<h1>' . esc_html__( 'Wisewand API Settings', 'wisewand-ai-content-writer-seo-content-generator' ) . '</h1>';

		settings_errors( 'wisewand_api_settings' );

		$this->render_api_configuration();
		$this->render_api_test_section();

		echo '</div>';
	}

	private function render_api_configuration() {
		$api_key       = Wisewand_API_Client::get_stored_api_key();
		$masked_key    = Wisewand_API_Client::get_masked_api_key();
		$is_configured = Wisewand_API_Client::is_api_key_configured();

		?>
		<div class="wisewand-form-section">
			<h2><?php esc_html_e( 'API Authentication', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>

			<form method="post" action="">
				<?php wp_nonce_field( 'wisewand_api_settings' ); ?>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="wisewand_api_key"><?php esc_html_e( 'Wisewand API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</th>
						<td>
							<input type="password"
									id="wisewand_api_key"
									name="wisewand_api_key"
									value="<?php echo esc_attr( $api_key ); ?>"
									class="regular-text"
									placeholder="<?php esc_html_e( 'Enter your Wisewand API key...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />

							<?php if ( $is_configured ) : ?>
							<br><small class="wisewand-key-info">
								<?php esc_html_e( 'Current key:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <code><?php echo esc_html( $masked_key ); ?></code>
								<button type="button" class="button-link" id="toggle-api-key">
									<?php esc_html_e( 'Show/Hide', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</button>
							</small>
							<?php endif; ?>

							<p class="description">
								<?php esc_html_e( 'Your Wisewand API key for authenticating requests. Get your API key from your Wisewand dashboard.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<br>
								<strong><?php esc_html_e( 'Security:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
								<?php esc_html_e( 'Your API key is stored securely in the WordPress database and never transmitted in plain text logs.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<label for="wisewand_api_base_url"><?php esc_html_e( 'API Base URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</th>
						<td>
							<input type="url"
									id="wisewand_api_base_url"
									name="wisewand_api_base_url"
									value="<?php echo esc_attr( $this->options->get( 'wisewand_api_base_url', 'https://api.wisewand.ai' ) ); ?>"
									class="regular-text" />
							<p class="description">
								<?php esc_html_e( 'Wisewand API base URL. Only change this if instructed by Wisewand support.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<label for="wisewand_api_timeout"><?php esc_html_e( 'API Timeout (seconds)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</th>
						<td>
							<input type="number"
									id="wisewand_api_timeout"
									name="wisewand_api_timeout"
									value="<?php echo esc_attr( $this->options->get( 'wisewand_api_timeout', 30 ) ); ?>"
									min="10" max="300" class="small-text" />
							<p class="description">
								<?php esc_html_e( 'Timeout for API requests. Increase if you experience timeout errors.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>

					<tr>
						<th scope="row">
							<label for="wisewand_openai_api_key">🤖 <?php esc_html_e( 'OpenAI API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</th>
						<td>
							<?php
							$openai_key        = get_option( 'wisewand_openai_api_key', '' );
							$openai_configured = ! empty( $openai_key ) && strlen( $openai_key ) > 20;
							$openai_masked     = $openai_configured ? substr( $openai_key, 0, 7 ) . '...' . substr( $openai_key, -4 ) : '';
							?>
							<input type="password"
									id="wisewand_openai_api_key"
									name="wisewand_openai_api_key"
									value="<?php echo esc_attr( $openai_key ); ?>"
									class="regular-text"
									placeholder="<?php esc_html_e( 'sk-proj-...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />

							<?php if ( $openai_configured ) : ?>
							<br><small class="openai-key-info">
								<?php esc_html_e( 'Current key:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <code><?php echo esc_html( $openai_masked ); ?></code>
								<button type="button" class="button-link" id="toggle-openai-key">
									<?php esc_html_e( 'Show/Hide', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</button>
							</small>
							<?php endif; ?>

							<p class="description">
								<strong>🤖 <?php esc_html_e( 'AI-Powered Category Matching', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
								<?php esc_html_e( 'Enable AI to automatically match keywords to WordPress categories using GPT-5.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<br>
								<?php esc_html_e( 'Get your API key from:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <a href="https://platform.openai.com/api-keys" target="_blank">platform.openai.com/api-keys</a>
								<br>
								<strong><?php esc_html_e( 'Model:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> gpt-5 (temperature: 0.3 for consistent results)
								<br>
								<strong><?php esc_html_e( 'Cost:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> ~$0.25 per 1,000 keywords
							</p>
						</td>
					</tr>
				</table>

				<div class="wisewand-api-actions">
					<?php submit_button( __( 'Save API Settings', 'wisewand-ai-content-writer-seo-content-generator' ), 'primary', 'submit', false ); ?>

					<?php if ( $is_configured ) : ?>
					<button type="button" class="button button-secondary" id="test-api-connection">
						<?php esc_html_e( 'Test Connection', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<button type="button" class="button button-link-delete" id="remove-api-key">
						<?php esc_html_e( 'Remove API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<?php endif; ?>
				</div>
			</form>
		</div>
		<?php
	}

	private function render_api_test_section() {
		$is_configured = Wisewand_API_Client::is_api_key_configured();

		if ( ! $is_configured ) {
			return;
		}

		?>
		<div class="wisewand-form-section">
			<h2><?php esc_html_e( 'API Connection Test', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>

			<div id="wisewand-api-test-results" style="display: none;">
				<!-- Results will be populated via AJAX -->
			</div>

			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Connection Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<td>
						<span id="connection-status" class="wisewand-status-unknown">
							<?php esc_html_e( 'Not tested', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</span>
						<button type="button" class="button button-secondary" id="test-api-detailed">
							<?php esc_html_e( 'Run Detailed Test', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</button>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'API Information', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
					<td>
						<div id="api-info">
							<em><?php esc_html_e( 'Click "Run Detailed Test" to fetch API information', 'wisewand-ai-content-writer-seo-content-generator' ); ?></em>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<?php
	}

	private function handle_form_submission() {
		check_admin_referer( 'wisewand_api_settings' );

		if ( ! current_user_can( 'manage_options' ) ) {
			add_settings_error(
				'wisewand_api_settings',
				'insufficient_permissions',
				__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ),
				'error'
			);
			return;
		}

		// Handle API key
		$api_key = isset( $_POST['wisewand_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_api_key'] ) ) : '';

		if ( ! empty( $api_key ) ) {
			$store_result = Wisewand_API_Client::store_api_key( $api_key );

			if ( is_wp_error( $store_result ) ) {
				add_settings_error(
					'wisewand_api_settings',
					'invalid_api_key',
					$store_result->get_error_message(),
					'error'
				);
				return;
			}

			// Test the API key
			$api_client  = new Wisewand_API_Client( $api_key, $this->logger );
			$test_result = $api_client->validate_api_key();

			if ( is_wp_error( $test_result ) ) {
				add_settings_error(
					'wisewand_api_settings',
					'api_key_test_failed',
					sprintf(
						/* translators: %s: Error message describing why the API connection test failed */
						__( 'API key saved but connection test failed: %s', 'wisewand-ai-content-writer-seo-content-generator' ),
						$test_result->get_error_message()
					),
					'error'
				);
			} else {
				add_settings_error(
					'wisewand_api_settings',
					'api_key_saved',
					__( 'API key saved and validated successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'updated'
				);

				$this->logger->info( 'Wisewand API key configured successfully' );

				// Invalidate project brief cache so migration validation uses fresh data.
				delete_transient( 'wisewand_project_brief' );
				wp_cache_delete( 'wisewand_project_brief', 'wisewand' );
			}
		} else {
			// Remove API key if empty
			Wisewand_API_Client::remove_api_key();
			add_settings_error(
				'wisewand_api_settings',
				'api_key_removed',
				__( 'API key removed', 'wisewand-ai-content-writer-seo-content-generator' ),
				'updated'
			);
		}

		// Handle OpenAI API key
		$openai_key = isset( $_POST['wisewand_openai_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_openai_api_key'] ) ) : '';

		if ( ! empty( $openai_key ) ) {
			update_option( 'wisewand_openai_api_key', $openai_key );

			add_settings_error(
				'wisewand_api_settings',
				'openai_key_saved',
				__( '🤖 OpenAI API key saved successfully! AI category matching is now enabled.', 'wisewand-ai-content-writer-seo-content-generator' ),
				'updated'
			);

			$this->logger->info( 'OpenAI API key configured' );
		} elseif ( isset( $_POST['wisewand_openai_api_key'] ) ) {
			// Remove if explicitly cleared
			delete_option( 'wisewand_openai_api_key' );
			add_settings_error(
				'wisewand_api_settings',
				'openai_key_removed',
				__( 'OpenAI API key removed', 'wisewand-ai-content-writer-seo-content-generator' ),
				'updated'
			);
		}

		// Handle other settings
		$this->options->set(
			'wisewand_api_base_url',
			isset( $_POST['wisewand_api_base_url'] ) ? esc_url_raw( wp_unslash( $_POST['wisewand_api_base_url'] ) ) : 'https://api.wisewand.ai'
		);
		$this->options->set(
			'wisewand_api_timeout',
			absint( $_POST['wisewand_api_timeout'] ?? 30 )
		);
	}

	public function ajax_test_api_connection() {
		$this->verify_ajax_request( 'wisewand_api_test', 'manage_options' );

		$api_key = Wisewand_API_Client::get_stored_api_key();

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'No API key configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$api_client = new Wisewand_API_Client( $api_key, $this->logger );
		$result     = $api_client->test_connection();

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

		wp_send_json_success(
			array(
				'message'            => __( 'API connection successful', 'wisewand-ai-content-writer-seo-content-generator' ),
				'articles_available' => count( $result['items'] ?? array() ),
			)
		);
	}

	public function ajax_detailed_api_test() {
		$this->verify_ajax_request( 'wisewand_api_detailed_test', 'manage_options' );

		$api_key = Wisewand_API_Client::get_stored_api_key();

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'No API key configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$api_client = new Wisewand_API_Client( $api_key, $this->logger );

		// Test multiple endpoints
		$test_results    = array();
		$overall_success = true;

		// Test 1: Basic connection
		$articles_result = $api_client->list_articles( array( 'take' => 1 ) );
		if ( is_wp_error( $articles_result ) ) {
			$test_results['articles'] = array(
				'success' => false,
				'error'   => $articles_result->get_error_message(),
			);
			$overall_success          = false;
		} else {
			$test_results['articles'] = array(
				'success' => true,
				'count'   => $articles_result['count'] ?? 0,
			);
		}

		// Test 2: Projects
		$projects_result = $api_client->list_projects( array( 'take' => 1 ), true );
		if ( is_wp_error( $projects_result ) ) {
			$test_results['projects'] = array(
				'success' => false,
				'error'   => $projects_result->get_error_message(),
			);
			$overall_success          = false;
		} else {
			$test_results['projects'] = array(
				'success' => true,
				'count'   => $projects_result['count'] ?? 0,
			);
		}

		// Test 3: Personas
		$personas_result = $api_client->list_personas( array( 'take' => 1 ), true );
		if ( is_wp_error( $personas_result ) ) {
			$test_results['personas'] = array(
				'success' => false,
				'error'   => $personas_result->get_error_message(),
			);
			$overall_success          = false;
		} else {
			$test_results['personas'] = array(
				'success' => true,
				'count'   => $personas_result['count'] ?? 0,
			);
		}

		if ( $overall_success ) {
			wp_send_json_success(
				array(
					'message'        => __( 'All API tests passed', 'wisewand-ai-content-writer-seo-content-generator' ),
					'rate_limit'     => '60 requests per minute',
					'articles_count' => $test_results['articles']['count'],
					'projects_count' => $test_results['projects']['count'],
					'personas_count' => $test_results['personas']['count'],
					'test_results'   => $test_results,
				)
			);
		} else {
			wp_send_json_error(
				array(
					'message'      => __( 'Some API tests failed', 'wisewand-ai-content-writer-seo-content-generator' ),
					'test_results' => $test_results,
				)
			);
		}
	}

	public function ajax_remove_api_key() {
		$this->verify_ajax_request( 'wisewand_api_remove', 'manage_options' );

		$result = Wisewand_API_Client::remove_api_key();

		if ( $result ) {
			$this->logger->info( 'Wisewand API key removed' );
			wp_send_json_success( array( 'message' => __( 'API key removed successfully', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to remove API key', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}
	}
}