<?php
/**
 * Admin AJAX handlers for the Ads.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;

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

final class AdsTxtController {

	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( 'ads-txt-manager' ) ) {
			return;
		}

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

		AjaxRouter::registerAdminAction( 'wp_powersuite_ads_txt_backup', [ $controller, 'backupContent' ], $capability );
	}

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

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

		return new \AdsTxtManager\Module();
	}

	public function backupContent(): void {
		$mod = $this->getAdsModule();
		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'] ] );
	}
}
