<?php
/**
 * HtaccessChangeLog — Audit trail subpage showing every .htaccess write.
 *
 * Displays a sortable/searchable table of all changes recorded by the
 * HtaccessChangeLogTable, plus integrity-check controls and export.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

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

class HtaccessChangeLog extends BasePage {

	public function __construct( Plugin $plugin ) {
		parent::__construct( $plugin );
	}

	public function get_scheme( $context ): array {
		$db      = $this->plugin->modules->get_db_tables();
		$table   = $db ? $db->get_table( 'htaccess_change_log' ) : null;

		$total         = $table ? $table->count()            : 0;
		$recent_7days  = $table ? $table->count_recent( 7 )  : 0;
		$recent_30days = $table ? $table->count_recent( 30 ) : 0;

		$rows = $table ? $table->get_recent( 100 ) : [];
		$data = array_map( function( $r ) {
			$id = (int) ( $r['id'] ?? 0 );

			$view_modal = [
				'id'      => 'htcl-view-' . $id,
				/* translators: %d: integer */
				'title'   => sprintf( __( 'Change Log Entry #%d', 'ultraguard-security-suite' ), $id ),
				'size'    => 'medium',
				'content' => $this->modal_content( [
					[ 'type' => 'text', 'name' => 'vcl_user',    'label' => __( 'User',         'ultraguard-security-suite' ), 'value' => esc_html( $r['user_login']    ?: __( 'System', 'ultraguard-security-suite' ) ),                         'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_reason',  'label' => __( 'Reason',        'ultraguard-security-suite' ), 'value' => esc_html( ucwords( str_replace( '_', ' ', $r['change_reason'] ?? '' ) ) ),                   'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_feature', 'label' => __( 'Feature Key',   'ultraguard-security-suite' ), 'value' => esc_html( $r['feature_key']  ?? '—' ),                                                        'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_size',    'label' => __( 'File Size',     'ultraguard-security-suite' ), 'value' => esc_html( $this->format_file_size( (int) ( $r['file_size'] ?? 0 ) ) ),                        'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_hash',    'label' => __( 'SHA-256 Hash',  'ultraguard-security-suite' ), 'value' => esc_html( $r['content_hash']  ?? '' ),                                                        'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_backup',  'label' => __( 'Backup Path',   'ultraguard-security-suite' ), 'value' => esc_html( $r['backup_path']   ?? __( '— no backup taken', 'ultraguard-security-suite' ) ),               'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_ip',      'label' => __( 'IP Address',    'ultraguard-security-suite' ), 'value' => esc_html( $r['ip_address']    ?? '—' ),                                                        'readonly' => true ],
					[ 'type' => 'text', 'name' => 'vcl_dt',      'label' => __( 'Date / Time',   'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),                                'readonly' => true ],
				] ),
			];

			return [
				'id'           => 'ug-htaccess-changelog-row-' . $id,
				'data-row-id'   => $id,
				'user_login'    => esc_html( $r['user_login']    ?: __( 'System', 'ultraguard-security-suite' ) ),
				'change_reason' => [
					'content' => esc_html( ucwords( str_replace( '_', ' ', $r['change_reason'] ?? '' ) ) ),
					'class'   => $this->reason_badge_class( $r['change_reason'] ?? '' ),
				],
				'feature_key'   => esc_html( $r['feature_key'] ?? '—' ),
				'file_size'     => esc_html( $this->format_file_size( (int) ( $r['file_size'] ?? 0 ) ) ),
				'content_hash'  => [
					'content' => esc_html( substr( $r['content_hash'] ?? '', 0, 12 ) . '…' ),
					'title'   => esc_attr( $r['content_hash'] ?? '' ),
					'class'   => 'monospace',
				],
				'ip_address'    => esc_html( $r['ip_address'] ?? '—' ),
				'created_at'    => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
				'actions'       => $this->row_actions( [
					[
						'type'         => 'button',
						'text'         => '',
						'icon'         => 'dashicons-visibility',
						'button_style' => 'secondary',
						'title'        => __( 'View full details', 'ultraguard-security-suite' ),
						'modal'        => $view_modal,
					],
					[
						'type'         => 'button',
						'text'         => '',
						'icon'         => 'dashicons-trash',
						'button_style' => 'danger',
						'title'        => __( 'Delete log entry', 'ultraguard-security-suite' ),
						'ajax'         => [
							'action'  => 'ultraguard_delete_htaccess_log_entry',
							'data'    => [ 'log_id' => $id ],
							'confirm' => __( 'Delete this change log entry?', 'ultraguard-security-suite' ),
						],
					],
				] ),
			];
		}, $rows );

		// Chart: daily changes over the last 14 days.
		$chart = $table
			? $table->get_chart_data( 'created_at', 'id', 'day', [], 14 )
			: [ 'labels' => [], 'data' => [] ];

		// Integrity status.
		$integrity = $table ? $table->verify_integrity() : null;

		return apply_filters( 'ultraguard_htaccess_change_log_scheme', [
			'type'      => 'page',
			'id'        => 'ultraguard-htaccess-change-log',
			'page_slug' => 'htaccess-change-log',
			'class'     => 'ultraguard-htaccess-change-log-page',

			'header' => [
				'title'    => __( 'Change Log', 'ultraguard-security-suite' ),
				'subtitle' => __( 'Immutable audit trail of every .htaccess write — who changed it, when, and why', 'ultraguard-security-suite' ),
				'badge'    => [
					/* translators: %d: number */
					'text'       => sprintf( _n( '%d Entry', '%d Entries', $total, 'ultraguard-security-suite' ), $total ),
					'badge_type' => $total > 0 ? 'info' : 'secondary',
				],
				'actions' => [
					$this->create_ajax_button( __( 'Verify Integrity',   'ultraguard-security-suite' ), 'ultraguard_verify_htaccess_integrity',  [], 'secondary', 'dashicons-shield'   ),
					$this->create_ajax_button( __( 'Export Log (CSV)',   'ultraguard-security-suite' ), 'ultraguard_export_htaccess_change_log', [], 'secondary', 'dashicons-download' ),
					$this->create_ajax_button( __( 'Refresh',            'ultraguard-security-suite' ), 'ultraguard_get_htaccess_change_log',    [], 'secondary', 'dashicons-update'   ),
				],
			],

			'data' => [
				// ── Stat row ──────────────────────────────────────────────────
				[
					'type'    => 'grid',
					'columns' => 12,
					'gap'     => '16px',
					'items'   => [
						[ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Changes',     'ultraguard-security-suite' ), 'value' => $total,         'format' => 'number', 'icon' => 'dashicons-edit',    'class' => 'info'      ] ],
						[ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last 7 Days',       'ultraguard-security-suite' ), 'value' => $recent_7days,  'format' => 'number', 'icon' => 'dashicons-clock',   'class' => $recent_7days  > 5 ? 'warning' : 'success' ] ],
						[ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last 30 Days',      'ultraguard-security-suite' ), 'value' => $recent_30days, 'format' => 'number', 'icon' => 'dashicons-calendar','class' => 'secondary' ] ],
						[ 'span' => 3, 'component' => [
							'type'   => 'stat-card',
							'title'  => __( 'Integrity', 'ultraguard-security-suite' ),
							'value'  => is_array( $integrity )
								? ( $integrity['match'] ? __( 'Verified', 'ultraguard-security-suite' ) : __( 'Mismatch', 'ultraguard-security-suite' ) )
								: __( 'Unknown', 'ultraguard-security-suite' ),
							'format' => 'text',
							'icon'   => 'dashicons-shield-alt',
							'class'  => is_array( $integrity )
								? ( $integrity['match'] ? 'success' : 'danger' )
								: 'secondary',
						] ],
					],
				],

				// ── Integrity alert ───────────────────────────────────────────
				...( ( is_array( $integrity ) && ! $integrity['match'] ) ? [ [
					'type'       => 'alert-box',
					'alert_type' => 'danger',
					'icon'       => 'dashicons-warning',
					'message'    => __( '⚠ Integrity mismatch: the current .htaccess file hash does not match the last recorded write. The file may have been modified outside of UltraGuard. Review the file immediately.', 'ultraguard-security-suite' ),
				] ] : [] ),

				// ── Activity chart ────────────────────────────────────────────
				[
					'type'  => 'card',
					'title' => __( 'Write Activity (Last 14 Days)', 'ultraguard-security-suite' ),
					'icon'  => 'dashicons-chart-bar',
					'data'  => [ [
						'type'           => 'chart',
						'chart_type'     => 'bar',
						'height'         => '180px',
						'labels'         => $chart['labels'],
						'datasets'       => [ [
							'label'           => __( 'Changes', 'ultraguard-security-suite' ),
							'data'            => $chart['data'],
							'backgroundColor' => 'rgba(99,102,241,0.6)',
							'borderColor'     => '#6366f1',
						] ],
					] ],
				],

				// ── Data table ────────────────────────────────────────────────
				[
					'type'       => 'data-table',
					'id'         => 'htaccess-change-log-table',
					'columns'    => [
						'user_login'    => [ 'title' => __( 'User',        'ultraguard-security-suite' ), 'sortable' => true ],
						'change_reason' => [ 'title' => __( 'Reason',      'ultraguard-security-suite' ), 'sortable' => true ],
						'feature_key'   => [ 'title' => __( 'Feature',     'ultraguard-security-suite' ) ],
						'file_size'     => [ 'title' => __( 'File Size',   'ultraguard-security-suite' ) ],
						'content_hash'  => [ 'title' => __( 'SHA-256',     'ultraguard-security-suite' ) ],
						'ip_address'    => [ 'title' => __( 'IP Address',  'ultraguard-security-suite' ), 'sortable' => true ],
						'created_at'    => [ 'title' => __( 'Date / Time', 'ultraguard-security-suite' ), 'sortable' => true ],
						'actions'       => [ 'title' => __( 'Actions',     'ultraguard-security-suite' ), 'width' => '90px' ],
					],
					'data'       => $data,
					'searchable' => true,
					'pagination' => [ 'enabled' => true, 'page_size' => 25 ],
					'empty_state' => [
						'title'       => __( 'No changes recorded yet', 'ultraguard-security-suite' ),
						'description' => __( 'Changes are logged automatically when you save, import, reset, or toggle security rules.', 'ultraguard-security-suite' ),
					],
				],
			],

			'form' => [ 'enable' => false ],
		], $context );
	}

	// ── Helpers ───────────────────────────────────────────────────────────────

	/**
	 * Map a change_reason slug to a badge colour class.
	 */
	private function reason_badge_class( string $reason ): string {
		return match ( true ) {
			$reason === 'reset'                                    => 'danger',
			$reason === 'manual_save'                              => 'primary',
			in_array( $reason, [ 'import', 'restore' ], true )    => 'warning',
			str_starts_with( $reason, 'before_' )                 => 'secondary',
			default                                                => 'info',
		};
	}
}
