<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function enqueue_plugin_description_styles() {
	wp_enqueue_style( 'ai-content-wizard-plugin-description-style', AI_CONTENT_WIZARD_URL . 'css/plugin-description-styles.css', array(), AI_CONTENT_WIZARD_VERSION );
	wp_enqueue_style( 'ai-content-wizard-font-inter', 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap', array(), null );
}
add_action( 'admin_enqueue_scripts', 'enqueue_plugin_description_styles' );

if ( ! defined( 'AI_CONTENT_WIZARD_DEFAULT_FEED_IMAGE' ) ) {
	define( 'AI_CONTENT_WIZARD_DEFAULT_FEED_IMAGE', AI_CONTENT_WIZARD_URL . 'css/img/witch-hat.svg_' );
}

function ai_content_wizard_get_feed_image( $item ) {
	$image = '';

	if ( method_exists( $item, 'get_thumbnail' ) ) {
		$thumb = $item->get_thumbnail();
		if ( ! empty( $thumb ) ) {
			$image = esc_url_raw( $thumb );
		}
	}

	if ( ! $image && method_exists( $item, 'get_enclosure' ) ) {
		$enclosure = $item->get_enclosure();
		if ( $enclosure && $enclosure->get_link() ) {
			$image = esc_url_raw( $enclosure->get_link() );
		}
	}

	if ( ! $image ) {
		$media_content = $item->get_item_tags( 'http://search.yahoo.com/mrss/', 'content' );
		if ( ! empty( $media_content[0]['attribs']['']['url'] ) ) {
			$image = esc_url_raw( $media_content[0]['attribs']['']['url'] );
		}
	}

	if ( ! $image ) {
		$media_thumb = $item->get_item_tags( 'http://search.yahoo.com/mrss/', 'thumbnail' );
		if ( ! empty( $media_thumb[0]['attribs']['']['url'] ) ) {
			$image = esc_url_raw( $media_thumb[0]['attribs']['']['url'] );
		}
	}

	if ( ! $image ) {
		$content = $item->get_content();
		if ( preg_match( '/<img[^>]+src\s*=\s*["\']([^"\']+)/i', $content, $matches ) ) {
			$image = esc_url_raw( $matches[1] );
		}
	}

	return $image ? $image : AI_CONTENT_WIZARD_DEFAULT_FEED_IMAGE;
}

function ai_content_wizard_render_icon( $slug ) {
	switch ( $slug ) {
		case 'spark':
			return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 2l2.6 7.6L26 12l-7.4 2.4L16 22l-2.6-7.6L6 12l7.4-2.4L16 2z" fill="currentColor" fill-opacity="0.85"/></svg>';
		case 'workflow':
			return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 6h12v6H10zM4 20h12v6H4zM18 20h10v6H18z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M16 12v6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M10 23h8M22 23h4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
		case 'shield':
			return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 3l10 4v8c0 7.4-4.3 12-10 14-5.7-2-10-6.6-10-14V7z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M12 16l3 3 6-7" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
		default:
			return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="16" r="14" stroke="currentColor" stroke-width="2" opacity="0.65"/><path d="M16 8v8l5 3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
	}
}

function ai_content_wizard_main_page() {
	include_once ABSPATH . WPINC . '/feed.php';
	$rss_items = fetch_feed( 'https://aiwizard.buyreadysite.com/blog/feed/' );
	$blog_items = array();
	if ( ! is_wp_error( $rss_items ) ) {
		$maxitems = $rss_items->get_item_quantity( 3 );
		$items = $rss_items->get_items( 0, $maxitems );
		foreach ( $items as $item ) {
			$blog_items[] = array(
				'title' => $item->get_title(),
				'link'  => $item->get_permalink(),
				'date'  => $item->get_date( 'M d, Y' ),
				'image' => ai_content_wizard_get_feed_image( $item ),
			);
		}
	}

	global $wpdb;
	$logs_table = $wpdb->prefix . 'ai_content_wizard_posts_logs';
	$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $logs_table ) );
	$stats = array(
		'total_posts'   => 0,
		'recent_posts'  => 0,
		'avg_tokens'    => 0,
		'active_models' => 'OpenAI Turbo Series',
	);
	if ( $table_exists === $logs_table ) {
		$stats['total_posts']  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$logs_table}" );
		$stats['recent_posts'] = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$logs_table} WHERE generation_time >= DATE_SUB( NOW(), INTERVAL 7 DAY )" );

		$tokens_column_exists = $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM {$logs_table} LIKE %s", 'tokens_used' ) );
		if ( $tokens_column_exists ) {
			$stats['avg_tokens'] = (int) $wpdb->get_var( "SELECT AVG(tokens_used) FROM {$logs_table} WHERE tokens_used > 0" );
		}
	}

	$quick_links = array(
		array(
			'label' => __( 'Single Post Studio', 'ai-content-wizard' ),
			'url'   => admin_url( 'admin.php?page=ai_content_wizard_create_post' ),
			'desc'  => __( 'Craft a blog post with guided brief + image prompts.', 'ai-content-wizard' ),
		),
		array(
			'label' => __( 'API Settings', 'ai-content-wizard' ),
			'url'   => admin_url( 'admin.php?page=ai_content_wizard_api_settings' ),
			'desc'  => __( 'Connect OpenAI and preview locked providers.', 'ai-content-wizard' ),
		),
		array(
			'label' => __( 'Statistics', 'ai-content-wizard' ),
			'url'   => admin_url( 'admin.php?page=ai_content_wizard_statistics' ),
			'desc'  => __( 'Track drafts, failures and token burn.', 'ai-content-wizard' ),
		),
	);

	$focus_cards = array(
		array(
			'title' => __( 'SEO Playbooks', 'ai-content-wizard' ),
			'desc'  => __( 'Auto-generate outlines, FAQs, meta tags and internal links for each brief.', 'ai-content-wizard' ),
			'icon'  => ai_content_wizard_render_icon( 'spark' ),
		),
		array(
			'title' => __( 'Guided Workflows', 'ai-content-wizard' ),
			'desc'  => __( 'Switch between quick drafts and research-heavy longreads in Pro mode.', 'ai-content-wizard' ),
			'icon'  => ai_content_wizard_render_icon( 'workflow' ),
		),
		array(
			'title' => __( 'Compliance Guardrails', 'ai-content-wizard' ),
			'desc'  => __( 'Automatic brand voice, safe-search filters, plagiarism checkpoints.', 'ai-content-wizard' ),
			'icon'  => ai_content_wizard_render_icon( 'shield' ),
		),
	);

	$upgrade_features = array(
		__( 'Unlock Gemini 2.0 Flash, Grok 3 Beta, Claude 3.5 Sonnet, DeepSeek-R1 and custom OpenAI endpoints.', 'ai-content-wizard' ),
		__( '40+ language auto-translation with Polylang/WPML syncing and locale-aware SEO fields.', 'ai-content-wizard' ),
		__( 'Content Planner: build multi-week calendars, assign owners and auto-schedule publications.', 'ai-content-wizard' ),
		__( 'Content Streams: transform RSS / Telegram feeds into moderated drafts with PromoPilot approvals.', 'ai-content-wizard' ),
		__( 'Expert Longread Studio: 20–100k character research flows with fact cards, TOC and section rewrites.', 'ai-content-wizard' ),
		__( 'Advanced media + compliance: watermarks, brand packs, per-workspace token budgets and audit logs.', 'ai-content-wizard' ),
	);

	$support_links = array(
		array(
			'label' => __( 'Telegram', 'ai-content-wizard' ),
			'url'   => 'https://t.me/buyreadysite',
		),
		array(
			'label' => __( 'Email', 'ai-content-wizard' ),
			'url'   => 'mailto:aiwizard@buyreadysite.com',
		),
		array(
			'label' => __( 'YouTube', 'ai-content-wizard' ),
			'url'   => 'https://www.youtube.com/@BuyReadySite_com',
		),
	);
	/* translators: %s is the current Lite plugin version. */
	$lite_release_label = sprintf( __( 'What is new in Lite %s', 'ai-content-wizard' ), AI_CONTENT_WIZARD_VERSION );
	?>
	<div class="ai-content-wizard-dashboard">
		<div class="aiw-hero">
			<div class="aiw-hero-text">
				<p class="aiw-pill">
					<?php esc_html_e( 'Lite Edition - OpenAI powered', 'ai-content-wizard' ); ?>
				</p>
				<h1><?php esc_html_e( 'Create polished posts without leaving WordPress', 'ai-content-wizard' ); ?></h1>
				<p class="aiw-hero-subtitle">
					<?php esc_html_e( 'Brief, generate, optimise and publish in one studio. Upgrade anytime to copy the glassmorphism UI and automations from the Pro flagship.', 'ai-content-wizard' ); ?>
				</p>
				<div class="aiw-hero-actions">
					<a class="aiw-btn aiw-btn-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=ai_content_wizard_create_post' ) ); ?>">
						<?php esc_html_e( 'Launch Single Post Studio', 'ai-content-wizard' ); ?>
					</a>
					<a class="aiw-btn aiw-btn-ghost" href="<?php echo esc_url( admin_url( 'admin.php?page=ai_content_wizard_api_settings' ) ); ?>">
						<?php esc_html_e( 'Configure API access', 'ai-content-wizard' ); ?>
					</a>
				</div>
				<ul class="aiw-hero-meta">
					<li>
						<?php
						/* translators: %s is the formatted count of generated posts. */
						printf( esc_html__( '%s total posts crafted', 'ai-content-wizard' ), number_format_i18n( $stats['total_posts'] ) );
						?>
					</li>
					<li>
						<?php
						/* translators: %s is the number of drafts created this week. */
						printf( esc_html__( '%s drafts this week', 'ai-content-wizard' ), number_format_i18n( $stats['recent_posts'] ) );
						?>
					</li>
					<li>
						<?php
						/* translators: %s is the approximate tokens spent per article. */
						printf( esc_html__( '~%s tokens / article', 'ai-content-wizard' ), number_format_i18n( $stats['avg_tokens'] ?: 3200 ) );
						?>
					</li>
				</ul>
			</div>
			<div class="aiw-hero-highlight">
				<p class="aiw-pill ghost"><?php echo esc_html( $lite_release_label ); ?></p>
				<h3><?php esc_html_e( 'Lite 2.5 mirrors the Pro workspace while keeping premium automations upgrade-only.', 'ai-content-wizard' ); ?></h3>
				<ul>
					<li><?php esc_html_e( 'Pro unlocks the newest models: Gemini 2.0, Grok 3, Claude 3.5, DeepSeek-R1 and extended OpenAI routing.', 'ai-content-wizard' ); ?></li>
					<li><?php esc_html_e( 'Auto-translate into 40+ languages with Polylang / WPML sync and locale-aware SEO tones.', 'ai-content-wizard' ); ?></li>
					<li><?php esc_html_e( 'Content Planner, Streams and Expert Longread remain visible here but require an upgrade to run.', 'ai-content-wizard' ); ?></li>
				</ul>
				<a class="aiw-btn aiw-btn-link" target="_blank" href="https://aiwizard.buyreadysite.com/pricing/">
					<?php esc_html_e( 'Compare plans →', 'ai-content-wizard' ); ?>
				</a>
			</div>
		</div>

		<?php if ( class_exists( 'AiContentWizard_PromoPilot' ) ) : ?>
			<div class="aiw-banner-card">
				<?php AiContentWizard_PromoPilot::render_dashboard_banner(); ?>
			</div>
		<?php endif; ?>

		<div class="aiw-grid aiw-stat-grid">
			<div class="aiw-card aiw-stat-card">
				<span class="aiw-label"><?php esc_html_e( 'Total Posts', 'ai-content-wizard' ); ?></span>
				<strong><?php echo esc_html( number_format_i18n( max( 1, $stats['total_posts'] ) ) ); ?></strong>
				<p><?php esc_html_e( 'Includes drafts generated inside the Lite studio.', 'ai-content-wizard' ); ?></p>
			</div>
			<div class="aiw-card aiw-stat-card">
				<span class="aiw-label"><?php esc_html_e( 'This Week', 'ai-content-wizard' ); ?></span>
				<strong><?php echo esc_html( number_format_i18n( $stats['recent_posts'] ) ); ?></strong>
				<p><?php esc_html_e( 'Recent requests. Reset when cache is cleared.', 'ai-content-wizard' ); ?></p>
			</div>
			<div class="aiw-card aiw-stat-card">
				<span class="aiw-label"><?php esc_html_e( 'Avg. tokens', 'ai-content-wizard' ); ?></span>
				<strong><?php echo esc_html( number_format_i18n( $stats['avg_tokens'] ?: 3200 ) ); ?></strong>
				<p><?php esc_html_e( 'Helpful to estimate OpenAI spend per article.', 'ai-content-wizard' ); ?></p>
			</div>
			<div class="aiw-card aiw-stat-card">
				<span class="aiw-label"><?php esc_html_e( 'Active provider', 'ai-content-wizard' ); ?></span>
				<strong><?php echo esc_html( $stats['active_models'] ); ?></strong>
				<p><?php esc_html_e( 'Gemini / Grok / Claude shown as locked until you upgrade.', 'ai-content-wizard' ); ?></p>
			</div>
		</div>

		<div class="aiw-section">
			<div class="aiw-section-header">
				<div>
					<p class="aiw-pill ghost"><?php esc_html_e( 'Workflow', 'ai-content-wizard' ); ?></p>
					<h2><?php esc_html_e( 'Stay in flow with curated actions', 'ai-content-wizard' ); ?></h2>
				</div>
				<a class="aiw-btn aiw-btn-link" href="<?php echo esc_url( admin_url( 'admin.php?page=ai_content_wizard_create_post' ) ); ?>">
					<?php esc_html_e( 'Open generator', 'ai-content-wizard' ); ?>
				</a>
			</div>
			<div class="aiw-grid aiw-focus-grid">
				<?php foreach ( $focus_cards as $card ) : ?>
					<div class="aiw-card aiw-focus-card">
						<span class="aiw-focus-icon"><?php echo $card['icon']; ?></span>
						<h3><?php echo esc_html( $card['title'] ); ?></h3>
						<p><?php echo esc_html( $card['desc'] ); ?></p>
					</div>
				<?php endforeach; ?>
			</div>
		</div>

		<div class="aiw-grid aiw-quick-links">
			<?php foreach ( $quick_links as $link ) : ?>
				<a class="aiw-card aiw-quick-link" href="<?php echo esc_url( $link['url'] ); ?>">
					<span><?php echo esc_html( $link['label'] ); ?></span>
					<p><?php echo esc_html( $link['desc'] ); ?></p>
					<span class="aiw-arrow">→</span>
				</a>
			<?php endforeach; ?>
		</div>

		<div class="aiw-section aiw-upgrade">
			<p class="aiw-pill ghost"><?php esc_html_e( 'Lite vs Pro', 'ai-content-wizard' ); ?></p>
			<h2><?php esc_html_e( 'Pro includes locked providers, planners and automation', 'ai-content-wizard' ); ?></h2>
			<p><?php esc_html_e( 'You already see the refreshed UI - upgrading simply unlocks every tile, Gemini/Grok access plus PromoPilot campaigns built for agencies.', 'ai-content-wizard' ); ?></p>
			<div class="aiw-upgrade-grid">
				<?php foreach ( $upgrade_features as $feature ) : ?>
					<div class="aiw-upgrade-item">
						<span class="aiw-dot"></span>
						<?php echo esc_html( $feature ); ?>
					</div>
				<?php endforeach; ?>
			</div>
			<a class="aiw-btn aiw-btn-primary" target="_blank" href="https://aiwizard.buyreadysite.com/pricing/">
				<?php esc_html_e( 'Start 5-day Pro trial', 'ai-content-wizard' ); ?>
			</a>
		</div>

		<div class="aiw-section">
			<div class="aiw-section-header">
				<div>
					<p class="aiw-pill ghost"><?php esc_html_e( 'Knowledge hub', 'ai-content-wizard' ); ?></p>
					<h2><?php esc_html_e( 'Latest changelog & growth ideas', 'ai-content-wizard' ); ?></h2>
				</div>
				<a class="aiw-btn aiw-btn-link" target="_blank" href="https://aiwizard.buyreadysite.com/blog/">
					<?php esc_html_e( 'Visit blog', 'ai-content-wizard' ); ?>
				</a>
			</div>
			<div class="aiw-grid aiw-blog-grid">
				<?php if ( empty( $blog_items ) ) : ?>
					<div class="aiw-card aiw-blog-card">
						<p><?php esc_html_e( 'Feed is loading. Check back shortly for the newest release notes.', 'ai-content-wizard' ); ?></p>
					</div>
				<?php else : ?>
					<?php foreach ( $blog_items as $post ) : ?>
						<a class="aiw-card aiw-blog-card" href="<?php echo esc_url( $post['link'] ); ?>" target="_blank">
							<div class="aiw-blog-cover" style="background-image:url('<?php echo esc_url( $post['image'] ); ?>');"></div>
							<h3><?php echo esc_html( $post['title'] ); ?></h3>
							<span class="aiw-blog-date"><?php echo esc_html( $post['date'] ); ?></span>
						</a>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>
		</div>

		<div class="aiw-section aiw-support">
			<div class="aiw-grid aiw-support-grid">
				<div class="aiw-card">
					<p class="aiw-pill ghost"><?php esc_html_e( 'Need help?', 'ai-content-wizard' ); ?></p>
					<h3><?php esc_html_e( 'Direct support channels', 'ai-content-wizard' ); ?></h3>
					<ul class="aiw-contact-list">
						<li><?php esc_html_e( 'Phone: +380 (73) 99-64-959', 'ai-content-wizard' ); ?></li>
						<?php foreach ( $support_links as $link ) : ?>
							<li><a href="<?php echo esc_url( $link['url'] ); ?>" target="_blank"><?php echo esc_html( $link['label'] ); ?></a></li>
						<?php endforeach; ?>
					</ul>
				</div>
				<div class="aiw-card">
					<p class="aiw-pill ghost"><?php esc_html_e( 'Docs & Academy', 'ai-content-wizard' ); ?></p>
					<h3><?php esc_html_e( 'Playbooks and tutorials', 'ai-content-wizard' ); ?></h3>
					<ul class="aiw-doc-links">
						<li><a href="https://aiwizard.buyreadysite.com/docs/" target="_blank"><?php esc_html_e( 'Official documentation', 'ai-content-wizard' ); ?></a></li>
						<li><a href="https://aiwizard.buyreadysite.com/faq/" target="_blank"><?php esc_html_e( 'FAQ & troubleshooting', 'ai-content-wizard' ); ?></a></li>
						<li><a href="https://aiseoautooptimize.pro/wiki-ai-content-wizard/" target="_blank"><?php esc_html_e( 'Partner & distributor wiki', 'ai-content-wizard' ); ?></a></li>
					</ul>
				</div>
			</div>
		</div>
	</div>
	<?php
}

function ai_content_wizard_add_footer_credit() {
	if ( ai_content_wizard_get_setting( 'ai_content_wizard_enable_footer_credit', 1 ) ) {
		echo "<!-- This site's content is enhanced by AI technologies provided by AI Content Wizard at BuyReadySite.com -->";
		echo '<div id="ai-content-wizard-footer-credit" style="text-align: center; padding: 20px 0; font-size: 14px;">Proudly powered by <a href="https://aiwizard.buyreadysite.com" target="_blank" style="text-decoration: underline;">AI Content Wizard</a> from BuyReadySite.com</div>';
	}
}
add_action( 'wp_footer', 'ai_content_wizard_add_footer_credit' );

