<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
final class ClaimPrism_Admin {
    /** @var ClaimPrism_Scanner */
    private $scanner;

    /** @var ClaimPrism_Background_Scanner */
    private $background;

    public function __construct( ClaimPrism_Scanner $scanner, ClaimPrism_Background_Scanner $background ) {
        $this->scanner = $scanner;
        $this->background = $background;
        add_action( 'admin_menu', array($this, 'add_menu'), 30 );
        add_action( 'admin_post_claimprism_scan', array($this, 'handle_scan') );
        add_action( 'admin_post_claimprism_export', array($this, 'handle_export') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_assets') );
    }

    private function has_pro_access() {
        return function_exists( 'cp_fs' ) && cp_fs()->can_use_premium_code();
    }

    private function capability() {
        return ( class_exists( 'WooCommerce' ) ? 'manage_woocommerce' : 'manage_options' );
    }

    public function add_menu() {
        $capability = $this->capability();
        if ( class_exists( 'WooCommerce' ) ) {
            add_submenu_page(
                'woocommerce',
                __( 'ClaimPrism', 'claimprism' ),
                __( 'ClaimPrism', 'claimprism' ),
                $capability,
                'claimprism',
                array($this, 'render_page')
            );
            return;
        }
        add_management_page(
            __( 'ClaimPrism', 'claimprism' ),
            __( 'ClaimPrism', 'claimprism' ),
            $capability,
            'claimprism',
            array($this, 'render_page')
        );
    }

    public function enqueue_assets( $hook ) {
        if ( false === strpos( $hook, 'claimprism' ) ) {
            return;
        }
        wp_enqueue_style(
            'claimprism-admin',
            CLAIMPRISM_URL . 'assets/admin.css',
            array(),
            CLAIMPRISM_VERSION
        );
        if ( false === strpos( $hook, 'claimprism-governance' ) ) {
            wp_enqueue_style(
                'claimprism-dashboard-dark',
                CLAIMPRISM_URL . 'assets/dashboard-dark.css',
                array('claimprism-admin'),
                CLAIMPRISM_VERSION
            );
        }
    }

    public function handle_scan() {
        if ( !current_user_can( $this->capability() ) ) {
            wp_die( esc_html__( 'You do not have permission to run this scan.', 'claimprism' ) );
        }
        check_admin_referer( 'claimprism_scan' );
        $this->background->start_scan();
        $this->background->run_batch();
        $url = add_query_arg( array(
            'page'       => 'claimprism',
            'cg_started' => 1,
        ), admin_url( ( class_exists( 'WooCommerce' ) ? 'admin.php' : 'tools.php' ) ) );
        wp_safe_redirect( $url );
        exit;
    }

    public function handle_export() {
        if ( !current_user_can( $this->capability() ) ) {
            wp_die( esc_html__( 'You do not have permission to export this report.', 'claimprism' ) );
        }
        check_admin_referer( 'claimprism_export' );
        if ( function_exists( 'cp_fs' ) ) {
        }
        wp_die( esc_html__( 'CSV export is available with ClaimPrism Pro.', 'claimprism' ), esc_html__( 'ClaimPrism Pro required', 'claimprism' ), array(
            'response' => 403,
        ) );
    }

    private function csv_safe_cell( $value ) {
        $value = (string) $value;
        if ( '' !== $value && preg_match( '/^(?:[=+\\-@\\t\\r\\n]|[ \\t\\r\\n]+[=+\\-@])/u', $value ) ) {
            return "'" . $value;
        }
        return $value;
    }

    public function render_page() {
        if ( !current_user_can( $this->capability() ) ) {
            return;
        }
        $summary = $this->scanner->get_summary();
        $findings = $this->scanner->get_findings( 100 );
        $affected = $this->scanner->get_affected_content_count();
        $priority_score = ClaimPrism_Scanner::calculate_review_priority( $summary );
        $priority_label = $this->priority_label( $priority_score );
        $last_scan = get_option( 'claimprism_last_scan', '' );
        $job = $this->background->get_state();
        $evidence_alerts = ClaimPrism_Editor::get_evidence_alerts( 30 );
        $show_onboarding = empty( $findings ) && empty( $last_scan ) && 'idle' === $job['status'];
        /* translators: %d: review-priority score from 0 to 100. */
        $priority_aria = sprintf( __( 'Review priority %d out of 100', 'claimprism' ), $priority_score );
        /* translators: %d: number of content items with detected signals. */
        $affected_copy = sprintf( _n(
            '%d content item currently has detected signals.',
            '%d content items currently have detected signals.',
            $affected,
            'claimprism'
        ), $affected );
        $last_scan_copy = '';
        if ( $last_scan ) {
            /* translators: %s: date/time of the last full scan. */
            $last_scan_copy = sprintf( __( 'Last full scan: %s', 'claimprism' ), $last_scan );
        }
        ?>
		<div class="wrap claimprism-wrap">
			<div class="claimprism-header">
				<div>
					<h1><?php 
        esc_html_e( 'ClaimPrism', 'claimprism' );
        ?></h1>
					<p><?php 
        esc_html_e( 'Environmental marketing claim risk screening for WordPress and WooCommerce.', 'claimprism' );
        ?></p>
				</div>
				<div class="claimprism-actions">
					<?php 
        if ( $this->has_pro_access() ) {
            ?>
						<form action="<?php 
            echo esc_url( admin_url( 'admin-post.php' ) );
            ?>" method="post">
							<input type="hidden" name="action" value="claimprism_export">
							<?php 
            wp_nonce_field( 'claimprism_export' );
            ?>
							<?php 
            submit_button(
                __( 'Export review CSV', 'claimprism' ),
                'secondary',
                'submit',
                false
            );
            ?>
						</form>
					<?php 
        } else {
            ?>
						<a class="button" href="<?php 
            echo esc_url( cp_fs()->get_upgrade_url() );
            ?>">
							<?php 
            esc_html_e( 'Export review CSV — Pro', 'claimprism' );
            ?>
						</a>
					<?php 
        }
        ?>
					<form action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>" method="post">
						<input type="hidden" name="action" value="claimprism_scan">
						<?php 
        wp_nonce_field( 'claimprism_scan' );
        ?>
						<?php 
        submit_button(
            __( 'Scan store now', 'claimprism' ),
            'primary',
            'submit',
            false
        );
        ?>
					</form>
				</div>
			</div>

			<?php 
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This status flag only controls a notice after a nonce-protected admin-post action.
        if ( isset( $_GET['cg_started'] ) ) {
            ?>
				<div class="notice notice-success is-dismissible"><p>
					<?php 
            esc_html_e( 'Full-store scan started. The first batch has already been checked; remaining batches continue in the background.', 'claimprism' );
            ?>
				</p></div>
			<?php 
        }
        ?>

			<div class="claimprism-disclaimer">
				<strong><?php 
        esc_html_e( 'Risk screening, not a compliance verdict.', 'claimprism' );
        ?></strong>
				<?php 
        esc_html_e( 'Findings are automated signals for human review and do not constitute legal advice.', 'claimprism' );
        ?>
			</div>

			<?php 
        if ( $show_onboarding ) {
            ?>
				<section class="claimprism-onboarding" aria-labelledby="claimprism-onboarding-title">
					<div class="claimprism-onboarding-copy">
						<span class="claimprism-onboarding-kicker"><?php 
            esc_html_e( 'Start here', 'claimprism' );
            ?></span>
						<h2 id="claimprism-onboarding-title"><?php 
            esc_html_e( 'Turn environmental claims into a reviewable workflow', 'claimprism' );
            ?></h2>
						<p><?php 
            esc_html_e( 'ClaimPrism scans your WordPress and WooCommerce content for environmental marketing signals, prioritizes what deserves human review, and helps you organize the supporting workflow.', 'claimprism' );
            ?></p>
						<form class="claimprism-onboarding-scan" action="<?php 
            echo esc_url( admin_url( 'admin-post.php' ) );
            ?>" method="post">
							<input type="hidden" name="action" value="claimprism_scan">
							<?php 
            wp_nonce_field( 'claimprism_scan' );
            ?>
							<?php 
            submit_button(
                __( 'Run your first scan', 'claimprism' ),
                'primary',
                'submit',
                false
            );
            ?>
						</form>
						<p class="claimprism-onboarding-note"><?php 
            esc_html_e( 'A finding is a screening signal for review — not a certification, legal conclusion, or compliance verdict.', 'claimprism' );
            ?></p>
					</div>
					<div class="claimprism-onboarding-steps" aria-label="<?php 
            echo esc_attr__( 'ClaimPrism workflow overview', 'claimprism' );
            ?>">
						<div class="claimprism-onboarding-step"><strong>1</strong><span><?php 
            esc_html_e( 'Scan', 'claimprism' );
            ?></span><p><?php 
            esc_html_e( 'Find environmental marketing language across your site.', 'claimprism' );
            ?></p></div>
						<div class="claimprism-onboarding-step"><strong>2</strong><span><?php 
            esc_html_e( 'Review findings', 'claimprism' );
            ?></span><p><?php 
            esc_html_e( 'Prioritize detected signals and decide what needs attention.', 'claimprism' );
            ?></p></div>
						<div class="claimprism-onboarding-step"><strong>3</strong><span><?php 
            esc_html_e( 'Pro governance', 'claimprism' );
            ?></span><p><?php 
            esc_html_e( 'Connect review, evidence, lifecycle decisions and monitoring.', 'claimprism' );
            ?></p></div>
						<div class="claimprism-onboarding-pro">
							<?php 
            if ( $this->has_pro_access() ) {
                ?>
								<a class="button" href="<?php 
                echo esc_url( add_query_arg( 'page', 'claimprism-governance', admin_url( ( class_exists( 'WooCommerce' ) ? 'admin.php' : 'tools.php' ) ) ) );
                ?>"><?php 
                esc_html_e( 'Open Claim Governance', 'claimprism' );
                ?></a>
							<?php 
            } else {
                ?>
								<a class="button" href="<?php 
                echo esc_url( cp_fs()->get_upgrade_url() );
                ?>"><?php 
                esc_html_e( 'Explore ClaimPrism Pro', 'claimprism' );
                ?></a>
							<?php 
            }
            ?>
							<small><?php 
            esc_html_e( 'Pro adds workflow and governance tools; it does not replace human or legal review.', 'claimprism' );
            ?></small>
						</div>
					</div>
				</section>
			<?php 
        }
        ?>

			<div class="cg-priority-panel cg-priority-<?php 
        echo esc_attr( $priority_label['class'] );
        ?>">
				<div class="cg-priority-score" aria-label="<?php 
        echo esc_attr( $priority_aria );
        ?>">
					<span><?php 
        esc_html_e( 'Review Priority', 'claimprism' );
        ?></span>
					<strong><?php 
        echo esc_html( $priority_score );
        ?><small>/100</small></strong>
					<em><?php 
        echo esc_html( $priority_label['label'] );
        ?></em>
				</div>
				<div class="cg-priority-copy">
					<h2><?php 
        esc_html_e( 'What needs attention first', 'claimprism' );
        ?></h2>
					<p><?php 
        echo esc_html( $affected_copy );
        ?></p>
					<?php 
        $this->render_next_actions( $summary, $evidence_alerts );
        ?>
					<p class="description"><?php 
        esc_html_e( 'The score measures review workload from detected signals. It is not a legal compliance score.', 'claimprism' );
        ?></p>
				</div>
			</div>

			<?php 
        $this->render_evidence_alerts( $evidence_alerts );
        ?>

			<div class="claimprism-cards">
				<?php 
        $this->render_card( 'critical', __( 'Critical', 'claimprism' ), $summary['critical'] );
        ?>
				<?php 
        $this->render_card( 'high', __( 'High', 'claimprism' ), $summary['high'] );
        ?>
				<?php 
        $this->render_card( 'medium', __( 'Review', 'claimprism' ), $summary['medium'] );
        ?>
				<?php 
        $this->render_card( 'total', __( 'Total', 'claimprism' ), array_sum( $summary ) );
        ?>
			</div>

			<?php 
        $this->render_scan_progress( $job );
        ?>
			<?php 
        do_action( 'claimprism_dashboard_after_progress', $job, $summary );
        ?>

			<div class="claimprism-meta">
				<?php 
        echo ( $last_scan ? esc_html( $last_scan_copy ) : esc_html__( 'No full scan has been run yet.', 'claimprism' ) );
        ?>
			</div>

			<h2><?php 
        esc_html_e( 'Findings', 'claimprism' );
        ?></h2>
			<?php 
        if ( empty( $findings ) ) {
            ?>
				<div class="claimprism-empty">
					<?php 
            if ( $last_scan ) {
                ?>
						<h3><?php 
                esc_html_e( 'No findings detected in the latest scan', 'claimprism' );
                ?></h3>
						<p><?php 
                esc_html_e( 'No screening signals are currently queued for review. ClaimPrism will continue to re-check supported content when it is saved and during future scans.', 'claimprism' );
                ?></p>
					<?php 
            } else {
                ?>
						<h3><?php 
                esc_html_e( 'Nothing to review yet', 'claimprism' );
                ?></h3>
						<p><?php 
                esc_html_e( 'Run the first scan. ClaimPrism will also re-check individual products, posts and pages when they are saved.', 'claimprism' );
                ?></p>
					<?php 
            }
            ?>
				</div>
			<?php 
        } else {
            ?>
				<div class="claimprism-table-wrap">
				<table class="widefat fixed striped claimprism-table">
					<thead><tr>
						<th><?php 
            esc_html_e( 'Priority', 'claimprism' );
            ?></th>
						<th><?php 
            esc_html_e( 'Content', 'claimprism' );
            ?></th>
						<th><?php 
            esc_html_e( 'Signal', 'claimprism' );
            ?></th>
						<th><?php 
            esc_html_e( 'Context', 'claimprism' );
            ?></th>
						<th><?php 
            esc_html_e( 'Source', 'claimprism' );
            ?></th>
					</tr></thead>
					<tbody>
					<?php 
            foreach ( $findings as $finding ) {
                ?>
						<tr>
							<td><span class="cg-badge cg-<?php 
                echo esc_attr( $finding['severity'] );
                ?>"><?php 
                echo esc_html( ucfirst( $finding['severity'] ) );
                ?></span></td>
							<td>
								<strong><?php 
                echo esc_html( ( $finding['content_title'] ? $finding['content_title'] : __( '(untitled)', 'claimprism' ) ) );
                ?></strong><br>
								<a href="<?php 
                echo esc_url( get_edit_post_link( (int) $finding['content_id'] ) );
                ?>"><?php 
                esc_html_e( 'Edit', 'claimprism' );
                ?></a>
								<?php 
                $this->render_evidence_status( $finding );
                ?>
							</td>
							<td><strong><?php 
                echo esc_html( $finding['matched_phrase'] );
                ?></strong><br><small><?php 
                echo esc_html( $finding['rule_label'] );
                ?></small></td>
							<td><?php 
                echo esc_html( $finding['context'] );
                ?></td>
							<td><a href="<?php 
                echo esc_url( $finding['source_url'] );
                ?>" target="_blank" rel="noopener noreferrer"><?php 
                esc_html_e( 'Official source', 'claimprism' );
                ?></a></td>
						</tr>
					<?php 
            }
            ?>
					</tbody>
				</table>
				</div>
			<?php 
        }
        ?>
		</div>
		<?php 
    }

    private function render_card( $class, $label, $value ) {
        ?>
		<div class="claimprism-card cg-card-<?php 
        echo esc_attr( $class );
        ?>">
			<span><?php 
        echo esc_html( $label );
        ?></span>
			<strong><?php 
        echo esc_html( number_format_i18n( $value ) );
        ?></strong>
		</div>
		<?php 
    }

    private function priority_label( $score ) {
        if ( $score >= 75 ) {
            return array(
                'class' => 'urgent',
                'label' => __( 'Urgent review', 'claimprism' ),
            );
        }
        if ( $score >= 50 ) {
            return array(
                'class' => 'high',
                'label' => __( 'High review load', 'claimprism' ),
            );
        }
        if ( $score >= 25 ) {
            return array(
                'class' => 'review',
                'label' => __( 'Review recommended', 'claimprism' ),
            );
        }
        if ( $score > 0 ) {
            return array(
                'class' => 'monitor',
                'label' => __( 'Monitor', 'claimprism' ),
            );
        }
        return array(
            'class' => 'clear',
            'label' => __( 'No detected workload', 'claimprism' ),
        );
    }

    private function render_next_actions( $summary, $evidence_alerts ) {
        $actions = array();
        if ( $summary['critical'] > 0 ) {
            /* translators: %d: number of critical signals. */
            $template = _n(
                'Review %d critical signal and its substantiation.',
                'Review %d critical signals and their substantiation.',
                $summary['critical'],
                'claimprism'
            );
            $actions[] = sprintf( $template, $summary['critical'] );
        }
        if ( $summary['high'] > 0 ) {
            /* translators: %d: number of high-priority environmental claims. */
            $template = _n(
                'Review %d high-priority environmental claim.',
                'Review %d high-priority environmental claims.',
                $summary['high'],
                'claimprism'
            );
            $actions[] = sprintf( $template, $summary['high'] );
        }
        if ( !empty( $evidence_alerts ) ) {
            $alert_count = count( $evidence_alerts );
            /* translators: %d: number of expired or expiring evidence references. */
            $template = _n(
                'Update %d expired or expiring evidence reference.',
                'Update %d expired or expiring evidence references.',
                $alert_count,
                'claimprism'
            );
            $actions[] = sprintf( $template, $alert_count );
        }
        if ( empty( $actions ) && ($summary['medium'] > 0 || $summary['low'] > 0) ) {
            $actions[] = __( 'Review the remaining lower-priority signals and link supporting evidence where appropriate.', 'claimprism' );
        }
        if ( empty( $actions ) ) {
            $actions[] = __( 'No signals are currently queued. Keep the scheduled scan enabled and re-check after content changes.', 'claimprism' );
        }
        ?>
		<ol class="cg-next-actions">
			<?php 
        foreach ( array_slice( $actions, 0, 3 ) as $action ) {
            ?>
				<li><?php 
            echo esc_html( $action );
            ?></li>
			<?php 
        }
        ?>
		</ol>
		<?php 
    }

    private function render_evidence_status( $finding ) {
        $entries = ClaimPrism_Editor::get_evidence( (int) $finding['content_id'] );
        if ( empty( $entries ) ) {
            return;
        }
        $today = current_time( 'Y-m-d' );
        $linked = null;
        foreach ( $entries as $entry ) {
            if ( !empty( $entry['claim_key'] ) && hash_equals( (string) $finding['claim_key'], (string) $entry['claim_key'] ) ) {
                $linked = $entry;
                break;
            }
        }
        ?>
		<br><small class="cg-evidence-status">
			<?php 
        if ( $linked ) {
            if ( !empty( $linked['expires'] ) && $linked['expires'] < $today ) {
                echo '<span class="cg-evidence-pill cg-evidence-expired">' . esc_html__( 'Linked evidence expired', 'claimprism' ) . '</span>';
            } else {
                echo '<span class="cg-evidence-pill cg-evidence-linked">' . esc_html__( 'Evidence linked', 'claimprism' ) . '</span>';
            }
        } else {
            /* translators: %d: number of evidence entries attached to the content item. */
            printf( esc_html__( '%d evidence entries — none linked', 'claimprism' ), count( $entries ) );
        }
        ?>
		</small>
		<?php 
    }

    private function render_evidence_alerts( $alerts ) {
        if ( empty( $alerts ) ) {
            return;
        }
        $expired = count( array_filter( $alerts, function ( $alert ) {
            return 'expired' === $alert['status'];
        } ) );
        $expiring = count( $alerts ) - $expired;
        /* translators: 1: number of expired evidence references, 2: number expiring within 30 days. */
        $summary_copy = sprintf( __( '%1$d expired · %2$d expiring within 30 days', 'claimprism' ), $expired, $expiring );
        ?>
		<div class="cg-evidence-alerts">
			<h2><?php 
        esc_html_e( 'Evidence attention needed', 'claimprism' );
        ?></h2>
			<p><?php 
        echo esc_html( $summary_copy );
        ?></p>
			<ul>
				<?php 
        foreach ( array_slice( $alerts, 0, 10 ) as $alert ) {
            ?>
					<li>
						<span class="cg-evidence-pill cg-evidence-<?php 
            echo esc_attr( $alert['status'] );
            ?>"><?php 
            echo esc_html( ( 'expired' === $alert['status'] ? __( 'Expired', 'claimprism' ) : __( 'Expiring', 'claimprism' ) ) );
            ?></span>
						<a href="<?php 
            echo esc_url( get_edit_post_link( $alert['post_id'] ) );
            ?>"><?php 
            echo esc_html( get_the_title( $alert['post_id'] ) );
            ?></a>
						— <?php 
            echo esc_html( $alert['label'] );
            ?> · <?php 
            echo esc_html( $alert['expires'] );
            ?>
					</li>
				<?php 
        }
        ?>
			</ul>
		</div>
		<?php 
    }

    private function render_scan_progress( $job ) {
        if ( 'idle' === $job['status'] ) {
            return;
        }
        $total = max( 0, (int) $job['total'] );
        $processed = min( $total, max( 0, (int) $job['processed'] ) );
        $percent = ( $total > 0 ? min( 100, (int) round( $processed / $total * 100 ) ) : 100 );
        $progress_copy = sprintf(
            /* translators: 1: processed items, 2: total items, 3: completion percentage. */
            __( '%1$d / %2$d items · %3$d%%', 'claimprism' ),
            $processed,
            $total,
            $percent
        );
        /* translators: %d: number of risk signals encountered in the current scan. */
        $findings_copy = sprintf( __( '%d risk signals encountered during this run.', 'claimprism' ), (int) $job['findings'] );
        ?>
		<div class="cg-scan-progress">
			<div class="cg-scan-progress-head">
				<strong><?php 
        echo ( 'completed' === $job['status'] ? esc_html__( 'Full scan completed', 'claimprism' ) : esc_html__( 'Full scan in progress', 'claimprism' ) );
        ?></strong>
				<span><?php 
        echo esc_html( $progress_copy );
        ?></span>
			</div>
			<div class="cg-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="<?php 
        echo esc_attr( $percent );
        ?>"><span style="width:<?php 
        echo esc_attr( $percent );
        ?>%"></span></div>
			<p><?php 
        echo esc_html( $findings_copy );
        ?></p>
		</div>
		<?php 
    }

}
