<?php
/**
 * Livada SEO — Tools View
 *
 * @package Livada_SEO
 */

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

$indexnow_key     = (string) Livada_SEO_Loader::get_setting( 'indexnow_key', '' );
$indexnow_key_url = $indexnow_key ? esc_url( home_url( '/' . $indexnow_key . '.txt' ) ) : '';
$seopress_active  = function_exists( 'is_plugin_active' ) && is_plugin_active( 'wp-seopress/seopress.php' );

// Yoast detection: plugin active OR meta keys present in the DB (allow import
// even if the plugin has been deactivated before the import is run).
$yoast_active = function_exists( 'is_plugin_active' )
	&& ( is_plugin_active( 'wordpress-seo/wp-seo.php' ) || is_plugin_active( 'wordpress-seo-premium/wp-seo-premium.php' ) );

if ( ! $yoast_active ) {
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$yoast_data_present = (bool) $wpdb->get_var(
		"SELECT 1 FROM {$wpdb->postmeta} WHERE meta_key LIKE '_yoast_wpseo_%' LIMIT 1"
	);
} else {
	$yoast_data_present = true;
}
?>
<div class="wrap livada-seo-wrap has-ls-hero">
<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>
	<h1><?php esc_html_e( 'Tools', 'livada-seo' ); ?></h1>

	<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'livada-seo' ); ?></p></div>
	<?php endif; ?>

	<!-- ── Import from SEOPress ── -->
	<div class="livada-tool-card" data-importer="seopress" data-ajax-action="livada_seo_import_seopress">
		<h2><?php esc_html_e( 'Import from SEOPress', 'livada-seo' ); ?></h2>
		<?php if ( ! $seopress_active ) : ?>
			<p class="description"><?php esc_html_e( 'SEOPress is not currently active. Activate it to import its data.', 'livada-seo' ); ?></p>
		<?php else : ?>
			<p><?php esc_html_e( 'Import post meta (title, description, noindex, focus keyword) and redirections from SEOPress into Livada SEO.', 'livada-seo' ); ?></p>
		<?php endif; ?>

		<button
			type="button"
			class="button button-primary livada-import-btn"
			<?php disabled( ! $seopress_active ); ?>
		><?php esc_html_e( 'Start Import', 'livada-seo' ); ?></button>

		<div class="livada-import-progress" style="display:none; margin-top: 12px;">
			<div class="livada-progress-bar-wrap">
				<div class="livada-progress-bar" style="width:0%;"></div>
			</div>
			<p class="livada-import-status description"></p>
		</div>
	</div>

	<!-- ── Import from Yoast SEO ── -->
	<div class="livada-tool-card" data-importer="yoast" data-ajax-action="livada_seo_import_yoast">
		<h2><?php esc_html_e( 'Import from Yoast SEO', 'livada-seo' ); ?></h2>
		<?php if ( ! $yoast_data_present ) : ?>
			<p class="description"><?php esc_html_e( 'No Yoast SEO data detected. Activate Yoast (or restore its data) to enable this import.', 'livada-seo' ); ?></p>
		<?php else : ?>
			<p>
				<?php esc_html_e( 'Import post meta (titles, meta descriptions, focus keywords, canonical URLs, OG images, robots flags), site-wide title templates, social profiles, and Yoast Premium redirections (301/302) into Livada SEO.', 'livada-seo' ); ?>
			</p>
			<p class="description">
				<?php esc_html_e( 'Yoast template variables (%%sitename%%, %%title%%, etc.) are converted to Livada syntax automatically. Existing Livada values are preserved at the site level and overwritten at the post level so the import is idempotent.', 'livada-seo' ); ?>
			</p>
		<?php endif; ?>

		<button
			type="button"
			class="button button-primary livada-import-btn"
			<?php disabled( ! $yoast_data_present ); ?>
		><?php esc_html_e( 'Start Import', 'livada-seo' ); ?></button>

		<div class="livada-import-progress" style="display:none; margin-top: 12px;">
			<div class="livada-progress-bar-wrap">
				<div class="livada-progress-bar" style="width:0%;"></div>
			</div>
			<p class="livada-import-status description"></p>
			<details class="livada-import-warnings" style="display:none; margin-top:8px;">
				<summary><?php esc_html_e( 'Warnings', 'livada-seo' ); ?></summary>
				<ul class="livada-import-warnings-list" style="font-size:12px; color:#646970; margin-top:6px;"></ul>
			</details>
		</div>
	</div>

	<!-- ── IndexNow Key ── -->
	<div class="livada-tool-card">
		<h2><?php esc_html_e( 'IndexNow Key', 'livada-seo' ); ?></h2>
		<p>
			<?php esc_html_e( 'Your current IndexNow key:', 'livada-seo' ); ?>
			<code id="livada-indexnow-key"><?php echo $indexnow_key ? esc_html( $indexnow_key ) : esc_html__( '(none)', 'livada-seo' ); ?></code>
		</p>
		<?php if ( $indexnow_key ) : ?>
			<p class="description">
				<?php esc_html_e( 'Key file URL:', 'livada-seo' ); ?>
				<a href="<?php echo esc_url( $indexnow_key_url ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $indexnow_key_url ); ?></a>
			</p>
		<?php endif; ?>
		<button type="button" id="livada-regenerate-indexnow" class="button"><?php esc_html_e( 'Regenerate Key', 'livada-seo' ); ?></button>
		<span id="livada-regenerate-indexnow-status" class="description" style="margin-left:8px;"></span>
	</div>

	<!-- ── Google Search Console keywords import ── -->
	<div class="livada-tool-card">
		<h2><?php esc_html_e( 'Import keywords from Google Search Console', 'livada-seo' ); ?></h2>
		<p>
			<?php esc_html_e( 'Upload a "Top queries" CSV exported from Search Console (filtered by Pages or with the Page column). Livada will match each URL to a post and store the top 25 keywords as post meta. Surfaces in the SEO metabox as "What this page is already ranking for".', 'livada-seo' ); ?>
		</p>

		<?php
		$gsc_status  = isset( $_GET['livada_gsc_status'] )  ? sanitize_key( $_GET['livada_gsc_status'] ) : ''; // phpcs:ignore
		$gsc_updated = isset( $_GET['livada_gsc_updated'] ) ? (int) $_GET['livada_gsc_updated']         : 0;   // phpcs:ignore
		$gsc_skipped = isset( $_GET['livada_gsc_skipped'] ) ? (int) $_GET['livada_gsc_skipped']         : 0;   // phpcs:ignore

		if ( 'ok' === $gsc_status ) {
			echo '<div class="notice notice-success inline"><p>' . sprintf(
				/* translators: 1: posts updated, 2: skipped */
				esc_html__( 'Imported: %1$d post(s) updated, %2$d URL(s) skipped (no matching post).', 'livada-seo' ),
				$gsc_updated,
				$gsc_skipped
			) . '</p></div>';
		} elseif ( 'invalid' === $gsc_status ) {
			echo '<div class="notice notice-error inline"><p>' . esc_html__( 'Invalid file: not a CSV or empty.', 'livada-seo' ) . '</p></div>';
		} elseif ( 'columns' === $gsc_status ) {
			echo '<div class="notice notice-error inline"><p>' . esc_html__( 'CSV header missing required columns (Query / Clicks / Impressions).', 'livada-seo' ) . '</p></div>';
		} elseif ( 'missing' === $gsc_status ) {
			echo '<div class="notice notice-error inline"><p>' . esc_html__( 'No file uploaded.', 'livada-seo' ) . '</p></div>';
		}
		?>

		<form method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:flex; gap:8px; align-items:center; margin-top:8px;">
			<?php wp_nonce_field( 'livada_seo_gsc_import' ); ?>
			<input type="hidden" name="action" value="livada_seo_gsc_import">
			<input type="file" name="gsc_csv" accept=".csv,text/csv" required>
			<button type="submit" class="button"><?php esc_html_e( 'Import CSV', 'livada-seo' ); ?></button>
		</form>
	</div>

	<!-- ── Settings JSON export / import ── -->
	<div class="livada-tool-card">
		<h2><?php esc_html_e( 'Settings — backup & restore', 'livada-seo' ); ?></h2>
		<p>
			<?php esc_html_e( 'Export your plugin settings (including all locations) as a JSON file. The Anthropic API key is intentionally stripped from the export.', 'livada-seo' ); ?>
		</p>

		<?php
		$import_status = isset( $_GET['livada_import'] ) ? sanitize_key( $_GET['livada_import'] ) : ''; // phpcs:ignore
		if ( 'ok' === $import_status ) {
			echo '<div class="notice notice-success inline"><p>' . esc_html__( 'Settings imported successfully.', 'livada-seo' ) . '</p></div>';
		} elseif ( 'invalid' === $import_status ) {
			echo '<div class="notice notice-error inline"><p>' . esc_html__( 'Invalid file: not a Livada SEO settings export.', 'livada-seo' ) . '</p></div>';
		} elseif ( 'missing' === $import_status ) {
			echo '<div class="notice notice-error inline"><p>' . esc_html__( 'No file uploaded.', 'livada-seo' ) . '</p></div>';
		}
		?>

		<div style="display:flex; gap:24px; flex-wrap:wrap; align-items:flex-start; margin-top:8px;">
			<a class="button"
				href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=livada_seo_export_settings' ), 'livada_seo_export_settings' ) ); ?>">
				<?php esc_html_e( 'Download settings JSON', 'livada-seo' ); ?>
			</a>

			<form method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:flex; gap:8px; align-items:center;">
				<?php wp_nonce_field( 'livada_seo_import_settings' ); ?>
				<input type="hidden" name="action" value="livada_seo_import_settings">
				<input type="file" name="livada_seo_import" accept=".json,application/json" required>
				<button type="submit" class="button"><?php esc_html_e( 'Import JSON', 'livada-seo' ); ?></button>
			</form>
		</div>
	</div>

	<!-- ── CSV export — all post SEO data ── -->
	<div class="livada-tool-card">
		<h2><?php esc_html_e( 'Export all SEO data as CSV', 'livada-seo' ); ?></h2>
		<p>
			<?php esc_html_e( 'One row per published post or page with: ID, post type, status, title, permalink, SEO title, meta description, focus keyword, SEO score, readability, schema type, location, noindex, cornerstone. Useful for backups, migrations, or external SEO audits.', 'livada-seo' ); ?>
		</p>
		<a class="button button-primary"
			href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=livada_seo_export_seo_csv' ), 'livada_seo_export_seo_csv' ) ); ?>">
			<?php esc_html_e( 'Download CSV', 'livada-seo' ); ?>
		</a>
	</div>

	<!-- ── Reset Settings ── -->
	<div class="livada-tool-card livada-tool-card--danger">
		<h2><?php esc_html_e( 'Reset All Settings', 'livada-seo' ); ?></h2>
		<p><?php esc_html_e( 'Restore all plugin settings to their default values. This cannot be undone.', 'livada-seo' ); ?></p>
		<button type="button" id="livada-reset-settings" class="button button-danger"><?php esc_html_e( 'Reset Settings', 'livada-seo' ); ?></button>
		<span id="livada-reset-status" class="description" style="margin-left:8px;"></span>
	</div>

</div>
