<?php
/**
 * Admin AJAX handlers for the Robots.txt Manager module.
 *
 * @package WP_PowerSuite\Core\Http\Controllers
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core\Http\Controllers;

use WP_PowerSuite\Core\Http\AjaxRouter;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;
use WP_PowerSuite\Core\RootTextFileHelper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class RobotsTxtController {

	private static ?self $instance = null;

	public static function getInstance(): self {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function register(): void {
		if ( ! OptionStoreModuleSettingsRepository::isModuleEnabled( 'robots-txt-manager' ) ) {
			return;
		}

		$controller = self::getInstance();
		$capability = NetworkScope::adminCapability();

		AjaxRouter::registerAdminAction( 'wp_powersuite_robots_txt_get', [ $controller, 'getContent' ], $capability );
		AjaxRouter::registerAdminAction( 'wp_powersuite_robots_txt_save', [ $controller, 'saveContent' ], $capability );
		AjaxRouter::registerAdminAction( 'wp_powersuite_robots_txt_backup', [ $controller, 'backupContent' ], $capability );
	}

	/**
	 * Module PHP files are not autoloaded during admin AJAX; require before use.
	 */
	private function getRobotsModule(): \RobotsTxtManager\Module {
		if ( ! class_exists( '\RobotsTxtManager\Module', false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			$module_file = WP_POWERSUITE_MODULES_DIR . 'robots-txt-manager' . DIRECTORY_SEPARATOR . 'module.php';
			if ( is_readable( $module_file ) ) {
				require_once $module_file;
			}
		}

		if ( ! class_exists( '\RobotsTxtManager\Module', false ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Robots.txt Manager module could not be loaded.', 'wp-powersuite' ),
					'code'    => 'module_not_found',
				]
			);
		}

		return new \RobotsTxtManager\Module();
	}

	public function getContent(): void {
		$mod = $this->getRobotsModule();
		if ( ! $mod->isEnabled() ) {
			wp_send_json_error( [ 'message' => __( 'Module is not enabled.', 'wp-powersuite' ) ] );
		}

		$content = $mod->getContent();
		if ( self::looksLikeHtml( $content ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Could not load robots.txt: received HTML instead of plain text. Load reads the file directly; check that robots.txt on disk is valid plain text.', 'wp-powersuite' ),
					'code'    => 'invalid_content_type',
				]
			);
		}

		wp_send_json_success( [ 'content' => $content ] );
	}

	public function saveContent(): void {
		$content = isset( $_POST['content'] ) ? wp_unslash( $_POST['content'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( ! is_string( $content ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid content.', 'wp-powersuite' ) ] );
		}

		$size_error = RootTextFileHelper::validateContentSize( $content );
		if ( $size_error !== null ) {
			wp_send_json_error( [ 'message' => $size_error ] );
		}

		$mod = $this->getRobotsModule();
		if ( ! $mod->isEnabled() ) {
			wp_send_json_error( [ 'message' => __( 'Module is not enabled.', 'wp-powersuite' ) ] );
		}

		$result = $mod->writeContent( $content );
		if ( empty( $result['success'] ) ) {
			wp_send_json_error(
				[
					'message' => $result['message'] ?? __( 'Could not write robots.txt.', 'wp-powersuite' ),
				]
			);
		}

		wp_send_json_success(
			[
				'message' => $result['message'] ?? __( 'Robots.txt saved.', 'wp-powersuite' ),
			]
		);
	}

	public function backupContent(): void {
		$mod = $this->getRobotsModule();
		if ( ! $mod->isEnabled() ) {
			wp_send_json_error( [ 'message' => __( 'Module is not enabled.', 'wp-powersuite' ) ] );
		}

		$result = $mod->createBackup();
		if ( empty( $result['success'] ) ) {
			wp_send_json_error(
				[
					'message' => $result['message'] ?? __( 'Could not create backup.', 'wp-powersuite' ),
				]
			);
		}

		wp_send_json_success( [ 'message' => $result['message'] ] );
	}

	private static function looksLikeHtml( string $content ): bool {
		$trimmed = ltrim( $content );
		if ( $trimmed === '' ) {
			return false;
		}

		return str_starts_with( $trimmed, '<!DOCTYPE' )
			|| str_starts_with( $trimmed, '<html' )
			|| str_starts_with( $trimmed, '<HTML' );
	}
}
