<?php
/**
 * Admin.
 *
 * @package Noesia_Commerce_Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View templates receive local variables from their renderer.
$report = isset( $report ) && is_array( $report ) ? $report : array();
$doctor_scan_scope = isset( $doctor_scan_scope ) && is_array( $doctor_scan_scope ) ? $doctor_scan_scope : array(
	'product_limit'         => 250,
	'large_image_kb'        => 500,
	'broken_links_enabled'  => false,
);
$checks                = isset( $report['checks'] ) && is_array( $report['checks'] ) ? $report['checks'] : array();
$doctor_issue_details  = isset( $doctor_issue_details ) && is_array( $doctor_issue_details ) ? $doctor_issue_details : array();
?>
<section class="noesia-cs-feature-hero noesia-cs-feature-hero--doctor">
	<div>
		<span><?php esc_html_e( 'Manual Scan', 'noesia-commerce-suite' ); ?></span>
		<h2><?php esc_html_e( 'Ecommerce Doctor', 'noesia-commerce-suite' ); ?></h2>
		<p><?php esc_html_e( 'Practical WooCommerce checks, controlled manually. No heavy scan runs on every page load.', 'noesia-commerce-suite' ); ?></p>
	</div>
	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noesia-cs-doctor-scan-form" data-noesia-cs-doctor-scan-form="1">
		<?php wp_nonce_field( 'noesia_cs_doctor_scan' ); ?>
		<input type="hidden" name="action" value="noesia_cs_doctor_scan">
		<button class="noesia-cs-primary-button" type="submit"><?php esc_html_e( 'Run Scan', 'noesia-commerce-suite' ); ?></button>
		<div class="noesia-cs-doctor-loader" data-noesia-cs-doctor-loader hidden><i></i><span><?php esc_html_e( 'Please wait. Large stores may need a few minutes. Do not reload this page.', 'noesia-commerce-suite' ); ?></span></div>
	</form>
</section>

<div class="noesia-cs-grid noesia-cs-grid--doctor-results">
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head">
			<h2><?php esc_html_e( 'Latest Scan Results', 'noesia-commerce-suite' ); ?></h2>
			<?php if ( $report['generated_at'] ) : ?>
				<span><?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $report['generated_at'] ) ); ?></span>
			<?php endif; ?>
		</div>
		<?php $admin->render_doctor_preview( $report ); ?>
	</div>

	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Scan Scope', 'noesia-commerce-suite' ); ?></h2></div>
		<ul class="noesia-cs-check-list">
			<li><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Current Quick Scan product scope: up to %d published products per manual scan for admin performance safety', 'noesia-commerce-suite' ), absint( $doctor_scan_scope['product_limit'] ?? 250 ) ); ?></li>
			<li><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Result examples shown per issue: first %d affected items. Total counts remain visible for the full scanned scope.', 'noesia-commerce-suite' ), absint( $checks['example_limit'] ?? 20 ) ); ?></li>
			<li><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Large image threshold: %d KB', 'noesia-commerce-suite' ), absint( $doctor_scan_scope['large_image_kb'] ?? 500 ) ); ?></li>
			<li><?php esc_html_e( 'Shipping data checks look for shippable products without weight or dimensions.', 'noesia-commerce-suite' ); ?></li>
			<li><?php esc_html_e( 'Sales opportunity checks look for products without cross-sells or upsells.', 'noesia-commerce-suite' ); ?></li>
			<li><?php esc_html_e( 'Catalog visibility checks find hidden in-stock products and visible out-of-stock products.', 'noesia-commerce-suite' ); ?></li>
			<li><?php esc_html_e( 'Suspicious order checks are risk signals only. They review recent orders and never mark an order as fraud.', 'noesia-commerce-suite' ); ?></li>
			<li><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Data retention review reports cancelled, failed or refunded orders older than %d months when enabled.', 'noesia-commerce-suite' ), absint( $doctor_scan_scope['data_retention_months'] ?? 24 ) ); ?></li>
			<li><?php esc_html_e( 'Temporary data checks are read-only. The plugin reports expired transients or WooCommerce sessions but never deletes them.', 'noesia-commerce-suite' ); ?></li>
			<li><?php esc_html_e( 'Autoloaded Options Health reviews option data loaded on every WordPress request and can reveal memory pressure from poorly configured plugins.', 'noesia-commerce-suite' ); ?></li>
			<li><?php esc_html_e( 'Action Scheduler Queue Health reviews pending, failed and in-progress WooCommerce background actions without running or deleting jobs.', 'noesia-commerce-suite' ); ?></li>
			<li><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Broken link checks perform real HTTP requests. Current Quick Scan URL scope: up to %d URLs per manual scan for admin performance safety.', 'noesia-commerce-suite' ), absint( $doctor_scan_scope['broken_link_limit'] ?? 20 ) ); ?></li>
			<li><?php esc_html_e( 'WooCommerce Cart, Checkout and My Account pages are checked when enabled.', 'noesia-commerce-suite' ); ?></li>
		</ul>
		<?php if ( isset( $checks['broken_link_checked'] ) && absint( $checks['broken_link_checked'] ) > 0 ) : ?>
			<p class="noesia-cs-panel__body-note"><?php printf( /* translators: 1: first numeric value; 2: second numeric value. */ esc_html__( 'Broken link quick check: %1$d product URLs checked out of the configured Quick Scan URL scope of %2$d. Other product checks use the Quick Scan product scope and do not perform HTTP requests.', 'noesia-commerce-suite' ), absint( $checks['broken_link_checked'] ), absint( $checks['broken_link_limit'] ?? 20 ) ); ?></p>
		<?php endif; ?>
	</div>
</div>

<?php
/**
 * Allow extensions to add safe diagnostic panels after the Free quick-scan area.
 *
 * The Free plugin does not load or call Pro classes directly. If no extension is
 * attached, this hook outputs nothing and the Free Doctor remains unchanged.
 *
 * @param array $report Current Doctor report.
 * @param object $admin  Admin renderer/controller instance.
 */
do_action( 'noesia_cs_ecommerce_doctor_after_quick_scan', $report, $admin );
?>

<?php if ( ! empty( $doctor_issue_details ) && ! empty( $doctor_issue_details['code'] ) ) : ?>
	<section class="noesia-cs-panel noesia-cs-doctor-details-panel" id="noesia-cs-doctor-details">
		<div class="noesia-cs-panel__head">
			<div>
				<span><?php esc_html_e( 'Detailed report', 'noesia-commerce-suite' ); ?></span>
				<h2><?php echo esc_html( $doctor_issue_details['title'] ?? __( 'Doctor issue details', 'noesia-commerce-suite' ) ); ?></h2>
			</div>
			<a class="noesia-cs-secondary-button" href="<?php echo esc_url( wp_nonce_url( add_query_arg( array(
				'action'                  => 'noesia_cs_doctor_export_issue',
				'noesia_cs_doctor_issue'  => sanitize_key( $doctor_issue_details['code'] ),
			), admin_url( 'admin-post.php' ) ), 'noesia_cs_doctor_export_' . sanitize_key( $doctor_issue_details['code'] ) ) ); ?>"><?php esc_html_e( 'Export CSV', 'noesia-commerce-suite' ); ?></a>
		</div>
		<p class="noesia-cs-panel__body-note"><?php echo esc_html( $doctor_issue_details['note'] ?? '' ); ?></p>
		<p class="noesia-cs-panel__body-note"><?php printf( /* translators: 1: first numeric value; 2: second numeric value. */ esc_html__( 'Showing %1$d rows on this page from %2$d total affected items generated from the current scan settings.', 'noesia-commerce-suite' ), count( (array) ( $doctor_issue_details['rows'] ?? array() ) ), absint( $doctor_issue_details['total'] ?? 0 ) ); ?></p>
		<div class="noesia-cs-doctor-details-table-wrap">
			<table class="noesia-cs-doctor-details-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Type', 'noesia-commerce-suite' ); ?></th>
						<th><?php esc_html_e( 'Item', 'noesia-commerce-suite' ); ?></th>
						<th><?php esc_html_e( 'Detail', 'noesia-commerce-suite' ); ?></th>
						<th><?php esc_html_e( 'Action', 'noesia-commerce-suite' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( (array) ( $doctor_issue_details['rows'] ?? array() ) as $row ) : ?>
						<tr>
							<td><?php echo esc_html( $row['type'] ?? '' ); ?></td>
							<td>
								<strong><?php echo esc_html( $row['name'] ?? '' ); ?></strong>
								<?php if ( ! empty( $row['id'] ) ) : ?><small>#<?php echo esc_html( absint( $row['id'] ) ); ?></small><?php endif; ?>
							</td>
							<td><?php echo esc_html( $row['detail'] ?? '' ); ?></td>
							<td>
								<?php if ( ! empty( $row['edit_url'] ) ) : ?>
									<a href="<?php echo esc_url( $row['edit_url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Open', 'noesia-commerce-suite' ); ?></a>
								<?php else : ?>
									<span>—</span>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
					<?php if ( empty( $doctor_issue_details['rows'] ) ) : ?>
						<tr><td colspan="4"><?php esc_html_e( 'No rows are currently available for this issue. Store data may have changed after the last scan.', 'noesia-commerce-suite' ); ?></td></tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php if ( absint( $doctor_issue_details['total_pages'] ?? 1 ) > 1 ) : ?>
			<div class="noesia-cs-doctor-pagination">
				<?php
				$current_page  = absint( $doctor_issue_details['page'] ?? 1 );
				$total_pages   = absint( $doctor_issue_details['total_pages'] ?? 1 );
				for ( $i = 1; $i <= $total_pages; $i++ ) :
					if ( $i > 1 && $i < $total_pages && abs( $i - $current_page ) > 2 ) {
						if ( 2 === $i || $total_pages - 1 === $i ) {
							echo '<span>…</span>';
						}
						continue;
					}
					$url = add_query_arg( array(
						'page'                    => 'noesia-commerce-suite',
						'tab'                     => 'ecommerce-doctor',
						'noesia_cs_doctor_issue'  => sanitize_key( $doctor_issue_details['code'] ),
						'noesia_cs_doctor_page'   => $i,
					), admin_url( 'admin.php' ) ) . '#noesia-cs-doctor-details';
					?>
					<a class="<?php echo $i === $current_page ? 'is-active' : ''; ?>" href="<?php echo esc_url( $url ); ?>"><?php echo esc_html( number_format_i18n( $i ) ); ?></a>
				<?php endfor; ?>
			</div>
		<?php endif; ?>
	</section>
<?php endif; ?>

<div class="noesia-cs-grid noesia-cs-grid--doctor-info">
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Broken Product Paths', 'noesia-commerce-suite' ); ?></h2></div>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Broken product URLs can damage trust and block a sales path. The Doctor uses a defined manual Quick Scan URL scope so large stores can run quick audits without overwhelming the server.', 'noesia-commerce-suite' ); ?></p>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Risk Signals, Not Accusations', 'noesia-commerce-suite' ); ?></h2></div>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Suspicious order checks help the store review risky signals before shipping, especially for Cash on Delivery workflows. Results are not fraud proof and should be reviewed by a human.', 'noesia-commerce-suite' ); ?></p>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Memory & Background Tasks', 'noesia-commerce-suite' ); ?></h2></div>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Autoloaded options and WooCommerce background tasks can reveal memory pressure, stuck automations or failed plugin integrations. These checks report health signals only; they do not delete data or run jobs.', 'noesia-commerce-suite' ); ?></p>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Safe Manual Scan & Pro Background Workflows', 'noesia-commerce-suite' ); ?></h2></div>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Quick Scan is a Free Core manual health snapshot designed to run safely inside a normal WordPress admin request. It uses defined Quick Scan scopes so large stores are not forced into heavy catalog scans during normal admin use.', 'noesia-commerce-suite' ); ?></p>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'The separate Pro Edition may provide background or batch audit workflows, progress tracking, action planning and export-oriented tools for larger operational reviews. Free Quick Scan remains usable on its own.', 'noesia-commerce-suite' ); ?></p>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Retention & Temporary Data', 'noesia-commerce-suite' ); ?></h2></div>
		<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Retention and temporary-data checks are read-only guidance. Review your own legal, tax and accounting obligations before deleting any order data or running cleanup tools.', 'noesia-commerce-suite' ); ?></p>
	</div>
</div>

<section class="noesia-cs-pro-grid">
	<?php $admin->pro_edition_card( __( 'Doctor Pro Deep Store Scan', 'noesia-commerce-suite' ), __( 'Scan large WooCommerce catalogs safely and uncover product gaps that can reduce trust, SEO quality and sales.', 'noesia-commerce-suite' ), 'doctor_deep_scan' ); ?>
	<?php $admin->pro_edition_card( __( 'Doctor Pro Action Plan', 'noesia-commerce-suite' ), __( 'Get a clear fix plan with priorities, severity, product links and the next actions your store should take.', 'noesia-commerce-suite' ), 'doctor_action_plan' ); ?>
	<?php $admin->pro_edition_card( __( 'CSV Action Plan Export', 'noesia-commerce-suite' ), __( 'Export the Doctor Pro fix plan as CSV so you or your team can work through the improvements.', 'noesia-commerce-suite' ), 'doctor_csv_export' ); ?>
</section>
