<?php
/**
 * AI Alt Text bulk generate tab.
 *
 * @package AIAltTextGenerator
 */

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

use AIAltTextGenerator\BulkGenerator;
use AIAltTextGenerator\Capabilities;
use AIAltTextGenerator\Settings;
use AIAltTextGenerator\Usage;

require_once __DIR__ . '/helpers.php';

if ( ! Capabilities::canGenerate() ) {
	echo '<div class="wpps-ai-alt-notice wpps-ai-alt-notice--warning"><p>' . esc_html__( 'You do not have permission to generate alt text.', 'wp-powersuite' ) . '</p></div>';
	return;
}

$settings    = Settings::get();
$has_key     = Settings::hasApiKey();
$has_woo     = class_exists( 'WooCommerce' );
$base_url    = admin_url( 'admin.php?page=' . \AIAltTextGenerator\Module::DASHBOARD_SLUG );
$bulk_defaults = [
	'overwrite'      => false,
	'only_attached'  => false,
	'skip_processed' => true,
	'woo_only'       => false,
	'woo_main_only'  => false,
	'target'         => 'missing',
];
$preview_count = BulkGenerator::countTargets( $bulk_defaults );
$preview_stats = BulkGenerator::getPreviewStats( $bulk_defaults );
$batch_size    = Settings::clampBatchSize( (int) ( $settings['batch_size'] ?? 5 ) );
$usage         = Usage::getSummary();
$monthly_limit = max( 0, (int) ( $settings['monthly_limit'] ?? 0 ) );
$generations   = (int) ( $usage['generations'] ?? 0 );
$remaining     = $monthly_limit > 0 ? max( 0, $monthly_limit - $generations ) : null;

$total_images = (int) ( $preview_stats['total'] ?? 0 );
$missing_alt  = (int) ( $preview_stats['missing'] ?? 0 );
$with_alt     = (int) ( $preview_stats['with_alt'] ?? 0 );
$missing_pct  = $total_images > 0 ? round( ( $missing_alt / $total_images ) * 100, 1 ) : 0;
$with_pct     = $total_images > 0 ? round( ( $with_alt / $total_images ) * 100, 1 ) : 0;
?>
<?php if ( ! $has_key ) : ?>
	<div class="wpps-ai-alt-notice wpps-ai-alt-notice--warning">
		<p>
			<?php esc_html_e( 'Add your API key before running bulk generation.', 'wp-powersuite' ); ?>
			<?php if ( Capabilities::canManage() ) : ?>
				<a class="wpps-ai-alt-tab-link" data-tab="settings" href="<?php echo esc_url( add_query_arg( 'tab', 'settings', $base_url ) ); ?>"><?php esc_html_e( 'Open Settings', 'wp-powersuite' ); ?></a>
			<?php endif; ?>
		</p>
	</div>
<?php endif; ?>

<div class="wpps-ai-alt-bulk-page">
	<div class="wpps-ai-alt-bulk-hero-stats" id="wpps-ai-alt-bulk-library-stats">
		<div class="wpps-ai-alt-bulk-hero-stat">
			<span class="wpps-ai-alt-bulk-hero-label"><?php esc_html_e( 'Total Images', 'wp-powersuite' ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-value" id="wpps-ai-alt-bulk-stat-total"><?php echo esc_html( (string) $total_images ); ?></span>
		</div>
		<div class="wpps-ai-alt-bulk-hero-stat is-warning">
			<span class="wpps-ai-alt-bulk-hero-label"><?php esc_html_e( 'Missing Alt Text', 'wp-powersuite' ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-value" id="wpps-ai-alt-bulk-stat-missing"><?php echo esc_html( (string) $missing_alt ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-pct" id="wpps-ai-alt-bulk-stat-missing-pct"><?php echo esc_html( (string) $missing_pct ); ?>%</span>
		</div>
		<div class="wpps-ai-alt-bulk-hero-stat is-success">
			<span class="wpps-ai-alt-bulk-hero-label"><?php esc_html_e( 'With Alt Text', 'wp-powersuite' ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-value" id="wpps-ai-alt-bulk-stat-complete"><?php echo esc_html( (string) $with_alt ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-pct" id="wpps-ai-alt-bulk-stat-complete-pct"><?php echo esc_html( (string) $with_pct ); ?>%</span>
		</div>
		<div class="wpps-ai-alt-bulk-hero-stat">
			<span class="wpps-ai-alt-bulk-hero-label"><?php echo null !== $remaining ? esc_html__( 'Remaining This Month', 'wp-powersuite' ) : esc_html__( 'Generations This Month', 'wp-powersuite' ); ?></span>
			<span class="wpps-ai-alt-bulk-hero-value" id="wpps-ai-alt-bulk-stat-remaining"><?php echo esc_html( null !== $remaining ? (string) $remaining : (string) $generations ); ?></span>
		</div>
	</div>

	<div class="wpps-ai-alt-card wpps-ai-alt-bulk-card">
		<div class="wpps-ai-alt-card-body">
			<div class="wpps-ai-alt-bulk-section">
				<h2 class="wpps-ai-alt-bulk-section-title"><?php esc_html_e( 'Keywords', 'wp-powersuite' ); ?></h2>

				<div class="wpps-ai-alt-field-full">
					<label class="wpps-ai-alt-field-label" for="wpps-ai-alt-bulk-seo-keywords"><?php esc_html_e( 'SEO Keywords (optional)', 'wp-powersuite' ); ?></label>
					<div class="wpps-ai-alt-field-control">
						<input type="text" id="wpps-ai-alt-bulk-seo-keywords" class="wpps-ai-alt-input" value="<?php echo esc_attr( (string) ( $settings['default_seo_keywords'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Enter keywords separated by commas', 'wp-powersuite' ); ?>" />
					</div>
					<span class="wpps-ai-alt-help"><?php esc_html_e( 'Saved automatically when you start a bulk run. At least one keyword is added to each alt if the AI omits them. Max 6 phrases.', 'wp-powersuite' ); ?></span>
				</div>

				<div class="wpps-ai-alt-field-full">
					<label class="wpps-ai-alt-field-label" for="wpps-ai-alt-bulk-negative-keywords"><?php esc_html_e( 'Negative Keywords (optional)', 'wp-powersuite' ); ?></label>
					<div class="wpps-ai-alt-field-control">
						<input type="text" id="wpps-ai-alt-bulk-negative-keywords" class="wpps-ai-alt-input" value="<?php echo esc_attr( (string) ( $settings['default_negative_keywords'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Enter negative keywords separated by commas', 'wp-powersuite' ); ?>" />
					</div>
					<span class="wpps-ai-alt-help"><?php esc_html_e( 'Do not include these in the generated alt text. Maximum of 6 keywords or phrases.', 'wp-powersuite' ); ?></span>
				</div>
			</div>

			<div class="wpps-ai-alt-bulk-section">
				<h2 class="wpps-ai-alt-bulk-section-title"><?php esc_html_e( 'Processing Options', 'wp-powersuite' ); ?></h2>
				<div class="wpps-ai-alt-option-list">
					<label class="wpps-ai-alt-option-row" for="wpps-ai-alt-bulk-overwrite">
						<input type="checkbox" id="wpps-ai-alt-bulk-overwrite" value="1" />
						<span class="wpps-ai-alt-option-copy">
							<span class="wpps-ai-alt-option-title"><?php esc_html_e( 'Overwrite existing alt text', 'wp-powersuite' ); ?></span>
							<span class="wpps-ai-alt-option-desc"><?php esc_html_e( 'Include images that already have alt text and replace their existing alt text.', 'wp-powersuite' ); ?></span>
						</span>
					</label>

					<label class="wpps-ai-alt-option-row" for="wpps-ai-alt-bulk-attached">
						<input type="checkbox" id="wpps-ai-alt-bulk-attached" value="1" />
						<span class="wpps-ai-alt-option-copy">
							<span class="wpps-ai-alt-option-title"><?php esc_html_e( 'Only attached images', 'wp-powersuite' ); ?></span>
							<span class="wpps-ai-alt-option-desc"><?php esc_html_e( 'Only process images that are attached to posts or pages.', 'wp-powersuite' ); ?></span>
						</span>
					</label>

					<label class="wpps-ai-alt-option-row" for="wpps-ai-alt-bulk-skip-processed">
						<input type="checkbox" id="wpps-ai-alt-bulk-skip-processed" value="1" checked="checked" />
						<span class="wpps-ai-alt-option-copy">
							<span class="wpps-ai-alt-option-title"><?php esc_html_e( 'Skip previously processed', 'wp-powersuite' ); ?></span>
							<span class="wpps-ai-alt-option-desc"><?php esc_html_e( 'Skip images that have already been processed by this module.', 'wp-powersuite' ); ?></span>
						</span>
					</label>
				</div>
			</div>

			<?php if ( $has_woo ) : ?>
				<div class="wpps-ai-alt-bulk-section">
					<h2 class="wpps-ai-alt-bulk-section-title"><?php esc_html_e( 'WooCommerce Options', 'wp-powersuite' ); ?></h2>
					<div class="wpps-ai-alt-option-list">
						<label class="wpps-ai-alt-option-row" for="wpps-ai-alt-bulk-woo-only">
							<input type="checkbox" id="wpps-ai-alt-bulk-woo-only" value="1" />
							<span class="wpps-ai-alt-option-copy">
								<span class="wpps-ai-alt-option-title"><?php esc_html_e( 'Only process WooCommerce product images.', 'wp-powersuite' ); ?></span>
							</span>
						</label>

						<label class="wpps-ai-alt-option-row" for="wpps-ai-alt-bulk-woo-main">
							<input type="checkbox" id="wpps-ai-alt-bulk-woo-main" value="1" />
							<span class="wpps-ai-alt-option-copy">
								<span class="wpps-ai-alt-option-title"><?php esc_html_e( 'For each product, only process the main image, and skip gallery images.', 'wp-powersuite' ); ?></span>
							</span>
						</label>
					</div>
				</div>
			<?php endif; ?>

			<div class="wpps-ai-alt-bulk-primary-action">
				<button type="button" class="button button-primary button-hero" id="wpps-ai-alt-bulk-start" data-count="<?php echo esc_attr( (string) $preview_count ); ?>" data-has-api-key="<?php echo $has_key ? '1' : '0'; ?>" <?php disabled( ! $has_key || $preview_count <= 0 ); ?>>
					<?php
					if ( $preview_count > 0 ) {
						printf(
							esc_html(
								_n(
									'Generate Alt Text for %d Image',
									'Generate Alt Text for %d Images',
									$preview_count,
									'wp-powersuite'
								)
							),
							$preview_count
						);
					} else {
						esc_html_e( 'No Images Match Selected Filters', 'wp-powersuite' );
					}
					?>
				</button>
				<p class="wpps-ai-alt-help wpps-ai-alt-bulk-match-count" id="wpps-ai-alt-bulk-match-count" aria-live="polite">
					<?php
					if ( $preview_count > 0 ) {
						printf(
							esc_html( _n( '%d image matches your filters', '%d images match your filters', $preview_count, 'wp-powersuite' ) ),
							$preview_count
						);
					} else {
						esc_html_e( 'No images match your filters', 'wp-powersuite' );
					}
					?>
				</p>
				<p class="wpps-ai-alt-help wpps-ai-alt-bulk-speed-hint">
					<?php
					printf(
						esc_html__( 'Processes 1 image per request to avoid host timeouts. Keep this tab open until the run finishes.', 'wp-powersuite' )
					);
					?>
				</p>
			</div>

			<div class="wpps-ai-alt-bulk-run-panel" id="wpps-ai-alt-bulk-run-panel" hidden>
				<div class="wpps-ai-alt-bulk-run-header">
					<div class="wpps-ai-alt-bulk-run-status">
						<span class="wpps-ai-alt-bulk-run-spinner" id="wpps-ai-alt-bulk-run-spinner" aria-hidden="true"></span>
						<span class="wpps-ai-alt-bulk-run-label" id="wpps-ai-alt-bulk-run-label"><?php esc_html_e( 'Generating alt text...', 'wp-powersuite' ); ?></span>
					</div>
					<button type="button" class="button wpps-ai-alt-bulk-stop-btn" id="wpps-ai-alt-bulk-stop"><?php esc_html_e( 'Stop', 'wp-powersuite' ); ?></button>
					<button type="button" class="button button-secondary" id="wpps-ai-alt-bulk-retry-failed" hidden><?php esc_html_e( 'Retry failed', 'wp-powersuite' ); ?></button>
				</div>

				<div class="wpps-ai-alt-bulk-run-progress">
					<div class="wpps-ai-alt-progress-bar wpps-ai-alt-bulk-progress-bar">
						<div class="wpps-ai-alt-progress-fill" id="wpps-ai-alt-bulk-progress-fill" style="width:0%;"></div>
					</div>
					<div class="wpps-ai-alt-bulk-run-meta">
						<span id="wpps-ai-alt-bulk-progress-text">0 / 0</span>
						<span class="wpps-ai-alt-bulk-progress-pct" id="wpps-ai-alt-bulk-progress-pct">0%</span>
					</div>
				</div>

				<div class="wpps-ai-alt-bulk-run-stats">
					<div class="wpps-ai-alt-bulk-stat-chip is-success">
						<span class="wpps-ai-alt-bulk-stat-label"><?php esc_html_e( 'Processed', 'wp-powersuite' ); ?></span>
						<span class="wpps-ai-alt-bulk-stat-value" id="wpps-ai-alt-bulk-stat-processed">0</span>
					</div>
					<div class="wpps-ai-alt-bulk-stat-chip is-failed">
						<span class="wpps-ai-alt-bulk-stat-label"><?php esc_html_e( 'Failed', 'wp-powersuite' ); ?></span>
						<span class="wpps-ai-alt-bulk-stat-value" id="wpps-ai-alt-bulk-stat-failed">0</span>
					</div>
					<div class="wpps-ai-alt-bulk-stat-chip is-skipped">
						<span class="wpps-ai-alt-bulk-stat-label"><?php esc_html_e( 'Skipped', 'wp-powersuite' ); ?></span>
						<span class="wpps-ai-alt-bulk-stat-value" id="wpps-ai-alt-bulk-stat-skipped">0</span>
					</div>
				</div>

				<div class="wpps-ai-alt-bulk-results-section">
					<h3 class="wpps-ai-alt-bulk-results-title">
						<?php esc_html_e( 'Live results', 'wp-powersuite' ); ?>
						<span class="wpps-ai-alt-bulk-results-count" id="wpps-ai-alt-bulk-results-count">0</span>
					</h3>
					<div class="wpps-ai-alt-bulk-results-scroll">
						<table class="widefat striped wpps-ai-alt-table wpps-ai-alt-bulk-results-table" id="wpps-ai-alt-bulk-results">
							<thead>
								<tr>
									<th class="col-image"><?php esc_html_e( 'Image', 'wp-powersuite' ); ?></th>
									<th class="col-status"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
									<th class="col-alt"><?php esc_html_e( 'Alt text', 'wp-powersuite' ); ?></th>
								</tr>
							</thead>
							<tbody></tbody>
						</table>
						<p class="wpps-ai-alt-bulk-results-empty" id="wpps-ai-alt-bulk-results-empty"><?php esc_html_e( 'Results appear here as images are processed.', 'wp-powersuite' ); ?></p>
					</div>
				</div>
			</div>

			<div class="wpps-ai-alt-notice wpps-ai-alt-notice--info" id="wpps-ai-alt-bulk-review-cta" hidden>
				<p>
					<?php esc_html_e( 'Some images are waiting for review before alt text is saved.', 'wp-powersuite' ); ?>
					<a class="button button-secondary wpps-ai-alt-tab-link" data-tab="review" href="<?php echo esc_url( add_query_arg( 'tab', 'review', $base_url ) ); ?>"><?php esc_html_e( 'Open Review tab', 'wp-powersuite' ); ?></a>
				</p>
			</div>
		</div>
	</div>
</div>
