<?php
/**
 * HtaccessDashboardContributor — Registers .htaccess data into the dashboard registry.
 *
 * Called from HtaccessModule::boot(). Contributes:
 *   - Stat card : .htaccess Security Score
 *   - Status item: .htaccess Manager
 *   - Coverage bar: .htaccess
 *   - Quick tile : .htaccess
 *
 * @package UltraguardPro\modules\htaccess
 */

namespace UltraguardPro\modules\htaccess;

use UltraguardPro\Plugin;

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

class HtaccessDashboardContributor {

	private Plugin $plugin;

	public function __construct( Plugin $plugin ) {
		$this->plugin = $plugin;
	}

	public function register(): void {
		add_action( 'admin_init', [ $this, 'contribute' ], 20 );
	}

	public function contribute(): void {
		if ( ! \UltraguardPro\core\Admin::is_ultraguard_dashboard() ) { return; }

		$path    = ABSPATH . '.htaccess';
		$exists  = file_exists( $path );
		$content = $exists ? file_get_contents( $path ) : '';

		// Security score (0-100): 4 markers × 25 pts each.
		$score_markers = [
			'Options -Indexes',
			'X-Frame-Options',
			'X-Content-Type-Options',
			'BEGIN UltraGuard',
		];
		$score = 0;
		foreach ( $score_markers as $m ) {
			if ( str_contains( $content, $m ) ) {
				$score += 25;
			}
		}

		// Count enabled security features.
		$features = [
			'disable_directory_listing', 'protect_wp_config', 'protect_wp_includes',
			'protect_uploads_php',       'block_xmlrpc',       'security_headers',
			'block_hotlinking',          'block_author_scan',  'block_bad_bots',
			'prevent_script_injection',  'limit_file_access',
		];
		$enabled_count = 0;
		foreach ( $features as $f ) {
			if ( get_option( 'ultraguard_htaccess_feature_' . $f, false ) ) { $enabled_count++; }
		}
		$total_features = count( $features );

		// Backup count.
		$backup_dir   = trailingslashit( wp_upload_dir()['basedir'] ) . 'ultraguard-htaccess-backups/';
		$backup_files = is_dir( $backup_dir ) ? ( glob( $backup_dir . 'htaccess-*.txt' ) ?: [] ) : [];
		$backup_count = count( $backup_files );

		$writable = $exists && is_writable( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- direct writability check for dashboard status only.

		// ── Stat card: Security Score ─────────────────────────────────────────
//		do_action( 'ultraguard_dashboard_register_stat', [
//			'id'       => 'stat-htaccess-score',
//			'title'    => __( '.htaccess Score', 'ultraguard-security-suite' ),
//			'value'    => $score,
//			'format'   => 'number',
//			'icon'     => 'dashicons-media-code',
//			'class'    => $score >= 75 ? 'success' : ( $score >= 50 ? 'warning' : 'danger' ),
//			'animated' => true,
//			'priority'        => 40,
//			'span'            => 3,
//			'hide_when_empty' => false,
//		] );

		// ── Module status item ────────────────────────────────────────────────
		do_action( 'ultraguard_dashboard_register_status', [
			'id'      => 'status-htaccess',
			'icon'    => 'dashicons-media-code',
			'text'    => __( '.htaccess Manager', 'ultraguard-security-suite' ),
			'badge'   => [
				'text'       => $exists ? ( $writable ? __( 'Writable', 'ultraguard-security-suite' ) : __( 'Read-only', 'ultraguard-security-suite' ) ) : __( 'Missing', 'ultraguard-security-suite' ),
				'badge_type' => $exists ? ( $writable ? 'success' : 'warning' ) : 'danger',
			],
			'actions' => [ [ 'type' => 'button', 'text' => __( 'Manage', 'ultraguard-security-suite' ), 'button_style' => 'secondary','size'=>'small', 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess' ) ] ],
			'priority' => 40,
		] );

		// ── Coverage bar ──────────────────────────────────────────────────────
		do_action( 'ultraguard_dashboard_register_coverage', [
			'id'       => 'coverage-htaccess',
			'title'    => __( '.htaccess', 'ultraguard-security-suite' ),
			'value'    => $score,
			'max'      => 100,
			'status'   => $score >= 75 ? 'success' : ( $score >= 50 ? 'warning' : 'secondary' ),
			/* translators: %1$d: integer, %2$d: integer */
			'label'    => sprintf( __( '%1$d / %2$d rules active', 'ultraguard-security-suite' ), $enabled_count, $total_features ),
			'priority' => 40,
		] );

		// ── Quick tile ────────────────────────────────────────────────────────
		do_action( 'ultraguard_dashboard_register_tile', [
			'title'    => __( '.htaccess', 'ultraguard-security-suite' ),
			'icon'     => 'dashicons-media-code',
			/* translators: %d: integer */
			'content'  => $exists ? sprintf( __( '%d%% protected', 'ultraguard-security-suite' ), $score ) : __( 'File missing', 'ultraguard-security-suite' ),
			'footer'   => [ 'type' => 'button', 'text' => __( 'Open', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess' ) ],
			'priority' => 40,
		] );

		// ── Extra stat: Backup count ──────────────────────────────────────────
		if ( $backup_count > 0 ) {
			do_action( 'ultraguard_dashboard_register_stat', [
				'id'              => 'stat-htaccess-backups',
				'title'           => __( '.htaccess Backups', 'ultraguard-security-suite' ),
				'value'           => $backup_count,
				'format'          => 'number',
				'icon'            => 'dashicons-backup',
				'class'           => 'info',
				'animated'        => false,
				'priority'        => 41,
				'span'            => 3,
				'hide_when_empty' => true,
			] );
		}
	}
}
