<?php
/**
 * Plugin Name: Inkferry SEO Fields
 * Description: Lets the Inkferry Google Docs add-on set SEO titles, meta descriptions and focus keyphrases for Yoast SEO, SEOPress and The SEO Framework. Only users who can edit a post can set its fields.
 * Version: 1.0.0
 * Author: Great Work LLC
 * Author URI: https://addons.greatwork.company/docs-to-wordpress
 * License: GPLv2 or later
 * Requires at least: 5.6
 */

if (!defined('ABSPATH')) {
    exit;
}

/** Which SEO plugin is active: yoast, rankmath, seopress, tsf or an empty string. */
function inkferry_seo_plugin() {
    if (defined('WPSEO_VERSION')) return 'yoast';
    if (class_exists('RankMath')) return 'rankmath';
    if (defined('SEOPRESS_VERSION')) return 'seopress';
    if (function_exists('the_seo_framework')) return 'tsf';
    return '';
}

/** The post meta keys each plugin uses for title, description and focus keyphrase. */
function inkferry_seo_keys() {
    return array(
        '_yoast_wpseo_title', '_yoast_wpseo_metadesc', '_yoast_wpseo_focuskw',
        '_seopress_titles_title', '_seopress_titles_desc', '_seopress_analysis_target_kw',
        '_genesis_title', '_genesis_description',
    );
}

add_action('init', function () {
    $types = get_post_types(array('show_in_rest' => true), 'names');
    foreach ($types as $type) {
        if ($type === 'attachment') continue;
        foreach (inkferry_seo_keys() as $key) {
            register_post_meta($type, $key, array(
                'type' => 'string',
                'single' => true,
                'show_in_rest' => true,
                'sanitize_callback' => 'sanitize_text_field',
                'auth_callback' => function ($allowed, $meta_key, $post_id) {
                    return current_user_can('edit_post', $post_id);
                },
            ));
        }
    }
}, 20);

add_action('rest_api_init', function () {
    register_rest_route('inkferry/v1', '/ping', array(
        'methods' => 'GET',
        'permission_callback' => function () {
            return current_user_can('edit_posts');
        },
        'callback' => function () {
            return array('ok' => true, 'version' => '1.0.0', 'seo' => inkferry_seo_plugin());
        },
    ));
});
