<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Logging\Logger;
use Wisewand\Calendar\Calendar_Entry_Manager;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.PHP.DevelopmentFunctions.error_log_error_log -- print_r() and error_log() are only used within WP_DEBUG conditionals for debugging; table names from $wpdb->prefix are safe to interpolate; direct database calls required for custom plugin table operations

/**
 * Wisewand Dashboard - Central hub for content automation overview
 * Shows metrics, pipeline status, upcoming publications, and recent activity
 */
class Dashboard_Page {

	private $options;
	private $logger;
	private $entry_manager;

	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;

		if ( ! class_exists( 'Wisewand\\Calendar\\Calendar_Entry_Manager' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Calendar/Calendar_Entry_Manager.php';
		}
		if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_Payload_Builder' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_Payload_Builder.php';
		}

		$payload_builder     = new \Wisewand\Utils\Wisewand_Payload_Builder( $options, $logger );
		$this->entry_manager = new \Wisewand\Calendar\Calendar_Entry_Manager( $options, $logger, $payload_builder );
	}

	/**
	 * Enqueue dashboard assets
	 */
	private function enqueue_assets() {
		wp_enqueue_style(
			'wisewand-dashboard-admin',
			WISEWAND_PLUGIN_URL . 'assets/css/admin/wisewand-dashboard-admin.css',
			array(),
			WISEWAND_PLUGIN_VERSION
		);

		wp_enqueue_script(
			'wisewand-dashboard-admin',
			WISEWAND_PLUGIN_URL . 'assets/js/admin/wisewand-dashboard-admin.js',
			array( 'jquery' ),
			WISEWAND_PLUGIN_VERSION,
			true
		);

		wp_localize_script(
			'wisewand-dashboard-admin',
			'wisewandDashboard',
			array(
				'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
				'nonce'       => wp_create_nonce( 'wisewand_dashboard' ),
				'calendarUrl' => admin_url( 'admin.php?page=wisewand-editorial-calendar' ),
			)
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$metrics = $this->get_dashboard_metrics();

		?>
		<div class="wrap wisewand-dashboard-page">
			<div class="dashboard-header">
				<div>
					<h1>📊 <?php esc_html_e( 'Wisewand Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h1>
					<p><?php esc_html_e( 'Content automation overview and metrics', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>
				<div class="header-actions">
					<button type="button" id="refresh-dashboard" class="button button-secondary">
						🔄 <?php esc_html_e( 'Refresh', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<span class="auto-refresh-indicator">
						🔄 <?php esc_html_e( 'Auto-refresh: 2min', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</span>
				</div>
			</div>

			<!-- Key Metrics -->
			<div class="dashboard-section key-metrics">
				<div class="metric-card metric-scheduled" data-filter="not_created">
					<div class="metric-icon">📅</div>
					<div class="metric-content">
						<div class="metric-value"><?php echo esc_html( $metrics['key_metrics']['scheduled'] ); ?></div>
						<div class="metric-label"><?php esc_html_e( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<div class="metric-card metric-generating" data-filter="generating">
					<div class="metric-icon">🔄</div>
					<div class="metric-content">
						<div class="metric-value"><?php echo esc_html( $metrics['key_metrics']['generating'] ); ?></div>
						<div class="metric-label"><?php esc_html_e( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<div class="metric-card metric-ready" data-filter="ready">
					<div class="metric-icon">✅</div>
					<div class="metric-content">
						<div class="metric-value"><?php echo esc_html( $metrics['key_metrics']['ready'] ); ?></div>
						<div class="metric-label"><?php esc_html_e( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<div class="metric-card metric-imported" data-view="imported">
					<div class="metric-icon">📰</div>
					<div class="metric-content">
						<div class="metric-value"><?php echo esc_html( $metrics['key_metrics']['imported'] ); ?></div>
						<div class="metric-label"><?php esc_html_e( 'Imported', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<div class="metric-card metric-failed" data-filter="failed">
					<div class="metric-icon">⚠️</div>
					<div class="metric-content">
						<div class="metric-value"><?php echo esc_html( $metrics['key_metrics']['failed'] ); ?></div>
						<div class="metric-label"><?php esc_html_e( 'Failed', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>
			</div>

			<div class="dashboard-grid">
				<!-- Left Column -->
				<div class="dashboard-column">
					<!-- Upcoming Publications -->
					<div class="dashboard-card">
						<h3>📅 <?php esc_html_e( 'Upcoming Publications', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="upcoming-stats">
							<div class="upcoming-stat">
								<span class="stat-label"><?php esc_html_e( 'Next 7 Days', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<span class="stat-value"><?php echo esc_html( $metrics['upcoming']['next_7_days'] ); ?></span>
							</div>
							<div class="upcoming-stat">
								<span class="stat-label"><?php esc_html_e( 'Next 30 Days', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<span class="stat-value"><?php echo esc_html( $metrics['upcoming']['next_30_days'] ); ?></span>
							</div>
							<div class="upcoming-stat">
								<span class="stat-label"><?php esc_html_e( 'This Month', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<span class="stat-value"><?php echo esc_html( $metrics['upcoming']['this_month'] ); ?></span>
							</div>
						</div>
					</div>

					<!-- Generation Pipeline -->
					<div class="dashboard-card">
						<h3>🔄 <?php esc_html_e( 'Generation Pipeline', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="pipeline-items">
							<?php if ( $metrics['pipeline']['tomorrow'] > 0 ) : ?>
							<div class="pipeline-item">
								<div class="pipeline-icon">⏳</div>
								<div class="pipeline-text">
									<strong><?php echo esc_html( $metrics['pipeline']['tomorrow'] ); ?></strong>
									<?php
									/* translators: %s: Date in format "Month Day" (e.g., "Jan 15", "Dec 31") */
									printf( esc_html__( 'articles scheduled for creation tomorrow (%s)', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( gmdate( 'M j', strtotime( '+1 day' ) ) ) );
									?>
								</div>
							</div>
							<?php endif; ?>

							<?php if ( $metrics['key_metrics']['generating'] > 0 ) : ?>
							<div class="pipeline-item">
								<div class="pipeline-icon">🔄</div>
								<div class="pipeline-text">
									<strong><?php echo esc_html( $metrics['key_metrics']['generating'] ); ?></strong>
									<?php esc_html_e( 'articles generating right now', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
							</div>
							<?php endif; ?>

							<?php if ( $metrics['key_metrics']['ready'] > 0 ) : ?>
							<div class="pipeline-item">
								<div class="pipeline-icon">✅</div>
								<div class="pipeline-text">
									<strong><?php echo esc_html( $metrics['key_metrics']['ready'] ); ?></strong>
									<?php esc_html_e( 'articles ready to publish', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
							</div>
							<?php endif; ?>

							<?php if ( $metrics['pipeline']['today'] > 0 ) : ?>
							<div class="pipeline-item">
								<div class="pipeline-icon">📰</div>
								<div class="pipeline-text">
									<strong><?php echo esc_html( $metrics['pipeline']['today'] ); ?></strong>
									<?php esc_html_e( 'articles publishing today', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
							</div>
							<?php endif; ?>

							<?php if ( $metrics['key_metrics']['failed'] > 0 ) : ?>
							<div class="pipeline-item pipeline-item-warning">
								<div class="pipeline-icon">⚠️</div>
								<div class="pipeline-text">
									<strong><?php echo esc_html( $metrics['key_metrics']['failed'] ); ?></strong>
									<?php esc_html_e( 'failed articles (will retry)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
							</div>
							<?php endif; ?>
						</div>
					</div>

					<!-- Content by Type -->
					<div class="dashboard-card">
						<h3>📝 <?php esc_html_e( 'Content by Type', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="content-type-list">
							<?php foreach ( $metrics['content_by_type'] as $type => $count ) : ?>
								<?php if ( $count > 0 ) : ?>
								<div class="content-type-item" data-type-filter="<?php echo esc_attr( $type ); ?>">
									<span class="type-icon"><?php echo esc_html( $this->get_type_icon( $type ) ); ?></span>
									<span class="type-label"><?php echo esc_html( $this->get_type_label( $type ) ); ?></span>
									<span class="type-count"><?php echo esc_html( $count ); ?></span>
								</div>
								<?php endif; ?>
							<?php endforeach; ?>
						</div>
					</div>
				</div>

				<!-- Right Column -->
				<div class="dashboard-column">
					<!-- Success Rate -->
					<div class="dashboard-card">
						<h3>📈 <?php esc_html_e( 'Success Rate (Last 30 Days)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="success-rate-stats">
							<div class="success-rate-chart">
								<div class="success-percentage" style="font-size: 42px; font-weight: 700; color: #10b981;">
									<?php echo esc_html( round( $metrics['success_rate']['percentage'], 1 ) ); ?>%
								</div>
								<div class="success-label"><?php esc_html_e( 'Success Rate', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
							</div>
							<div class="success-breakdown">
								<div class="breakdown-item">
									<span class="breakdown-label"><?php esc_html_e( 'Total Generated', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="breakdown-value"><?php echo esc_html( $metrics['success_rate']['total'] ); ?></span>
								</div>
								<div class="breakdown-item success-text">
									<span class="breakdown-label"><?php esc_html_e( 'Successful', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="breakdown-value"><?php echo esc_html( $metrics['success_rate']['successful'] ); ?></span>
								</div>
								<div class="breakdown-item failed-text">
									<span class="breakdown-label"><?php esc_html_e( 'Failed', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="breakdown-value"><?php echo esc_html( $metrics['success_rate']['failed'] ); ?></span>
								</div>
								<div class="breakdown-item">
									<span class="breakdown-label"><?php esc_html_e( 'Retried', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="breakdown-value"><?php echo esc_html( $metrics['success_rate']['retried'] ); ?></span>
								</div>
							</div>
						</div>
					</div>

					<!-- Recent Activity -->
					<div class="dashboard-card">
						<h3>⚡ <?php esc_html_e( 'Recent Activity (Last 24h)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="recent-activity-list">
							<?php if ( empty( $metrics['recent_activity'] ) ) : ?>
								<div class="empty-state-small">
									<p><?php esc_html_e( 'No recent activity', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
								</div>
							<?php else : ?>
								<?php foreach ( $metrics['recent_activity'] as $activity ) : ?>
								<div class="activity-item" data-entry-id="<?php echo esc_attr( $activity['id'] ); ?>">
									<div class="activity-time"><?php echo esc_html( $activity['time_ago'] ); ?></div>
									<div class="activity-content">
										<span class="activity-icon"><?php echo esc_html( $activity['icon'] ); ?></span>
										<strong>"<?php echo esc_html( $activity['keyword'] ); ?>"</strong>
										→ <?php echo esc_html( $activity['status_label'] ); ?>
										<?php if ( ! empty( $activity['wisewand_url'] ) ) : ?>
											<a href="<?php echo esc_url( $activity['wisewand_url'] ); ?>" target="_blank" class="wisewand-link" title="<?php esc_html_e( 'View in Wisewand Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
												🔗 <?php esc_html_e( 'View', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
											</a>
										<?php endif; ?>
									</div>
								</div>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>
					</div>

					<!-- CRON Status -->
					<div class="dashboard-card">
						<h3>⏰ <?php esc_html_e( 'CRON Automation', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
						<div class="cron-status-info">
							<!-- Overall Status -->
							<div class="cron-stat cron-overall-status">
								<span class="cron-label"><?php esc_html_e( 'Overall Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<span class="cron-value cron-healthy">✅ <?php esc_html_e( 'Healthy', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							</div>

							<!-- 15-Minute Status Check CRON -->
							<div class="cron-section">
								<div class="cron-section-header">
									<strong>⚡ <?php esc_html_e( 'Status Check (Every 15 min)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
									<span class="cron-description"><?php esc_html_e( 'Checks status, imports ready, retries failed', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								</div>
								<div class="cron-stat">
									<span class="cron-label"><?php esc_html_e( 'Last Run', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="cron-value"><?php echo esc_html( $metrics['cron']['status_check']['last_run'] ); ?></span>
								</div>
								<div class="cron-stat">
									<span class="cron-label"><?php esc_html_e( 'Next Run', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="cron-value cron-next-run"><?php echo esc_html( $metrics['cron']['status_check']['next_run'] ); ?></span>
								</div>
								<?php if ( ! empty( $metrics['cron']['status_check']['last_summary'] ) ) : ?>
								<div class="cron-mini-summary">
									<span class="mini-stat">✅ <?php echo esc_html( $metrics['cron']['status_check']['last_summary']['status_checked'] ?? 0 ); ?> checked</span>
									<span class="mini-stat">📥 <?php echo esc_html( $metrics['cron']['status_check']['last_summary']['imported'] ?? 0 ); ?> imported</span>
									<span class="mini-stat">🔄 <?php echo esc_html( $metrics['cron']['status_check']['last_summary']['retried'] ?? 0 ); ?> retried</span>
								</div>
								<?php endif; ?>
							</div>

							<!-- Daily Full CRON -->
							<div class="cron-section">
								<div class="cron-section-header">
									<strong>🌙 <?php esc_html_e( 'Daily Operations (2 AM)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
									<span class="cron-description"><?php esc_html_e( 'Generates new articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								</div>
								<div class="cron-stat">
									<span class="cron-label"><?php esc_html_e( 'Last Run', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="cron-value"><?php echo esc_html( $metrics['cron']['daily']['last_run'] ); ?></span>
								</div>
								<div class="cron-stat">
									<span class="cron-label"><?php esc_html_e( 'Next Run', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
									<span class="cron-value cron-next-run"><?php echo esc_html( $metrics['cron']['daily']['next_run'] ); ?></span>
								</div>
								<?php if ( ! empty( $metrics['cron']['daily']['last_summary'] ) ) : ?>
								<div class="cron-mini-summary">
									<span class="mini-stat">🆕 <?php echo esc_html( $metrics['cron']['daily']['last_summary']['generated'] ?? 0 ); ?> generated</span>
									<span class="mini-stat">📥 <?php echo esc_html( $metrics['cron']['daily']['last_summary']['imported'] ?? 0 ); ?> imported</span>
									<span class="mini-stat">🔄 <?php echo esc_html( $metrics['cron']['daily']['last_summary']['retried'] ?? 0 ); ?> retried</span>
								</div>
								<?php endif; ?>
							</div>

							<?php if ( empty( $metrics['cron']['next_run_timestamp'] ) ) : ?>
							<div class="cron-warning" style="margin-top: 16px; padding: 12px; background: #fef3c7; border-left: 3px solid #f59e0b; border-radius: 6px;">
								<p style="margin: 0; font-size: 13px; color: #92400e;">
									⚠️ <?php esc_html_e( 'CRON is not scheduled. It will auto-schedule on next page load or when you generate a roadmap.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</p>
								<p style="margin: 8px 0 0 0; font-size: 11px; color: #92400e;">
									<?php esc_html_e( 'If this persists, check your WordPress CRON system or contact support.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</p>
							</div>
							<?php endif; ?>

							<?php if ( ! empty( $metrics['cron']['debug_info'] ) && WP_DEBUG ) : ?>
							<details style="margin-top: 12px;">
								<summary style="cursor: pointer; font-size: 12px; color: #64748b;">🔧 Debug Info</summary>
								<pre style="font-size: 10px; background: #f1f5f9; padding: 8px; border-radius: 4px; overflow-x: auto; margin-top: 8px;">
								<?php echo esc_html( print_r( $metrics['cron']['debug_info'], true ) ); ?>
								</pre>
							</details>
							<?php endif; ?>

							<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #e5e7eb;">
								<button type="button" id="manual-trigger-cron" class="button button-secondary" style="width: 100%; padding: 8px 16px; font-size: 13px;">
									▶️ <?php esc_html_e( 'Run CRON Manually', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</button>
								<p style="font-size: 11px; color: #64748b; margin: 8px 0 0 0; text-align: center;">
									<?php esc_html_e( 'Trigger status check and generation immediately', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</p>
							</div>

							<div id="cron-logs-output" style="display: none; margin-top: 12px; padding: 12px; background: #0f172a; border-radius: 8px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 11px; line-height: 1.6; color: #e2e8f0;"></div>
						</div>
					</div>
				</div>
			</div>

			<!-- Imported Articles Section -->
			<div class="dashboard-card dashboard-imported-articles">
				<div class="imported-header">
					<h3>📰 <?php esc_html_e( 'Recently Imported Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
					<div class="imported-stats-summary">
						<span class="import-stat-badge">
							<strong><?php echo esc_html( $metrics['imported_stats']['last_24h'] ); ?></strong> <?php esc_html_e( 'last 24h', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</span>
						<span class="import-stat-badge">
							<strong><?php echo esc_html( $metrics['imported_stats']['last_7d'] ); ?></strong> <?php esc_html_e( 'last 7 days', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</span>
						<span class="import-stat-badge">
							<strong><?php echo esc_html( $metrics['imported_stats']['last_30d'] ); ?></strong> <?php esc_html_e( 'last 30 days', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</span>
					</div>
				</div>

				<?php if ( empty( $metrics['imported_articles'] ) ) : ?>
					<div class="empty-state">
						<div class="empty-state-icon">📭</div>
						<h4><?php esc_html_e( 'No imported articles yet', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h4>
						<p><?php esc_html_e( 'Articles will appear here once they are automatically imported from Wisewand to WordPress.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
					</div>
				<?php else : ?>
					<div class="imported-articles-table-wrapper">
						<table class="imported-articles-table">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Article', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Imported', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $metrics['imported_articles'] as $article ) : ?>
								<tr class="imported-article-row" data-post-id="<?php echo esc_attr( $article['post_id'] ); ?>">
									<td class="article-title-cell">
										<div class="article-title-wrapper">
											<strong class="article-title"><?php echo esc_html( $article['post_title'] ); ?></strong>
											<?php if ( ! empty( $article['wisewand_article_id'] ) ) : ?>
												<a href="<?php echo esc_url( $article['wisewand_url'] ); ?>"
													target="_blank"
													class="wisewand-badge"
													title="<?php esc_html_e( 'View in Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
													🔗 Wisewand
												</a>
											<?php endif; ?>
										</div>
									</td>
									<td class="language-cell">
										<span class="language-badge language-<?php echo esc_attr( $article['language'] ); ?>">
											<?php echo esc_html( strtoupper( $article['language'] ) ); ?>
										</span>
									</td>
									<td class="status-cell">
										<span class="status-badge status-<?php echo esc_attr( $article['post_status'] ); ?>">
											<?php echo esc_html( $this->get_wordpress_status_label( $article['post_status'] ) ); ?>
										</span>
									</td>
									<td class="categories-cell">
										<?php if ( ! empty( $article['categories'] ) ) : ?>
											<div class="categories-list">
												<?php foreach ( array_slice( $article['categories'], 0, 3 ) as $category ) : ?>
													<span class="category-tag"><?php echo esc_html( $category ); ?></span>
												<?php endforeach; ?>
												<?php if ( count( $article['categories'] ) > 3 ) : ?>
													<span class="category-more">+<?php echo count( $article['categories'] ) - 3; ?></span>
												<?php endif; ?>
											</div>
										<?php else : ?>
											<span class="text-muted">—</span>
										<?php endif; ?>
									</td>
									<td class="author-cell">
										<?php echo esc_html( $article['author_name'] ); ?>
									</td>
									<td class="import-date-cell">
										<span class="import-time" title="<?php echo esc_attr( $article['imported_at_full'] ); ?>">
											<?php echo esc_html( $article['imported_at'] ); ?>
										</span>
									</td>
									<td class="actions-cell">
										<div class="article-actions">
											<a href="<?php echo esc_url( $article['edit_url'] ); ?>"
												class="action-btn action-edit"
												title="<?php esc_html_e( 'Edit post', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
												✏️
											</a>
											<?php if ( $article['post_status'] === 'publish' ) : ?>
												<a href="<?php echo esc_url( $article['view_url'] ); ?>"
													target="_blank"
													class="action-btn action-view"
													title="<?php esc_html_e( 'View post', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
													👁️
												</a>
											<?php endif; ?>
										</div>
									</td>
								</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>

					<?php if ( $metrics['imported_stats']['total'] > count( $metrics['imported_articles'] ) ) : ?>
						<div class="imported-footer">
							<a href="<?php echo esc_url( admin_url( 'edit.php' ) ); ?>" class="view-all-link">
								<?php
								/* translators: %d: Total number of imported articles */
								printf( esc_html__( 'View all %d imported articles →', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $metrics['imported_stats']['total'] ) );
								?>
							</a>
						</div>
					<?php endif; ?>
				<?php endif; ?>
			</div>

			<!-- Quick Actions -->
			<div class="dashboard-quick-actions">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-editorial-calendar' ) ); ?>" class="quick-action-btn">
					📅 <?php esc_html_e( 'View Calendar', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-seo-intelligence' ) ); ?>" class="quick-action-btn">
					🔍 <?php esc_html_e( 'Browse Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-articles' ) ); ?>" class="quick-action-btn">
					📝 <?php esc_html_e( 'View Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</div>
		</div>

		<?php
		$this->enqueue_assets();
	}

	private function get_dashboard_metrics() {
		global $wpdb;
		$table       = $wpdb->prefix . 'wisewand_editorial_calendar';
		$posts_table = $wpdb->prefix . 'posts';

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table names derived from $wpdb->prefix are safe to interpolate, dashboard metrics queries on custom plugin table

		// Key Metrics
		$key_metrics = array(
			'scheduled'  => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wisewand_status = 'not_created'" ),
			'generating' => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wisewand_status IN ('creating', 'generating')" ),
			'ready'      => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wisewand_status = 'ready'" ),
			'imported'   => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wordpress_post_id IS NOT NULL AND wordpress_post_id > 0" ),
			'failed'     => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wisewand_status = 'failed'" ),
		);

		// Upcoming Publications
		$upcoming = array(
			'next_7_days'  => $wpdb->get_var(
				"SELECT COUNT(*) FROM {$table} WHERE publication_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)"
			),
			'next_30_days' => $wpdb->get_var(
				"SELECT COUNT(*) FROM {$table} WHERE publication_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)"
			),
			'this_month'   => $wpdb->get_var(
				"SELECT COUNT(*) FROM {$table} WHERE YEAR(publication_date) = YEAR(CURDATE()) AND MONTH(publication_date) = MONTH(CURDATE())"
			),
		);

		// Pipeline
		$pipeline = array(
			'tomorrow' => $wpdb->get_var(
				"SELECT COUNT(*) FROM {$table} WHERE publication_date = DATE_ADD(CURDATE(), INTERVAL 1 DAY) AND wisewand_status = 'not_created'"
			),
			'today'    => $wpdb->get_var(
				"SELECT COUNT(*) FROM {$table} WHERE publication_date = CURDATE()"
			),
		);

		// Success Rate (Last 30 Days)
		$total_30d = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$table} WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"
		);

		$successful_30d = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$table} WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND (wisewand_status = 'ready' OR wordpress_status = 'published')"
		);

		$failed_30d = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$table} WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND wisewand_status = 'failed'"
		);

		$retried_30d = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$table} WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND wisewand_retry_count > 0"
		);

		$success_rate = array(
			'total'      => $total_30d,
			'successful' => $successful_30d,
			'failed'     => $failed_30d,
			'retried'    => $retried_30d,
			'percentage' => $total_30d > 0 ? ( $successful_30d / $total_30d ) * 100 : 0,
		);

		// Content by Type
		$content_by_type_raw = $wpdb->get_results(
			"SELECT wisewand_type, COUNT(*) as count FROM {$table} GROUP BY wisewand_type",
			ARRAY_A
		);

		$content_by_type = array();
		foreach ( $content_by_type_raw as $row ) {
			$content_by_type[ $row['wisewand_type'] ] = $row['count'];
		}

		// Recent Activity (Last 24 hours)
		$recent_activity_raw = $wpdb->get_results(
			"SELECT * FROM {$table} WHERE updated_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY updated_at DESC LIMIT 10",
			ARRAY_A
		);

        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		$recent_activity = array_map(
			function ( $entry ) {
				return array(
					'id'                  => $entry['id'],
					'keyword'             => $entry['keyword'],
					'status'              => $entry['wisewand_status'],
					'wisewand_article_id' => $entry['wisewand_article_id'],
					'wisewand_url'        => ! empty( $entry['wisewand_article_id'] ) ? 'https://app.wisewand.ai/articles/' . $entry['wisewand_article_id'] . '/result' : null,
					'time_ago'            => human_time_diff( strtotime( $entry['updated_at'] ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' ),
					'icon'                => $this->get_status_icon( $entry['wisewand_status'] ),
					'status_label'        => $this->get_status_label( $entry['wisewand_status'] ),
				);
			},
			$recent_activity_raw
		);

		// Imported Articles Statistics
		$imported_stats = $this->get_imported_stats( $table );

		// Recently Imported Articles (with full details)
		$imported_articles = $this->get_imported_articles( $table, $posts_table );

		// CRON Status
		$cron = $this->get_cron_info();

		return array(
			'key_metrics'       => $key_metrics,
			'upcoming'          => $upcoming,
			'pipeline'          => $pipeline,
			'success_rate'      => $success_rate,
			'content_by_type'   => $content_by_type,
			'recent_activity'   => $recent_activity,
			'imported_stats'    => $imported_stats,
			'imported_articles' => $imported_articles,
			'cron'              => $cron,
		);
	}

	/**
	 * Get imported articles statistics
	 *
	 * @param string $table Editorial calendar table name
	 * @return array Statistics array with counts
	 */
	private function get_imported_stats( $table ) {
		global $wpdb;

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table names derived from $wpdb->prefix are safe to interpolate, imported stats queries on custom plugin table
		return array(
			'total'    => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wordpress_post_id IS NOT NULL AND wordpress_post_id > 0" ),
			'last_24h' => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wordpress_post_id IS NOT NULL AND wordpress_post_id > 0 AND published_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)" ),
			'last_7d'  => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wordpress_post_id IS NOT NULL AND wordpress_post_id > 0 AND published_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)" ),
			'last_30d' => $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE wordpress_post_id IS NOT NULL AND wordpress_post_id > 0 AND published_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)" ),
		);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	}

	/**
	 * Get recently imported articles with full details
	 *
	 * @param string $table Editorial calendar table name
	 * @param string $posts_table WordPress posts table name
	 * @return array Array of imported articles with details
	 */
	private function get_imported_articles( $table, $posts_table ) {
		global $wpdb;
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table names derived from $wpdb->prefix are safe to interpolate, JOIN query between custom plugin table and posts table
		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
                    ec.id as entry_id,
                    ec.keyword,
                    ec.wisewand_article_id,
                    ec.wisewand_lang,
                    ec.wordpress_post_id,
                    ec.wordpress_categories,
                    ec.published_at,
                    p.ID as post_id,
                    p.post_title,
                    p.post_status,
                    p.post_author,
                    p.post_date
                FROM {$table} ec
                INNER JOIN {$posts_table} p ON ec.wordpress_post_id = p.ID
                WHERE ec.wordpress_post_id IS NOT NULL
                AND ec.wordpress_post_id > 0
                ORDER BY ec.published_at DESC
                LIMIT %d",
				20
			),
			ARRAY_A
		);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		// Transform results into structured array
		return array_map(
			function ( $row ) {
				// Get author name
				$author      = get_user_by( 'id', $row['post_author'] );
				$author_name = $author ? $author->display_name : __( 'Unknown', 'wisewand-ai-content-writer-seo-content-generator' );

				// Get categories
				$categories = array();
				if ( ! empty( $row['wordpress_categories'] ) ) {
					$category_ids = json_decode( $row['wordpress_categories'], true );
					if ( is_array( $category_ids ) ) {
						foreach ( $category_ids as $cat_id ) {
							$category = get_category( $cat_id );
							if ( $category ) {
								$categories[] = $category->name;
							}
						}
					}
				}

				// Fallback: get categories from WordPress post if none in editorial calendar
				if ( empty( $categories ) ) {
					$post_categories = get_the_category( $row['post_id'] );
					foreach ( $post_categories as $cat ) {
						$categories[] = $cat->name;
					}
				}

				// Format import date
				$imported_timestamp = ! empty( $row['published_at'] ) ? strtotime( $row['published_at'] ) : strtotime( $row['post_date'] );
				$imported_at        = human_time_diff( $imported_timestamp, current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' );
				$imported_at_full   = ! empty( $row['published_at'] ) ? $row['published_at'] : $row['post_date'];

				// Wisewand URL
				$wisewand_url = ! empty( $row['wisewand_article_id'] )
				? 'https://app.wisewand.ai/articles/' . $row['wisewand_article_id'] . '/result'
				: '';

				return array(
					'entry_id'            => $row['entry_id'],
					'post_id'             => $row['post_id'],
					'post_title'          => $row['post_title'],
					'post_status'         => $row['post_status'],
					'language'            => $row['wisewand_lang'] ?? 'en',
					'categories'          => $categories,
					'author_name'         => $author_name,
					'imported_at'         => $imported_at,
					'imported_at_full'    => $imported_at_full,
					'wisewand_article_id' => $row['wisewand_article_id'],
					'wisewand_url'        => $wisewand_url,
					'edit_url'            => get_edit_post_link( $row['post_id'] ),
					'view_url'            => get_permalink( $row['post_id'] ),
				);
			},
			$results
		);
	}

	private function get_cron_info() {
		// Check BOTH CRON jobs
		$status_check_cron = wp_next_scheduled( 'wisewand_check_article_status' );  // 15-minute
		$daily_cron        = wp_next_scheduled( 'wisewand_editorial_calendar_cron' );      // Daily

		// Get last run times for BOTH CRONs
		$last_status_check   = get_option( 'wisewand_cron_last_status_check', null );
		$last_status_summary = get_option( 'wisewand_cron_last_status_summary', null );
		$last_daily_run      = get_option( 'wisewand_cron_last_run', null );
		$last_daily_summary  = get_option( 'wisewand_cron_last_summary', null );

		// Debug logging
		$this->logger->debug(
			'Dashboard CRON check',
			array(
				'status_check_next' => $status_check_cron ? gmdate( 'Y-m-d H:i:s', $status_check_cron ) : 'not scheduled',
				'daily_next'        => $daily_cron ? gmdate( 'Y-m-d H:i:s', $daily_cron ) : 'not scheduled',
				'last_status_check' => $last_status_check,
				'last_daily_run'    => $last_daily_run,
			)
		);

		// Get all scheduled CRONs for debugging
		$all_crons            = _get_cron_array();
		$wisewand_crons_found = array();
		foreach ( $all_crons as $timestamp => $cron ) {
			foreach ( $cron as $hook => $data ) {
				if ( strpos( $hook, 'wisewand' ) !== false ) {
					$wisewand_crons_found[ $hook ] = gmdate( 'Y-m-d H:i:s', $timestamp );
				}
			}
		}

		$this->logger->debug( 'All Wisewand CRONs found', $wisewand_crons_found );

		// Format 15-minute CRON info
		$status_check_info = array(
			'scheduled'    => $status_check_cron !== false,
			'last_run'     => $last_status_check ? human_time_diff( strtotime( $last_status_check ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' ) : __( 'Never', 'wisewand-ai-content-writer-seo-content-generator' ),
			'last_summary' => $last_status_summary ? json_decode( $last_status_summary, true ) : null,
		);

		if ( $status_check_cron ) {
			$time_diff = $status_check_cron - current_time( 'timestamp' );
			if ( $time_diff > 0 ) {
				$status_check_info['next_run'] = human_time_diff( current_time( 'timestamp' ), $status_check_cron );
			} else {
				$status_check_info['next_run'] = __( 'Overdue (will run soon)', 'wisewand-ai-content-writer-seo-content-generator' );
			}
			$status_check_info['next_run_timestamp'] = $status_check_cron;
		} else {
			$status_check_info['next_run']           = __( 'Not scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
			$status_check_info['next_run_timestamp'] = null;
		}

		// Format daily CRON info
		$daily_info = array(
			'scheduled'    => $daily_cron !== false,
			'last_run'     => $last_daily_run ? human_time_diff( strtotime( $last_daily_run ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' ) : __( 'Never', 'wisewand-ai-content-writer-seo-content-generator' ),
			'last_summary' => $last_daily_summary ? json_decode( $last_daily_summary, true ) : null,
		);

		if ( $daily_cron ) {
			$time_diff = $daily_cron - current_time( 'timestamp' );
			if ( $time_diff > 0 ) {
				$daily_info['next_run'] = human_time_diff( current_time( 'timestamp' ), $daily_cron );
			} else {
				$daily_info['next_run'] = __( 'Overdue (will run soon)', 'wisewand-ai-content-writer-seo-content-generator' );
			}
			$daily_info['next_run_timestamp'] = $daily_cron;
		} else {
			$daily_info['next_run']           = __( 'Not scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
			$daily_info['next_run_timestamp'] = null;
		}

		// Determine which ran most recently for display
		$most_recent_run     = null;
		$most_recent_summary = null;

		if ( $last_status_check && $last_daily_run ) {
			$most_recent_run     = strtotime( $last_status_check ) > strtotime( $last_daily_run ) ? $last_status_check : $last_daily_run;
			$most_recent_summary = strtotime( $last_status_check ) > strtotime( $last_daily_run ) ? $last_status_summary : $last_daily_summary;
		} elseif ( $last_status_check ) {
			$most_recent_run     = $last_status_check;
			$most_recent_summary = $last_status_summary;
		} elseif ( $last_daily_run ) {
			$most_recent_run     = $last_daily_run;
			$most_recent_summary = $last_daily_summary;
		}

		return array(
			// Legacy fields (for backward compatibility)
			'last_run'           => $most_recent_run ? human_time_diff( strtotime( $most_recent_run ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'wisewand-ai-content-writer-seo-content-generator' ) : __( 'Never', 'wisewand-ai-content-writer-seo-content-generator' ),
			'next_run'           => $status_check_info['next_run'], // Show 15-min CRON (runs most frequently)
			'next_run_timestamp' => $status_check_info['next_run_timestamp'],
			'last_summary'       => $most_recent_summary ? json_decode( $most_recent_summary, true ) : null,

			// Detailed CRON info (NEW)
			'status_check'       => $status_check_info,  // 15-minute CRON
			'daily'              => $daily_info,                // Daily CRON
			'debug_info'         => $wisewand_crons_found,
		);
	}

	private function get_status_icon( $status ) {
		$icons = array(
			'not_created' => '📅',
			'creating'    => '🔄',
			'generating'  => '🔄',
			'ready'       => '✅',
			'failed'      => '⚠️',
		);
		return $icons[ $status ] ?? '❓';
	}

	private function get_status_label( $status ) {
		$labels = array(
			'not_created' => __( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ),
			'creating'    => __( 'Creating', 'wisewand-ai-content-writer-seo-content-generator' ),
			'generating'  => __( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ),
			'ready'       => __( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ),
			'failed'      => __( 'Failed', 'wisewand-ai-content-writer-seo-content-generator' ),
		);
		return $labels[ $status ] ?? $status;
	}

	private function get_wordpress_status_label( $status ) {
		$labels = array(
			'publish' => __( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ),
			'draft'   => __( 'Draft', 'wisewand-ai-content-writer-seo-content-generator' ),
			'pending' => __( 'Pending', 'wisewand-ai-content-writer-seo-content-generator' ),
			'private' => __( 'Private', 'wisewand-ai-content-writer-seo-content-generator' ),
			'future'  => __( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ),
			'trash'   => __( 'Trash', 'wisewand-ai-content-writer-seo-content-generator' ),
		);
		return $labels[ $status ] ?? ucfirst( $status );
	}

	private function get_type_icon( $type ) {
		$icons = array(
			'blog'                         => '📝',
			'news'                         => '📰',
			'affiliation-product-review'   => '🛍️',
			'affiliation-compare-products' => '📊',
			'affiliation-top-product'      => '🏆',
			'categorypage'                 => '🏪',
			'categorypages'                => '🏪',
			'productpage'                  => '📦',
			'productpages'                 => '📦',
			'discoverarticles'             => '📱',
		);
		return $icons[ $type ] ?? '📄';
	}

	private function get_type_label( $type ) {
		$labels = array(
			'blog'                         => __( 'Blog Articles', 'wisewand-ai-content-writer-seo-content-generator' ),
			'news'                         => __( 'News Articles', 'wisewand-ai-content-writer-seo-content-generator' ),
			'affiliation-product-review'   => __( 'Product Reviews', 'wisewand-ai-content-writer-seo-content-generator' ),
			'affiliation-compare-products' => __( 'Compare Products', 'wisewand-ai-content-writer-seo-content-generator' ),
			'affiliation-top-product'      => __( 'Top Products', 'wisewand-ai-content-writer-seo-content-generator' ),
			'categorypage'                 => __( 'Category Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'categorypages'                => __( 'Category Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'productpage'                  => __( 'Product Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'productpages'                 => __( 'Product Pages', 'wisewand-ai-content-writer-seo-content-generator' ),
			'discoverarticles'             => __( 'Discover Articles', 'wisewand-ai-content-writer-seo-content-generator' ),
		);
		return $labels[ $type ] ?? ucfirst( $type );
	}
}
