<?php
/**
 * Template: Tools / Website Scanner (native, full parity)
 *
 * Mirrors the Cloud Tools view: intro + scan-frequency badge, three metric
 * cards (cookies / issues / last scan), a "new scan" card that triggers an
 * asynchronous scan via the trigger-scan proxy, a scan-history table (last 10
 * scans), and — when a completed scan exists — the detected-cookies table and
 * issues list. All values come from the get-scan-results proxy contract
 * ({ scan, cookies, issues, history:[{status,cookiesFound,issuesFound,createdAt}], scanFrequency }).
 *
 * @var array $data JSON data from Cloud API (get-scan-results response).
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Website Scanner', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

// Extract scan data with safe defaults.
$scan     = ( isset( $data['scan'] ) && is_array( $data['scan'] ) ) ? $data['scan'] : array();
$cookies  = ( isset( $data['cookies'] ) && is_array( $data['cookies'] ) ) ? $data['cookies'] : array();
$issues   = ( isset( $data['issues'] ) && is_array( $data['issues'] ) ) ? $data['issues'] : array();
$history  = ( isset( $data['history'] ) && is_array( $data['history'] ) ) ? $data['history'] : array();
$scan_freq = isset( $data['scanFrequency'] ) ? (string) $data['scanFrequency'] : 'monthly';

$has_completed = ! empty( $scan ) && isset( $scan['status'] ) && 'COMPLETED' === $scan['status'];
$cookies_found = $has_completed && isset( $scan['cookiesFound'] ) ? number_format_i18n( absint( $scan['cookiesFound'] ) ) : '—';
$issues_found  = $has_completed && isset( $scan['issuesFound'] ) ? number_format_i18n( absint( $scan['issuesFound'] ) ) : '—';

$date_fmt = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
// Last scan date = most recent scan of ANY status (history[0]); else "Never".
$last_scan_date = __( 'Never', 'biscotti-cmp' );
if ( ! empty( $history ) && ! empty( $history[0]['createdAt'] ) ) {
	$last_scan_date = wp_date( $date_fmt, strtotime( $history[0]['createdAt'] ) );
} elseif ( $has_completed && ! empty( $scan['completedAt'] ) ) {
	$last_scan_date = wp_date( $date_fmt, strtotime( $scan['completedAt'] ) );
}

// Plan scan-frequency labels.
$freq_labels = array(
	'realtime'  => __( 'Realtime', 'biscotti-cmp' ),
	'daily'     => __( 'Daily', 'biscotti-cmp' ),
	'weekly'    => __( 'Weekly', 'biscotti-cmp' ),
	'monthly'   => __( 'Monthly', 'biscotti-cmp' ),
	'quarterly' => __( 'Quarterly', 'biscotti-cmp' ),
	'manual'    => __( 'Manual', 'biscotti-cmp' ),
);
$freq_label = isset( $freq_labels[ $scan_freq ] ) ? $freq_labels[ $scan_freq ] : ucfirst( $scan_freq );

/**
 * Render a coloured status pill for a scan status.
 *
 * @param string $status Scan status (COMPLETED|IN_PROGRESS|PENDING|FAILED).
 * @return void
 */
if ( ! function_exists( 'biscotti_scan_status_pill' ) ) {
	function biscotti_scan_status_pill( $status ) {
		$map = array(
			'COMPLETED'   => array( 'class' => 'biscotti-pill-green', 'label' => __( 'Completed', 'biscotti-cmp' ), 'icon' => '✓' ),
			'IN_PROGRESS' => array( 'class' => 'biscotti-pill-blue', 'label' => __( 'In Progress', 'biscotti-cmp' ), 'icon' => '⏳' ),
			'PENDING'     => array( 'class' => 'biscotti-pill-blue', 'label' => __( 'Pending', 'biscotti-cmp' ), 'icon' => '⏳' ),
			'FAILED'      => array( 'class' => 'biscotti-pill-red', 'label' => __( 'Failed', 'biscotti-cmp' ), 'icon' => '✕' ),
		);
		$m = isset( $map[ $status ] ) ? $map[ $status ] : array( 'class' => 'biscotti-pill-gray', 'label' => $status, 'icon' => '' );
		printf(
			'<span class="biscotti-pill %s">%s %s</span>',
			esc_attr( $m['class'] ),
			esc_html( $m['icon'] ),
			esc_html( $m['label'] )
		);
	}
}
?>

<div class="biscotti-page biscotti-page-tools">

	<p class="description biscotti-tools-intro">
		<?php esc_html_e( 'Scan your website to detect cookies, tracking scripts, and third-party services. The scan analyzes your site and categorizes all findings.', 'biscotti-cmp' ); ?>
		<br />
		<?php
		printf(
			/* translators: %s: scan frequency label (e.g. Monthly). */
			esc_html__( 'Automatic scan frequency on your plan: %s', 'biscotti-cmp' ),
			'<span class="biscotti-plan-badge">' . esc_html( $freq_label ) . '</span>'
		);
		?>
	</p>

	<!-- Metrics -->
	<div class="biscotti-stats-grid">
		<?php
		Biscotti_Template_Renderer::stat_card( __( 'Cookies Found', 'biscotti-cmp' ), $cookies_found, 'dashicons-admin-generic' );
		Biscotti_Template_Renderer::stat_card( __( 'Issues Found', 'biscotti-cmp' ), $issues_found, 'dashicons-warning' );
		Biscotti_Template_Renderer::stat_card( __( 'Last Scan', 'biscotti-cmp' ), $last_scan_date, 'dashicons-clock' );
		?>
	</div>

	<!-- New Scan -->
	<div class="biscotti-card">
		<h3>🚀 <?php esc_html_e( 'New Scan', 'biscotti-cmp' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Start a fresh scan now. Results appear in the scan history once the scan finishes.', 'biscotti-cmp' ); ?></p>
		<p>
			<button type="button" id="biscotti-start-scan" class="button button-primary">
				<span class="dashicons dashicons-search" style="margin-top:4px;margin-right:4px;"></span>
				<?php esc_html_e( 'Start Scan', 'biscotti-cmp' ); ?>
			</button>
			<span id="biscotti-scan-status" class="biscotti-save-status" role="status"></span>
		</p>
	</div>

	<!-- Scan History -->
	<div class="biscotti-card">
		<h3>📊 <?php esc_html_e( 'Scan History', 'biscotti-cmp' ); ?></h3>
		<?php if ( empty( $history ) ) : ?>
			<div class="biscotti-empty-state">
				<span class="dashicons dashicons-info-outline biscotti-empty-icon"></span>
				<h3><?php esc_html_e( 'No scan results yet', 'biscotti-cmp' ); ?></h3>
				<p><?php esc_html_e( 'Run your first website scan to detect cookies and third-party services on your site.', 'biscotti-cmp' ); ?></p>
			</div>
		<?php else : ?>
			<table class="widefat biscotti-data-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Status', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Cookies', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Issues', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Date', 'biscotti-cmp' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $history as $row ) : ?>
						<tr>
							<td><?php biscotti_scan_status_pill( isset( $row['status'] ) ? $row['status'] : '' ); ?></td>
							<td><?php echo esc_html( number_format_i18n( absint( $row['cookiesFound'] ?? 0 ) ) ); ?></td>
							<td><?php echo esc_html( number_format_i18n( absint( $row['issuesFound'] ?? 0 ) ) ); ?></td>
							<td><?php echo esc_html( ! empty( $row['createdAt'] ) ? wp_date( $date_fmt, strtotime( $row['createdAt'] ) ) : '—' ); ?></td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</div>

	<?php if ( $has_completed && ! empty( $cookies ) ) : ?>
		<!-- Detected Cookies (latest completed scan) -->
		<div class="biscotti-card">
			<h3><?php esc_html_e( 'Detected Cookies', 'biscotti-cmp' ); ?></h3>
			<?php
			Biscotti_Template_Renderer::data_table(
				array(
					'name'     => __( 'Cookie Name', 'biscotti-cmp' ),
					'domain'   => __( 'Domain', 'biscotti-cmp' ),
					'category' => __( 'Category', 'biscotti-cmp' ),
					'duration' => __( 'Duration', 'biscotti-cmp' ),
				),
				array_map(
					function ( $cookie ) {
						return array(
							'name'     => isset( $cookie['name'] ) ? $cookie['name'] : '',
							'domain'   => isset( $cookie['domain'] ) ? $cookie['domain'] : '',
							'category' => isset( $cookie['category'] ) ? $cookie['category'] : '',
							'duration' => isset( $cookie['duration'] ) ? $cookie['duration'] : '',
						);
					},
					$cookies
				)
			);
			?>
		</div>
	<?php endif; ?>

	<?php if ( $has_completed && ! empty( $issues ) ) : ?>
		<!-- Issues -->
		<div class="biscotti-card">
			<h3><?php esc_html_e( 'Issues', 'biscotti-cmp' ); ?></h3>
			<div class="biscotti-issues-list">
				<?php foreach ( $issues as $issue ) : ?>
					<div class="notice notice-<?php echo esc_attr( 'error' === ( $issue['severity'] ?? '' ) ? 'error' : 'warning' ); ?> inline">
						<p>
							<?php if ( ! empty( $issue['severity'] ) ) : ?>
								<strong><?php echo esc_html( ucfirst( $issue['severity'] ) ); ?>:</strong>
							<?php endif; ?>
							<?php echo esc_html( $issue['message'] ?? '' ); ?>
						</p>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
	<?php endif; ?>

</div>
