<?php

declare(strict_types=1);

namespace ACA\YoastSeo\Value\Formatter\User;

use AC;
use AC\Helper;
use AC\Helper\Dashicon;
use AC\Type\Value;

class FallbackMetaTitle implements AC\Formatter
{
    public function format(Value $value): Value
    {
        if ($value->get_value()) {
            return $value;
        }

        $icon = Helper\Html::create()->tooltip(
            Dashicon::create('media-text', 'gray')->render(),
            __('Specific title is missing. The current title is generated by Yoast SEO.', 'codepress-admin-columns')
        );

        return $value->with_value(
            sprintf(
                '%s %s',
                $icon,
                $this->get_wp_seo_author_title($value->get_id())
            )
        );
    }

    private function get_wp_seo_author_title($user_id)
    {
        $old_author = get_query_var('author');
        set_query_var('author', $user_id);

        $titles = get_option('wpseo_titles');
        $author_title = is_array($titles) ? ($titles['title-author-wpseo'] ?? false) : false;
        $title = wpseo_replace_vars($author_title, (object)[]);

        set_query_var('author', $old_author);

        return $title;
    }

}
