<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Integrations;

defined('ABSPATH') || exit;

/**
 * SEOPress integration. Overrides title/description/canonical on a store-detail
 * URL. SEOPress's XML sitemap is built from registered post types, so the custom
 * store-detail URLs can't be injected the way Yoast/Rank Math allow — that piece
 * is intentionally omitted (those two cover the sitemap need).
 */
final class SeoPress implements Integration
{
    private StoreDetailSeo $seo;

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

    public function isActive(): bool
    {
        return defined('SEOPRESS_VERSION');
    }

    public function register(): void
    {
        add_filter('seopress_titles_title', [$this, 'title']);
        add_filter('seopress_titles_desc', [$this, 'description']);
        add_filter('seopress_titles_canonical', [$this, 'canonical']);
    }

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

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

    /** SEOPress passes the full <link rel="canonical"> markup through this filter. */
    public function canonical($html)
    {
        $url = $this->seo->canonical();
        if (! $this->seo->isStoreDetail() || $url === '') {
            return $html;
        }

        return '<link rel="canonical" href="' . esc_url($url) . '" />' . "\n";
    }
}
