<?php

namespace NeurogenesisTheme\QuickSetup\Steps;

use NeurogenesisTheme\Helpers\ThemeOptions;
use NeurogenesisTheme\QuickSetup\Step;

defined( 'ABSPATH' ) || exit;

final class PublishFirstPage extends Step {

	public function id(): string {
		return 'publish';
	}

	public function label(): string {
		return __( 'Publish your first page', 'thinko' );
	}

	public function url(): string {
		return admin_url( 'edit.php?post_type=page' );
	}

	public function completed(): bool {
		$filtered = $this->filtered_completed( 'neurogenesis_theme_quick_setup_publish_completed' );
		if ( null !== $filtered ) {
			return $filtered;
		}

		$started_at = (string) ThemeOptions::get( ThemeOptions::QUICK_SETUP_STARTED_AT, '' );

		// Imported demo content counts as "a page was added/imported".
		$imported = get_posts(
			array(
				'post_type'              => 'page',
				'post_status'            => 'publish',
				'posts_per_page'         => 1,
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'meta_query'             => array(
					array(
						'key'     => '_neurogenesis_theme_imported',
						'compare' => 'EXISTS',
					),
				),
			)
		);

		if ( ! empty( $imported ) ) {
			return true;
		}

		// Otherwise, require a newly-published page since theme activation.
		if ( '' === $started_at ) {
			return false;
		}

		$pages = get_posts(
			array(
				'post_type'              => 'page',
				'post_status'            => 'publish',
				'posts_per_page'         => 1,
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'date_query'             => array(
					array(
						'after'     => $started_at,
						'inclusive' => false,
					),
				),
			)
		);

		return ! empty( $pages );
	}
}
