<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Arcai_Admin {

	private $indexer;

	public function __construct( Arcai_Indexer $indexer ) {
		$this->indexer = $indexer;
	}

	public function register_hooks() {
		add_action( 'admin_menu', array( $this, 'add_menu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_arcai_estimate_index', array( $this, 'ajax_estimate' ) );
		add_action( 'wp_ajax_arcai_start_index', array( $this, 'ajax_start' ) );
		add_action( 'wp_ajax_arcai_index_status', array( $this, 'ajax_status' ) );
		add_action( 'wp_ajax_arcai_cancel_index', array( $this, 'ajax_cancel' ) );
	}

	public function add_menu() {
		add_menu_page(
			__( 'Archivist AI', 'archivist-ai' ),
			__( 'Archivist AI', 'archivist-ai' ),
			'manage_options',
			'archivist-ai',
			array( $this, 'render_page' ),
			'dashicons-format-chat',
			58
		);
	}

	public function register_settings() {
		register_setting(
			'arcai_settings_group',
			Arcai_Settings::OPTION,
			array( 'sanitize_callback' => array( 'Arcai_Settings', 'sanitize' ) )
		);
	}

	public function enqueue_assets( $hook ) {
		if ( 'toplevel_page_archivist-ai' !== $hook ) {
			return;
		}
		wp_enqueue_style( 'arcai-admin', ARCAI_PLUGIN_URL . 'assets/css/admin.css', array(), ARCAI_VERSION );
		wp_enqueue_script( 'arcai-admin', ARCAI_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), ARCAI_VERSION, true );
		wp_localize_script(
			'arcai-admin',
			'arcaiAdmin',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'arcai_admin' ),
				'i18n'    => array(
					/* translators: 1: number of posts, 2: token count, 3: estimated cost in USD. */
					'confirmIndex' => __( 'Indexing %1$s posts will use roughly %2$s tokens. Estimated cost: %3$s. Continue?', 'archivist-ai' ),
					'error'        => __( 'Request failed. Please try again.', 'archivist-ai' ),
				),
			)
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = Arcai_Settings::all();
		$state    = $this->indexer->get_state();
		$usage    = Arcai_Usage::summary( 30 );
		$today    = Arcai_Usage::cost_today();
		?>
		<div class="wrap arcai-wrap">
			<h1><?php esc_html_e( 'Archivist AI', 'archivist-ai' ); ?></h1>

			<div class="arcai-columns">
			<div class="arcai-main">

			<h2><?php esc_html_e( 'Settings', 'archivist-ai' ); ?></h2>
			<form method="post" action="options.php">
				<?php settings_fields( 'arcai_settings_group' ); ?>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><label for="arcai-api-key"><?php esc_html_e( 'OpenAI API key', 'archivist-ai' ); ?></label></th>
						<td>
							<input type="password" id="arcai-api-key" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[api_key]" value="<?php echo esc_attr( $settings['api_key'] ); ?>" class="regular-text" autocomplete="off" />
							<p class="description"><?php esc_html_e( 'One key covers both indexing (embeddings) and answers. You pay OpenAI directly at list price.', 'archivist-ai' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Post types to index', 'archivist-ai' ); ?></th>
						<td>
							<?php foreach ( get_post_types( array( 'public' => true ), 'objects' ) as $type ) : ?>
								<?php if ( 'attachment' === $type->name ) { continue; } ?>
								<label style="margin-right:16px">
									<input type="checkbox" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[post_types][]" value="<?php echo esc_attr( $type->name ); ?>" <?php checked( in_array( $type->name, (array) $settings['post_types'], true ) ); ?> />
									<?php echo esc_html( $type->labels->name ); ?>
								</label>
							<?php endforeach; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-daily-cap"><?php esc_html_e( 'Daily spending cap (USD)', 'archivist-ai' ); ?></label></th>
						<td>
							<input type="number" step="0.5" min="0" id="arcai-daily-cap" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[daily_cap]" value="<?php echo esc_attr( $settings['daily_cap'] ); ?>" class="small-text" />
							<p class="description"><?php esc_html_e( 'When reached, the AI chat pauses until midnight. 0 disables the cap.', 'archivist-ai' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-rate-limit"><?php esc_html_e( 'Visitor rate limit (chat turns / hour / IP)', 'archivist-ai' ); ?></label></th>
						<td><input type="number" min="1" id="arcai-rate-limit" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[rate_limit]" value="<?php echo esc_attr( $settings['rate_limit'] ); ?>" class="small-text" /></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Chat bubble', 'archivist-ai' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[bubble_enabled]" value="1" <?php checked( $settings['bubble_enabled'] ); ?> />
								<?php esc_html_e( 'Show the floating chat bubble on the site', 'archivist-ai' ); ?>
							</label>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-bubble-color"><?php esc_html_e( 'Bubble color', 'archivist-ai' ); ?></label></th>
						<td><input type="color" id="arcai-bubble-color" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[bubble_color]" value="<?php echo esc_attr( $settings['bubble_color'] ); ?>" /></td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-greeting"><?php esc_html_e( 'Greeting message', 'archivist-ai' ); ?></label></th>
						<td><input type="text" id="arcai-greeting" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[greeting]" value="<?php echo esc_attr( $settings['greeting'] ); ?>" class="regular-text" /></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Subscriber-only mode', 'archivist-ai' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[require_login]" value="1" <?php checked( $settings['require_login'] ); ?> <?php disabled( ! arcai_is_pro() ); ?> />
								<?php esc_html_e( 'Restrict the chat to logged-in users', 'archivist-ai' ); ?>
							</label>
							<?php if ( ! arcai_is_pro() ) : ?>
								<p class="description">
									<a href="<?php echo esc_url( arcai_fs()->get_upgrade_url() ); ?>"><?php esc_html_e( 'Upgrade to Pro', 'archivist-ai' ); ?></a>
									<?php esc_html_e( 'to turn the AI chat into a premium perk for your subscribers.', 'archivist-ai' ); ?>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-chat-model"><?php esc_html_e( 'Answer model', 'archivist-ai' ); ?></label></th>
						<td><input type="text" id="arcai-chat-model" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[chat_model]" value="<?php echo esc_attr( $settings['chat_model'] ); ?>" class="regular-text" /></td>
					</tr>
					<tr>
						<th scope="row"><label for="arcai-embedding-model"><?php esc_html_e( 'Embedding model', 'archivist-ai' ); ?></label></th>
						<td><input type="text" id="arcai-embedding-model" name="<?php echo esc_attr( Arcai_Settings::OPTION ); ?>[embedding_model]" value="<?php echo esc_attr( $settings['embedding_model'] ); ?>" class="regular-text" /></td>
					</tr>
				</table>
				<?php submit_button(); ?>
			</form>

			<hr />

			<h2><?php esc_html_e( 'Indexing', 'archivist-ai' ); ?></h2>
			<p>
				<?php
				printf(
					/* translators: 1: indexed post count, 2: free cap */
					esc_html__( 'Indexed posts: %1$s (free version indexes the %2$s most recent posts).', 'archivist-ai' ),
					'<strong id="arcai-indexed-count">' . esc_html( $state['indexed_posts'] ) . '</strong>',
					esc_html( number_format_i18n( ARCAI_FREE_POST_CAP ) )
				);
				?>
			</p>
			<p>
				<button type="button" class="button button-primary" id="arcai-index-btn" <?php disabled( 'running' === $state['status'] ); ?>>
					<?php esc_html_e( 'Estimate cost & index all posts', 'archivist-ai' ); ?>
				</button>
				<button type="button" class="button" id="arcai-cancel-btn" <?php disabled( 'running' !== $state['status'] ); ?>>
					<?php esc_html_e( 'Cancel', 'archivist-ai' ); ?>
				</button>
			</p>
			<div id="arcai-progress" data-status="<?php echo esc_attr( $state['status'] ); ?>">
				<div class="arcai-progress-bar"><span style="width:<?php echo esc_attr( $state['total'] ? round( 100 * $state['done'] / $state['total'] ) : 0 ); ?>%"></span></div>
				<p class="arcai-progress-text"></p>
			</div>

			</div>

			<div class="arcai-side">
				<h2><?php esc_html_e( 'Usage (last 30 days)', 'archivist-ai' ); ?></h2>
				<?php if ( ! arcai_is_pro() ) : ?>
				<div class="arcai-upsell">
					<p><?php esc_html_e( 'See exactly what your AI search spends — per day, per month, broken down by indexing and chat.', 'archivist-ai' ); ?></p>
					<p><a class="button button-primary" href="<?php echo esc_url( arcai_fs()->get_upgrade_url() ); ?>"><?php esc_html_e( 'Upgrade to Pro', 'archivist-ai' ); ?></a></p>
				</div>
				<?php else : ?>
				<p>
					<?php
					printf(
						/* translators: %s: dollar amount */
						esc_html__( 'Spent today: %s', 'archivist-ai' ),
						'<strong>$' . esc_html( number_format_i18n( $today, 4 ) ) . '</strong>'
					);
					?>
				</p>
				<table class="widefat striped">
					<thead><tr>
						<th><?php esc_html_e( 'Type', 'archivist-ai' ); ?></th>
						<th><?php esc_html_e( 'Events', 'archivist-ai' ); ?></th>
						<th><?php esc_html_e( 'Cost', 'archivist-ai' ); ?></th>
					</tr></thead>
					<tbody>
					<?php if ( empty( $usage ) ) : ?>
						<tr><td colspan="3"><?php esc_html_e( 'No usage yet.', 'archivist-ai' ); ?></td></tr>
					<?php else : ?>
						<?php foreach ( $usage as $row ) : ?>
							<tr>
								<td><?php echo esc_html( $row->event_type ); ?></td>
								<td><?php echo esc_html( number_format_i18n( $row->events ) ); ?></td>
								<td>$<?php echo esc_html( number_format_i18n( (float) $row->cost, 4 ) ); ?></td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
					</tbody>
				</table>
				<?php endif; ?>
			</div>
			</div>
		</div>
		<?php
	}

	private function verify_ajax() {
		if ( ! current_user_can( 'manage_options' ) || ! check_ajax_referer( 'arcai_admin', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'archivist-ai' ) ), 403 );
		}
	}

	public function ajax_estimate() {
		$this->verify_ajax();
		wp_send_json_success( $this->indexer->estimate() );
	}

	public function ajax_start() {
		$this->verify_ajax();
		$result = $this->indexer->start();
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}
		wp_send_json_success( $this->indexer->get_state() );
	}

	public function ajax_status() {
		$this->verify_ajax();
		$state = $this->indexer->get_state();
		if ( 'running' === $state['status'] ) {
			$this->indexer->process_batch();
			$state = $this->indexer->get_state();
		}
		wp_send_json_success( $state );
	}

	public function ajax_cancel() {
		$this->verify_ajax();
		$this->indexer->cancel();
		wp_send_json_success( $this->indexer->get_state() );
	}
}
