<?php

declare(strict_types=1);

namespace ProudNerds\Helpers;

use Timber\Post;
use Timber\Timber;

/**
 * Class: ArchiveHooks.
 *
 * Hooks relating to the archive pages can be added and altered here.
 */
class ArchiveHooks
{
    /**
     * Retrieve the post set as the archive page for the given post type.
     *
     * @param $postType
     * @return Post|null
     */
    public static function getArchivePost(string $postType): \Timber\Post|null
    {
        $currentArchivePost = Timber::get_posts([
            'numberposts' => 1,
            'nopaging' => true,
            'post_type' => 'page',
            'meta_key' => 'original_type',
            'meta_value' => $postType,
        ]);

        if (is_array($currentArchivePost) && isset($currentArchivePost[0])) {
            $post = Timber::get_post($currentArchivePost[0]->ID);
        }
        return $post ?? null;
    }

    /**
     * Create page if not exists.
     *
     * Note: Sets a transient to prevent checking if the page exists on every page load. If the page is not being created,
     * try clearing the transients. By using "wp transient delete --all" in the terminal.
     *
     * @return void
     */
    public static function createArchivePageIfNotExists(string $title, string $slug, string $postType): void
    {
        if (!is_admin()) {
            return;
        }

        static::addPostState($title, $slug);

        if (get_transient(sprintf('archive_page_%s_created', $slug))) {
            return;
        }

        if (!get_page_by_path($slug)) {
            wp_insert_post([
                'post_title' => $title,
                'post_name' => $slug,
                'post_status' => 'publish',
                'menu_order' => 1,
                'post_type' => 'page',
                'meta_input' => ['original_type' => $postType],
            ]);

            set_transient(sprintf('archive_page_%s_created', $slug), true);
        }
    }

    /**
     * Add a post state. This will show a label in the page overview next to the page title.
     *
     * @return void
     */
    public static function addPostState($title, $slug): void
    {
        add_filter('display_post_states', function ($post_states, $post) use (&$title, &$slug) {
            if ($post->post_name === $slug) {
                $post_states[] = $title . ' overzicht';
            }

            return $post_states;
        }, 10, 2);
    }
}
