<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Integrations;

defined('ABSPATH') || exit;

/**
 * Rank Math SEO integration. Overrides the title/description/canonical on a
 * store-detail URL and registers a sitemap provider exposing every store URL
 * (cliq-stores-sitemap.xml).
 */
final class RankMath implements Integration
{
    public const SITEMAP = 'cliq-stores';

    private StoreDetailSeo $seo;

    public function __construct(StoreDetailSeo $seo)
    {
        $this->seo = $seo;
    }

    public function isActive(): bool
    {
        return defined('RANK_MATH_VERSION') || class_exists('RankMath\\Helper');
    }

    public function register(): void
    {
        add_filter('rank_math/frontend/title', [$this, 'title']);
        add_filter('rank_math/frontend/description', [$this, 'description']);
        add_filter('rank_math/frontend/canonical', [$this, 'canonical']);

        // Sitemap provider — only when Rank Math's interface is available.
        if (interface_exists('RankMath\\Sitemap\\Providers\\Provider')) {
            add_filter('rank_math/sitemap/providers', [$this, 'addSitemapProvider']);
        }
    }

    public function title($title)
    {
        return $this->seo->isStoreDetail() ? $this->seo->title($this->separator()) : $title;
    }

    public function description($value)
    {
        $desc = $this->seo->description();
        return ($this->seo->isStoreDetail() && $desc !== '') ? $desc : $value;
    }

    public function canonical($value)
    {
        $url = $this->seo->canonical();
        return ($this->seo->isStoreDetail() && $url !== '') ? $url : $value;
    }

    private function separator(): string
    {
        if (class_exists('RankMath\\Helper') && method_exists('RankMath\\Helper', 'get_settings')) {
            $sep = trim((string) \RankMath\Helper::get_settings('titles.title_separator'));
            if ($sep !== '') {
                return $sep;
            }
        }

        return '-';
    }

    /**
     * @param array<int, object> $providers
     * @return array<int, object>
     */
    public function addSitemapProvider(array $providers): array
    {
        $providers[] = new class ($this->seo) implements \RankMath\Sitemap\Providers\Provider {
            private StoreDetailSeo $seo;

            public function __construct(StoreDetailSeo $seo)
            {
                $this->seo = $seo;
            }

            public function handles_type($type)
            {
                return $type === RankMath::SITEMAP;
            }

            public function get_index_links($max_entries)
            {
                return [[
                    'loc' => \RankMath\Sitemap\Router::get_base_url(RankMath::SITEMAP . '-sitemap.xml'),
                    'lastmod' => '',
                ]];
            }

            public function get_sitemap_links($type, $max_entries, $current_page)
            {
                $links = [];
                foreach ($this->seo->storeUrls() as $u) {
                    $links[] = [
                        'loc' => $u['loc'],
                        'mod' => $u['lastmod'],
                    ];
                }

                return $links;
            }
        };

        return $providers;
    }
}
