<?php
/**
 * General cleanup view.
 *
 * @var array<string, mixed>|null $last_scan
 * @var array<string, mixed>      $last_clean
 * @var array<string, mixed>      $overview
 */

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

use DatabaseCleanup\Module;

$db_bytes       = (int) ( $overview['database_bytes'] ?? 0 );
$bloat_bytes    = is_array( $last_scan ) ? (int) ( $last_scan['total_bytes'] ?? 0 ) : 0;
$bloat_count    = is_array( $last_scan ) ? (int) ( $last_scan['total_count'] ?? 0 ) : 0;
$issues_count   = is_array( $last_scan ) ? (int) ( $last_scan['issues_count'] ?? 0 ) : 0;
$last_scan_ts   = is_array( $last_scan ) ? (int) ( $last_scan['scanned_at'] ?? 0 ) : 0;
$last_clean_ts  = is_array( $last_clean ) ? (int) ( $last_clean['timestamp'] ?? 0 ) : 0;
$revisions       = (int) ( $overview['revisions'] ?? 0 );
$revisions_total = (int) ( $overview['revisions_total'] ?? $revisions );
$autoload_bytes  = (int) ( $overview['autoload_bytes'] ?? 0 );
$spam_comments  = (int) ( $overview['spam_comments'] ?? 0 );

$has_scan       = $last_scan_ts > 0;
$needs_warn     = ! empty( $overview['revisions_warn'] ) || ! empty( $overview['autoload_warn'] ) || ( $has_scan && $issues_count > 0 );
$datetime_fmt   = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );

if ( ! $has_scan ) {
	$health_state = 'unknown';
	$health_text  = __( 'Not scanned', 'wp-powersuite' );
} elseif ( $needs_warn ) {
	$health_state = 'attention';
	$health_text  = __( 'Needs attention', 'wp-powersuite' );
} else {
	$health_state = 'good';
	$health_text  = __( 'Healthy', 'wp-powersuite' );
}
?>
<div class="wpps-dc-panel wpps-dc-health">
	<div class="wpps-dc-health__head">
		<h2 class="wpps-dc-health__title"><?php esc_html_e( 'Database health', 'wp-powersuite' ); ?></h2>
		<span class="wpps-dc-health__status wpps-dc-health__status--<?php echo esc_attr( $health_state ); ?>" data-stat="health_status">
			<span class="wpps-dc-health__dot" aria-hidden="true"></span>
			<span data-stat="health_label"><?php echo esc_html( $health_text ); ?></span>
		</span>
		<span class="wpps-dc-health__scanned">
			<?php esc_html_e( 'Last scan:', 'wp-powersuite' ); ?>
			<span data-stat="last_scan"><?php echo esc_html( $has_scan ? wp_date( $datetime_fmt, $last_scan_ts ) : '—' ); ?></span>
		</span>
	</div>
	<div class="wpps-dc-health__grid">
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="database_bytes"><?php echo esc_html( $db_bytes > 0 ? Module::formatBytes( $db_bytes ) : '—' ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Database size', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat wpps-dc-stat--accent">
			<span class="wpps-dc-stat__value" data-stat="total_bytes"><?php echo esc_html( $has_scan ? Module::formatBytes( $bloat_bytes ) : '—' ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Removable', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="total_count"><?php echo esc_html( $has_scan ? number_format_i18n( $bloat_count ) : '—' ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Cleanup items', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="issues_count"><?php echo esc_html( $has_scan ? number_format_i18n( $issues_count ) : '—' ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Categories', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="revisions">
				<?php echo esc_html( number_format_i18n( $revisions ) ); ?>
				<?php if ( ! empty( $overview['revisions_warn'] ) ) : ?>
					<span class="wpps-dc-badge wpps-dc-badge-warning"><?php esc_html_e( 'High', 'wp-powersuite' ); ?></span>
				<?php endif; ?>
			</span>
			<span class="wpps-dc-stat__label">
				<?php esc_html_e( 'Removable revisions', 'wp-powersuite' ); ?>
				<?php if ( $revisions_total > $revisions ) : ?>
					<span class="wpps-dc-stat__hint" data-stat="revisions_total_hint">
						<?php
						printf(
							/* translators: %s: total revision count */
							esc_html__( 'of %s total', 'wp-powersuite' ),
							esc_html( number_format_i18n( $revisions_total ) )
						);
						?>
					</span>
				<?php endif; ?>
			</span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="autoload_bytes">
				<?php echo esc_html( Module::formatBytes( $autoload_bytes ) ); ?>
				<?php if ( ! empty( $overview['autoload_warn'] ) ) : ?>
					<span class="wpps-dc-badge wpps-dc-badge-warning"><?php esc_html_e( 'High', 'wp-powersuite' ); ?></span>
				<?php endif; ?>
			</span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Autoloaded', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="spam_comments"><?php echo esc_html( number_format_i18n( $spam_comments ) ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Spam comments', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-dc-stat">
			<span class="wpps-dc-stat__value" data-stat="last_cleanup"><?php echo esc_html( $last_clean_ts > 0 ? wp_date( $datetime_fmt, $last_clean_ts ) : '—' ); ?></span>
			<span class="wpps-dc-stat__label"><?php esc_html_e( 'Last cleanup', 'wp-powersuite' ); ?></span>
		</div>
	</div>
	<?php
	$trend_points = isset( $size_history ) && is_array( $size_history ) ? $size_history : [];
	if ( count( $trend_points ) >= 2 ) :
		$trend_db = array_map( static fn( $p ): int => (int) ( $p['db'] ?? 0 ), $trend_points );
		$trend_n  = count( $trend_db );
		$trend_lo = min( $trend_db );
		$trend_hi = max( $trend_db );
		$trend_rg = max( 1, $trend_hi - $trend_lo );
		$svg_w    = 320;
		$svg_h    = 44;
		$step     = $trend_n > 1 ? $svg_w / ( $trend_n - 1 ) : $svg_w;
		$coords   = [];
		foreach ( $trend_db as $i => $v ) {
			$x        = round( $i * $step, 2 );
			$y        = round( $svg_h - ( ( $v - $trend_lo ) / $trend_rg ) * ( $svg_h - 6 ) - 3, 2 );
			$coords[] = $x . ',' . $y;
		}
		$polyline = implode( ' ', $coords );
		$area     = '0,' . $svg_h . ' ' . $polyline . ' ' . round( ( $trend_n - 1 ) * $step, 2 ) . ',' . $svg_h;
		$delta    = $trend_db[ $trend_n - 1 ] - $trend_db[0];
		$delta_dir = $delta < 0 ? 'down' : ( $delta > 0 ? 'up' : 'flat' );
		?>
		<div class="wpps-dc-trend wpps-dc-trend--<?php echo esc_attr( $delta_dir ); ?>">
			<div class="wpps-dc-trend__head">
				<span class="wpps-dc-trend__title"><?php esc_html_e( 'Database size trend', 'wp-powersuite' ); ?></span>
				<span class="wpps-dc-trend__delta">
					<?php
					if ( $delta < 0 ) {
						printf(
							/* translators: %s: amount of space reduced */
							esc_html__( '%s smaller', 'wp-powersuite' ),
							esc_html( Module::formatBytes( abs( $delta ) ) )
						);
					} elseif ( $delta > 0 ) {
						printf(
							/* translators: %s: amount of growth */
							esc_html__( '%s larger', 'wp-powersuite' ),
							esc_html( Module::formatBytes( $delta ) )
						);
					} else {
						esc_html_e( 'No change', 'wp-powersuite' );
					}
					?>
					<span class="wpps-dc-trend__since">
						<?php
						printf(
							/* translators: %d: number of recorded scans */
							esc_html__( 'over last %d scans', 'wp-powersuite' ),
							(int) $trend_n
						);
						?>
					</span>
				</span>
			</div>
			<svg class="wpps-dc-trend__chart" viewBox="0 0 <?php echo esc_attr( (string) $svg_w ); ?> <?php echo esc_attr( (string) $svg_h ); ?>" preserveAspectRatio="none" role="img" aria-label="<?php esc_attr_e( 'Database size over time', 'wp-powersuite' ); ?>">
				<polygon class="wpps-dc-trend__area" points="<?php echo esc_attr( $area ); ?>"></polygon>
				<polyline class="wpps-dc-trend__line" points="<?php echo esc_attr( $polyline ); ?>" fill="none"></polyline>
			</svg>
		</div>
	<?php endif; ?>
</div>

<div class="wpps-dc-panel wpps-dc-list-panel">
	<h2 class="wpps-dc-panel-title"><?php esc_html_e( 'General cleanup', 'wp-powersuite' ); ?></h2>
	<div class="wpps-dc-panel-toolbar">
		<div class="wpps-dc-toolbar">
			<p id="wpps-dc-scan-summary" class="wpps-dc-scan-summary">
				<?php
				if ( $last_scan_ts > 0 ) {
					printf(
						esc_html__( '%1$d tasks with bloat · %2$s items · %3$s removable', 'wp-powersuite' ),
						$issues_count,
						number_format_i18n( $bloat_count ),
						esc_html( Module::formatBytes( $bloat_bytes ) )
					);
				} else {
					esc_html_e( 'Run a scan to analyze revisions, transients, spam, orphans, duplicates, and more.', 'wp-powersuite' );
				}
				?>
			</p>
			<div class="wpps-dc-toolbar-actions">
				<button type="button" class="button button-primary" id="wpps-dc-scan"><?php esc_html_e( 'Scan Database', 'wp-powersuite' ); ?></button>
				<button type="button" class="button" id="wpps-dc-clean-selected" disabled><?php esc_html_e( 'Clean Selected', 'wp-powersuite' ); ?></button>
				<button type="button" class="button" id="wpps-dc-clean-all-safe" disabled><?php esc_html_e( 'Clean All Safe', 'wp-powersuite' ); ?></button>
			</div>
		</div>

		<div class="wpps-dc-filters">
			<button type="button" class="wpps-dc-filter is-active" data-filter="all"><?php esc_html_e( 'All tasks', 'wp-powersuite' ); ?></button>
			<button type="button" class="wpps-dc-filter" data-filter="bloat"><?php esc_html_e( 'Has bloat', 'wp-powersuite' ); ?></button>
			<button type="button" class="wpps-dc-filter" data-filter="safe"><?php esc_html_e( 'Safe', 'wp-powersuite' ); ?></button>
			<button type="button" class="wpps-dc-filter" data-filter="caution"><?php esc_html_e( 'Caution', 'wp-powersuite' ); ?></button>
		</div>
	</div>
	<div class="wpps-dc-panel-body">
		<div id="wpps-dc-progress" class="wpps-dc-progress" hidden>
			<div class="wpps-dc-progress-bar"><span id="wpps-dc-progress-fill"></span></div>
			<p id="wpps-dc-progress-text"></p>
		</div>

		<div class="wpps-dc-table-wrap">
			<table class="wp-list-table widefat fixed striped table-view-list wpps-dc-tasks-table" id="wpps-dc-results-table">
				<thead>
					<tr>
						<td id="cb" class="manage-column column-cb check-column">
							<label class="screen-reader-text" for="wpps-dc-select-all"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></label>
							<input type="checkbox" id="wpps-dc-select-all" />
						</td>
						<th scope="col" class="manage-column column-task column-primary"><?php esc_html_e( 'Task', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-category"><?php esc_html_e( 'Category', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-count"><?php esc_html_e( 'Count', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-savings"><?php esc_html_e( 'Est. savings', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-status"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-action"><?php esc_html_e( 'Action', 'wp-powersuite' ); ?></th>
					</tr>
				</thead>
				<tbody id="wpps-dc-results-body"></tbody>
				<tfoot>
					<tr>
						<td class="manage-column column-cb check-column">
							<input type="checkbox" class="wpps-dc-select-all-foot" aria-label="<?php esc_attr_e( 'Select all', 'wp-powersuite' ); ?>" />
						</td>
						<th scope="col" class="manage-column column-task column-primary"><?php esc_html_e( 'Task', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-category"><?php esc_html_e( 'Category', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-count"><?php esc_html_e( 'Count', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-savings"><?php esc_html_e( 'Est. savings', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-status"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-action"><?php esc_html_e( 'Action', 'wp-powersuite' ); ?></th>
					</tr>
				</tfoot>
			</table>
		</div>
	</div>
</div>
