<?php

namespace WPConfigEditor;

use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\WpConfigHelper;

class Module extends AbstractModule {

	private const MODULE_ID = 'wp-config-editor';
	private const MODULE_VERSION = '1.0.0';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'WP Config Editor', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Edit wp-config.php in the admin with backup-before-save safeguards.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin' ];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		// UI and AJAX only; no hooks.
	}

	/**
	 * Get path to wp-config.php.
	 *
	 * @return string|null Path or null if not found.
	 */
	public function getConfigPath(): ?string {
		return WpConfigHelper::resolveConfigPath();
	}

	/**
	 * Check if wp-config.php is writable.
	 */
	public function isConfigWritable(): bool {
		$path = $this->getConfigPath();
		return $path && is_writable( $path );
	}

	/**
	 * Get wp-config.php content.
	 *
	 * @return string|false Content or false on failure.
	 */
	public function getConfigContent(): string|false {
		$path = $this->getConfigPath();
		if ( ! $path ) {
			return false;
		}

		$read = WpConfigHelper::readFileContents( $path );
		return $read['success'] ? $read['content'] : false;
	}

	/**
	 * Create backup of wp-config.php in private storage.
	 *
	 * @return string|false Backup file path or false on failure.
	 */
	public function createBackup(): string|false {
		$path = $this->getConfigPath();
		if ( ! $path ) {
			return false;
		}

		return WpConfigHelper::createSecureBackup( $path, 'editor' );
	}

	/**
	 * Write content to wp-config.php. Caller must create backup first.
	 *
	 * @param string $content Raw file content.
	 * @return bool True on success.
	 */
	public function writeConfig( string $content ): bool {
		$path = $this->getConfigPath();
		if ( ! $path ) {
			return false;
		}

		$result = WpConfigHelper::writeValidatedConfig( $path, $content );
		return $result['success'];
	}

	/**
	 * Write content to wp-config.php with validation error detail.
	 *
	 * @return array{success: bool, message: string}
	 */
	public function writeConfigWithMessage( string $content ): array {
		$path = $this->getConfigPath();
		if ( ! $path ) {
			return [
				'success' => false,
				'message' => __( 'wp-config.php not found.', 'wp-powersuite' ),
			];
		}

		return WpConfigHelper::writeValidatedConfig( $path, $content );
	}
}
