<?php

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

/**
 * Changeloger Block Analytics Admin Page
 *
 * Displays analytics, usage pages, and action buttons for the cha/changeloger block.
 */
class Changeloger_Block_Analytics {

	/**
	 * Block name identifier.
	 *
	 * @var string
	 */
	private $block_name = 'cha/changeloger';

	/**
	 * Block search pattern in post content.
	 *
	 * @var string
	 */
	private $block_pattern = 'wp:cha/changeloger';

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
	}

	/**
	 * Enqueue page-specific styles and scripts
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_assets( string $hook ): void {
		if ( 'changeloger_page_changeloger-block' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'cha-block-analytics',
			plugins_url( 'assets/css/block-analytics.css', dirname( __FILE__ ) ),
			[],
			defined( 'CHANGELOGER_VERSION' ) ? CHANGELOGER_VERSION : '1.0.0'
		);

		// Inline script for "Add Block to Page" buttons.
		wp_enqueue_script( 'wp-api-request' );
		wp_add_inline_script(
			'wp-api-request',
			sprintf(
				'window.chaBlockAnalytics = %s;',
				wp_json_encode( [
					'adminUrl' => admin_url(),
					'restUrl'  => rest_url( 'wp/v2/pages' ),
					'nonce'    => wp_create_nonce( 'wp_rest' ),
				] )
			)
		);
	}

	/**
	 * Render the block analytics page
	 *
	 * @return void
	 */
	public function render_page(): void {
		$analytics    = $this->get_block_analytics();
		$usage_pages  = $this->get_usage_pages();
		$block_page   = $this->get_block_page();
		$has_block    = ! empty( $block_page );

		?>
		<div class="cha-page-wrap cha-block-analytics">
			<!-- Header -->
			<div class="cha-page-header">
				<div class="cha-page-header-left">
					<div class="cha-page-header-icon">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="28" height="28">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
						</svg>
					</div>
					<div class="cha-page-header-content">
						<h1><?php esc_html_e( 'Changeloger Block', 'changeloger' ); ?></h1>
						<p class="cha-page-header-subtitle"><?php esc_html_e( 'Analytics & usage overview for the Changeloger block', 'changeloger' ); ?></p>
					</div>
				</div>
				<div class="cha-page-header-right">
						<a href="#" class="cha-btn cha-btn-primary cha-btn-lg cha-add-block-btn" id="cha-block-action-btn">
							<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="18" height="18">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
							</svg>
							<?php esc_html_e( 'Add Block to Page', 'changeloger' ); ?>
						</a>
				</div>
			</div>

			<!-- Stats Grid -->
			<div class="cha-stats-cards">
				<!-- Total Pages -->
				<div class="cha-stat-card" id="cha-stat-total-pages">
					<div class="cha-stat-icon" style="background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); color: #3b82f6;">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
						</svg>
					</div>
					<div class="cha-stat-content">
						<span class="cha-stat-number"><?php echo esc_html( $analytics['total_pages'] ); ?></span>
						<span class="cha-stat-label"><?php esc_html_e( 'Pages Using Block', 'changeloger' ); ?></span>
					</div>
				</div>

				<!-- Published -->
				<div class="cha-stat-card" id="cha-stat-published">
					<div class="cha-stat-icon" style="background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%); color: #10b981;">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
						</svg>
					</div>
					<div class="cha-stat-content">
						<span class="cha-stat-number"><?php echo esc_html( $analytics['published'] ); ?></span>
						<span class="cha-stat-label"><?php esc_html_e( 'Published', 'changeloger' ); ?></span>
					</div>
				</div>

				<!-- Draft -->
				<div class="cha-stat-card" id="cha-stat-drafts">
					<div class="cha-stat-icon" style="background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); color: #f59e0b;">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
						</svg>
					</div>
					<div class="cha-stat-content">
						<span class="cha-stat-number"><?php echo esc_html( $analytics['draft'] ); ?></span>
						<span class="cha-stat-label"><?php esc_html_e( 'Drafts', 'changeloger' ); ?></span>
					</div>
				</div>

				<!-- Post Types -->
				<div class="cha-stat-card" id="cha-stat-post-types">
					<div class="cha-stat-icon" style="background: linear-gradient(135deg, #fdf4ff 0%, #f3e8ff 100%); color: #a855f7;">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
						</svg>
					</div>
					<div class="cha-stat-content">
						<span class="cha-stat-number"><?php echo esc_html( $analytics['post_types'] ); ?></span>
						<span class="cha-stat-label"><?php esc_html_e( 'Post Types', 'changeloger' ); ?></span>
					</div>
				</div>
			</div>

			<!-- Main Content Grid -->
			<div class="cha-ba-content-grid">
				<!-- Left Column: Usage Pages Table -->
				<div class="cha-ba-main-content">
					<div class="cha-ba-card">
						<div class="cha-ba-card-header">
							<div class="cha-ba-card-header-left">
								<h2><?php esc_html_e( 'Usage Pages', 'changeloger' ); ?></h2>
								<span class="cha-ba-count-badge"><?php echo esc_html( $analytics['total_pages'] ); ?></span>
							</div>
						</div>
						<div class="cha-ba-card-body cha-ba-no-padding">
							<?php if ( ! empty( $usage_pages ) ) : ?>
								<table class="cha-ba-table" id="cha-block-usage-table">
									<thead>
										<tr>
											<th><?php esc_html_e( 'Page Title', 'changeloger' ); ?></th>
											<th><?php esc_html_e( 'Post Type', 'changeloger' ); ?></th>
											<th><?php esc_html_e( 'Status', 'changeloger' ); ?></th>
											<th><?php esc_html_e( 'Date', 'changeloger' ); ?></th>
											<th><?php esc_html_e( 'Actions', 'changeloger' ); ?></th>
										</tr>
									</thead>
									<tbody>
										<?php foreach ( $usage_pages as $page ) : ?>
											<tr>
												<td>
													<div class="cha-ba-page-title">
														<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="16" height="16">
															<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
														</svg>
														<a href="<?php echo esc_url( get_edit_post_link( $page['ID'] ) ); ?>">
															<?php echo esc_html( $page['title'] ); ?>
														</a>
													</div>
												</td>
												<td>
													<span class="cha-ba-type-badge"><?php echo esc_html( $page['post_type'] ); ?></span>
												</td>
												<td>
													<span class="cha-ba-status-dot cha-ba-status-<?php echo esc_attr( $page['status_raw'] ); ?>">
														<?php echo esc_html( $page['status'] ); ?>
													</span>
												</td>
												<td>
													<span class="cha-ba-date"><?php echo esc_html( $page['date'] ); ?></span>
												</td>
												<td>
													<div class="cha-ba-actions">
														<a href="<?php echo esc_url( get_edit_post_link( $page['ID'] ) ); ?>" class="cha-ba-action-link" title="<?php esc_attr_e( 'Edit', 'changeloger' ); ?>">
															<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="15" height="15">
																<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
															</svg>
														</a>
														<?php if ( 'publish' === $page['status_raw'] ) : ?>
															<a href="<?php echo esc_url( get_permalink( $page['ID'] ) ); ?>" class="cha-ba-action-link" target="_blank" title="<?php esc_attr_e( 'View', 'changeloger' ); ?>">
																<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="15" height="15">
																	<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
																</svg>
															</a>
														<?php endif; ?>
													</div>
												</td>
											</tr>
										<?php endforeach; ?>
									</tbody>
								</table>
							<?php else : ?>
								<div class="cha-ba-empty-state">
									<div class="cha-ba-empty-icon">
										<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="48" height="48">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
										</svg>
									</div>
									<h3><?php esc_html_e( 'No pages found', 'changeloger' ); ?></h3>
									<p><?php esc_html_e( 'The Changeloger block has not been added to any page yet.', 'changeloger' ); ?></p>
									<a href="#" class="cha-btn cha-btn-primary cha-add-block-btn">
										<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="16" height="16">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
										</svg>
										<?php esc_html_e( 'Add Block to Page', 'changeloger' ); ?>
									</a>
								</div>
							<?php endif; ?>
						</div>
					</div>
				</div>

				<!-- Right Column: Block Info & Details -->
				<div class="cha-ba-sidebar">
					<!-- Block Info Card -->
					<div class="cha-ba-card cha-ba-block-info-card">
						<div class="cha-ba-card-header">
							<h2><?php esc_html_e( 'Block Information', 'changeloger' ); ?></h2>
						</div>
						<div class="cha-ba-card-body">
							<ul class="cha-ba-info-list">
								<li>
									<span class="cha-ba-info-label"><?php esc_html_e( 'Block Name', 'changeloger' ); ?></span>
									<span class="cha-ba-info-value">
										<code><?php echo esc_html( $this->block_name ); ?></code>
									</span>
								</li>
								<li>
									<span class="cha-ba-info-label"><?php esc_html_e( 'Title', 'changeloger' ); ?></span>
									<span class="cha-ba-info-value"><?php esc_html_e( 'Changeloger', 'changeloger' ); ?></span>
								</li>
								<li>
									<span class="cha-ba-info-label"><?php esc_html_e( 'Category', 'changeloger' ); ?></span>
									<span class="cha-ba-info-value"><?php esc_html_e( 'Widgets', 'changeloger' ); ?></span>
								</li>
								<li>
									<span class="cha-ba-info-label"><?php esc_html_e( 'Status', 'changeloger' ); ?></span>
									<span class="cha-ba-info-value">
										<?php if ( $has_block ) : ?>
											<span class="cha-ba-active-badge">
												<span class="cha-ba-active-dot"></span>
												<?php esc_html_e( 'Active', 'changeloger' ); ?>
											</span>
										<?php else : ?>
											<span class="cha-ba-inactive-badge">
												<?php esc_html_e( 'Not In Use', 'changeloger' ); ?>
											</span>
										<?php endif; ?>
									</span>
								</li>
							</ul>
						</div>
					</div>

					<!-- Post Type Breakdown Card -->
					<?php if ( ! empty( $analytics['type_breakdown'] ) ) : ?>
						<div class="cha-ba-card">
							<div class="cha-ba-card-header">
								<h2><?php esc_html_e( 'Post Type Breakdown', 'changeloger' ); ?></h2>
							</div>
							<div class="cha-ba-card-body">
								<div class="cha-ba-breakdown-list">
									<?php foreach ( $analytics['type_breakdown'] as $type => $count ) : ?>
										<?php
										$post_type_obj = get_post_type_object( $type );
										$type_label    = $post_type_obj ? $post_type_obj->labels->singular_name : ucfirst( $type );
										$percentage    = $analytics['total_pages'] > 0 ? round( ( $count / $analytics['total_pages'] ) * 100 ) : 0;
										?>
										<div class="cha-ba-breakdown-item">
											<div class="cha-ba-breakdown-header">
												<span class="cha-ba-breakdown-label"><?php echo esc_html( $type_label ); ?></span>
												<span class="cha-ba-breakdown-count"><?php echo esc_html( $count ); ?></span>
											</div>
											<div class="cha-ba-breakdown-bar">
												<div class="cha-ba-breakdown-fill" style="width: <?php echo esc_attr( $percentage ); ?>%;"></div>
											</div>
										</div>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					<?php endif; ?>

					<!-- Quick Actions Card -->
					<div class="cha-ba-card">
						<div class="cha-ba-card-header">
							<h2><?php esc_html_e( 'Quick Actions', 'changeloger' ); ?></h2>
						</div>
						<div class="cha-ba-card-body">
							<div class="cha-ba-quick-actions">
								<?php if ( $has_block ) : ?>
									<a href="<?php echo esc_url( get_edit_post_link( $block_page['ID'] ) ); ?>" class="cha-ba-quick-action" id="cha-edit-block-page">
										<div class="cha-ba-qa-icon" style="background: #dbeafe; color: #2563eb;">
											<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
												<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
											</svg>
										</div>
										<span><?php esc_html_e( 'Edit Block Page', 'changeloger' ); ?></span>
									</a>
								<?php endif; ?>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=changeloger-releases' ) ); ?>" class="cha-ba-quick-action" id="cha-manage-releases">
									<div class="cha-ba-qa-icon" style="background: #ede9fe; color: #7c3aed;">
										<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
										</svg>
									</div>
									<span><?php esc_html_e( 'Manage Releases', 'changeloger' ); ?></span>
								</a>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=changeloger-settings' ) ); ?>" class="cha-ba-quick-action" id="cha-block-settings">
									<div class="cha-ba-qa-icon" style="background: #f3f4f6; color: #6b7280;">
										<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
										</svg>
									</div>
									<span><?php esc_html_e( 'Block Settings', 'changeloger' ); ?></span>
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<script>
		( function() {
			document.querySelectorAll( '.cha-add-block-btn' ).forEach( function( btn ) {
				btn.addEventListener( 'click', function( e ) {
					e.preventDefault();

					if ( btn.dataset.loading ) return;
					btn.dataset.loading = 'true';

					var originalHtml = btn.innerHTML;
					btn.innerHTML = '<span class="cha-spinner"></span> Creating…';
					btn.style.pointerEvents = 'none';

					var config = window.chaBlockAnalytics || {};

					fetch( config.restUrl, {
						method: 'POST',
						credentials: 'same-origin',
						headers: {
							'Content-Type': 'application/json',
							'X-WP-Nonce': config.nonce,
						},
						body: JSON.stringify( {
							title: 'Changelog',
							status: 'draft',
						} ),
					} )
					.then( function( r ) { return r.json(); } )
					.then( function( data ) {
						if ( data && data.id ) {
							window.location.href = config.adminUrl + 'post.php?post=' + data.id + '&action=edit&cha_add_block=changeloger';
						} else {
							throw new Error( data.message || 'Failed to create page.' );
						}
					} )
					.catch( function( err ) {
						alert( 'Error: ' + err.message );
						btn.innerHTML = originalHtml;
						btn.style.pointerEvents = '';
						delete btn.dataset.loading;
					} );
				} );
			} );
		} )();
		</script>
		<?php
	}

	/**
	 * Get block analytics data
	 *
	 * @return array
	 */
	private function get_block_analytics(): array {
		global $wpdb;

		// Count all posts containing the changeloger block by status.
		$sql = "SELECT p.post_status, p.post_type, COUNT(*) as count
				FROM {$wpdb->posts} p
				WHERE p.post_content LIKE %s
				AND p.post_status IN ('publish', 'draft', 'private', 'pending')
				GROUP BY p.post_status, p.post_type";

		$results = $wpdb->get_results(
			$wpdb->prepare( $sql, '%' . $wpdb->esc_like( $this->block_pattern ) . '%' ),
			ARRAY_A
		);

		$total     = 0;
		$published = 0;
		$draft     = 0;
		$types     = [];

		foreach ( $results as $row ) {
			$count = (int) $row['count'];
			$total += $count;

			if ( 'publish' === $row['post_status'] ) {
				$published += $count;
			}
			if ( 'draft' === $row['post_status'] ) {
				$draft += $count;
			}

			if ( ! isset( $types[ $row['post_type'] ] ) ) {
				$types[ $row['post_type'] ] = 0;
			}
			$types[ $row['post_type'] ] += $count;
		}

		// Sort by count descending.
		arsort( $types );

		return [
			'total_pages'    => $total,
			'published'      => $published,
			'draft'          => $draft,
			'post_types'     => count( $types ),
			'type_breakdown' => $types,
		];
	}

	/**
	 * Get pages using the changeloger block
	 *
	 * @return array
	 */
	private function get_usage_pages(): array {
		global $wpdb;

		$sql = "SELECT p.ID, p.post_title, p.post_type, p.post_date, p.post_status
				FROM {$wpdb->posts} p
				WHERE p.post_content LIKE %s
				AND p.post_status IN ('publish', 'draft', 'private', 'pending')
				ORDER BY p.post_date DESC
				LIMIT 20";

		$results = $wpdb->get_results(
			$wpdb->prepare( $sql, '%' . $wpdb->esc_like( $this->block_pattern ) . '%' )
		);

		$pages = [];
		foreach ( $results as $result ) {
			$post_type_obj = get_post_type_object( $result->post_type );
			$pages[] = [
				'ID'         => $result->ID,
				'title'      => $result->post_title ?: __( '(no title)', 'changeloger' ),
				'post_type'  => $post_type_obj ? $post_type_obj->labels->singular_name : ucfirst( $result->post_type ),
				'status'     => ucfirst( $result->post_status ),
				'status_raw' => $result->post_status,
				'date'       => human_time_diff( strtotime( $result->post_date ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'changeloger' ),
			];
		}

		return $pages;
	}

	/**
	 * Get the first published page containing the changeloger block
	 *
	 * @return array|null
	 */
	private function get_block_page(): ?array {
		global $wpdb;

		$sql = "SELECT p.ID, p.post_title
				FROM {$wpdb->posts} p
				WHERE p.post_content LIKE %s
				AND p.post_status = 'publish'
				ORDER BY p.post_date ASC
				LIMIT 1";

		$result = $wpdb->get_row(
			$wpdb->prepare( $sql, '%' . $wpdb->esc_like( $this->block_pattern ) . '%' )
		);

		if ( ! $result ) {
			return null;
		}

		return [
			'ID'    => $result->ID,
			'title' => $result->post_title,
		];
	}
}
