<?php
/**
 * Admin list of pages/posts built with Aura Builder.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Admin;

use AuraBuilder\Storage\DocumentRepository;

final class PagesList {

	public function hooks(): void {
		// Priority 5: register top-level hub before other submenus attach to it.
		add_action( 'admin_menu', array( $this, 'menu' ), 5 );
	}

	public function menu(): void {
		$icon = defined( 'AURA_BUILDER_LOGO_64_URL' )
			? AURA_BUILDER_LOGO_64_URL
			: 'dashicons-layout';

		// Top-level menu opens the pages list (capability: edit_pages).
		// Settings uses a separate slug + manage_options — avoids WP blocking the whole plugin menu.
		add_menu_page(
			'Auranet Builder',
			'Auranet Builder',
			'edit_pages',
			'aura-builder-pages',
			array( $this, 'render' ),
			$icon,
			58
		);

		add_submenu_page(
			'aura-builder-pages',
			'Páginas do Builder',
			'Páginas',
			'edit_pages',
			'aura-builder-pages',
			array( $this, 'render' )
		);
	}

	public function render(): void {
		if ( ! \AuraBuilder\Support\Capabilities::can_use_builder() ) {
			wp_die(
				esc_html__( 'Sem permissão para acessar o Aura Builder. Use uma conta Administrador ou Editor.', 'auranet-page-theme-builder' ),
				esc_html__( 'Sem permissão', 'auranet-page-theme-builder' ),
				array( 'response' => 403 )
			);
		}

		$repo  = new DocumentRepository();
		$home  = \AuraBuilder\Admin\HomePageBridge::get_home_id();
		$items = $this->query_builder_posts();
		$logo  = defined( 'AURA_BUILDER_LOGO_64_URL' ) ? AURA_BUILDER_LOGO_64_URL : '';

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline" style="display:inline-flex;align-items:center;gap:8px">
				<?php if ( $logo ) : ?>
					<img src="<?php echo esc_url( $logo ); ?>" alt="" width="28" height="28" style="width:28px;height:28px;object-fit:contain;border-radius:6px;vertical-align:middle"/>
				<?php else : ?>
					<span class="dashicons dashicons-layout" style="font-size:28px;width:28px;height:28px;margin-right:6px"></span>
				<?php endif; ?>
				Páginas do Aura Builder
			</h1>
			<a href="<?php echo esc_url( admin_url( 'post-new.php?post_type=page' ) ); ?>" class="page-title-action">Nova página</a>
			<hr class="wp-header-end"/>

			<p style="color:#646970;max-width:60ch">
				Páginas e posts com o Builder ativo. Abra no editor visual ou veja no site.
				<?php if ( $home > 0 ) : ?>
					<br/><strong>Página inicial do Builder:</strong>
					<?php echo esc_html( get_the_title( $home ) ?: ( '#' . $home ) ); ?>
					— o Editor do tema (Aparência) redireciona para ela.
				<?php endif; ?>
			</p>

			<table class="wp-list-table widefat fixed striped table-view-list">
				<thead>
					<tr>
						<th scope="col" style="width:40%">Título</th>
						<th scope="col">Tipo</th>
						<th scope="col">Status</th>
						<th scope="col">Inicial</th>
						<th scope="col">Data</th>
						<th scope="col">Ações</th>
					</tr>
				</thead>
				<tbody>
				<?php if ( ! $items ) : ?>
					<tr>
						<td colspan="6">
							Nenhuma página com Aura Builder ainda.
							<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=page' ) ); ?>">Abrir páginas</a>
							e clique em <strong>Editar com Aura Builder</strong>.
						</td>
					</tr>
				<?php else : ?>
					<?php foreach ( $items as $post ) : ?>
						<?php
						$id      = (int) $post->ID;
						$edit    = admin_url( 'admin.php?page=aura-builder&post=' . $id );
						$view    = get_permalink( $id );
						$wp_edit = get_edit_post_link( $id, 'raw' );
						$is_home = $home === $id || ( (int) get_option( 'page_on_front' ) === $id && get_option( 'show_on_front' ) === 'page' );
						$enabled = $repo->is_enabled( $id );
						?>
						<tr>
							<td>
								<strong>
									<a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( get_the_title( $id ) ?: '(sem título)' ); ?></a>
								</strong>
								<?php if ( ! $enabled ) : ?>
									<span class="description"> — builder desativado</span>
								<?php endif; ?>
							</td>
							<td><?php echo esc_html( $post->post_type === 'page' ? 'Página' : 'Post' ); ?></td>
							<td><?php echo esc_html( get_post_status_object( $post->post_status )->label ?? $post->post_status ); ?></td>
							<td>
								<?php if ( $is_home ) : ?>
									<span style="color:#7c3aed;font-weight:700"><?php echo esc_html( '★ Sim' ); ?></span>
								<?php else : ?>
									<?php echo esc_html( '—' ); ?>
								<?php endif; ?>
							</td>
							<td><?php echo esc_html( get_the_date( '', $id ) ); ?></td>
							<td>
								<a class="button button-primary button-small" href="<?php echo esc_url( $edit ); ?>">Abrir no Builder</a>
								<?php if ( $view ) : ?>
									<a class="button button-small" href="<?php echo esc_url( $view ); ?>" target="_blank" rel="noopener">Ver</a>
								<?php endif; ?>
								<?php if ( $wp_edit ) : ?>
									<a class="button button-small" href="<?php echo esc_url( $wp_edit ); ?>">WP</a>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * @return list<\WP_Post>
	 */
	private function query_builder_posts(): array {
		// Posts with builder meta on.
		$q = new \WP_Query(
			array(
				'post_type'              => array( 'page', 'post' ),
				'post_status'            => array( 'publish', 'draft', 'pending', 'private', 'future' ),
				'posts_per_page'         => 200,
				'orderby'                => 'modified',
				'order'                  => 'DESC',
				'meta_query'             => array(
					array(
						'key'     => AURA_BUILDER_META_ON,
						'value'   => '1',
						'compare' => '=',
					),
				),
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
			)
		);
		return is_array( $q->posts ) ? $q->posts : array();
	}
}
