<?php

namespace SEOAIC\seoaic_acf;

use SEOAIC\SEOAIC_SETTINGS;

class SEOAICWysiwygField extends SEOAICCustomField
{
    public const DEFAULT_POST_TYPES = ['post', 'page'];

    public function __construct() {
        parent::__construct(
            'field_seoaic_wysiwyg',
            'seoaicWysiwygContent',
            'wysiwyg'
        );

        add_action('acf/init', [$this, 'registerField'], 99);
        add_filter("acf/load_value/key={$this->fieldKey}", [$this, 'loadFieldValue'], 20, 3);
        add_filter("acf/update_value/key={$this->fieldKey}", [$this, 'preventSavingField'], 20, 3);
    }

    /**
     * Register WYSIWYG editor for post type
     *
     * @return void
     */
    public function registerField()
    {
        if (
          !seoaic_is_scf_active()
          || !SEOAIC_SETTINGS::isGeneratedContentInCustomFieldTurnedOn()
        ) {
            return;
        }

        if (!function_exists('acf_add_local_field_group')) {
            return;
        }

        acf_add_local_field_group([
            'key'      => 'group_seoaic_wysiwyg',
            'title'    => esc_html__('SEO AI Content field', 'seoaic'),
            'fields'   => [
                [
                    'key'           => $this->fieldKey,
                    'label'         => esc_html__('Post content', 'seoaic'),
                    'name'          => $this->fieldName,
                    'type'          => $this->fieldType,
                    'instructions'  => esc_html__('This field displays generated post content (in case if you can`t see the default editor)', 'seoaic'),
                    'required'      => 0,
                    'toolbar'       => 'full',
                    'media_upload'  => 1,
                    'tabs'          => 'all'
                ]
            ],
            'location' => [
                [
                    [
                        'param'    => 'post_type',
                        'operator' => '==',
                        'value'    => SEOAIC_SETTINGS::getSEOAICPostType()
                    ]
                ]
            ]
        ]);
    }

    /**
     * Loads content of the current post
     *
     * @param mixed $value
     * @param int $postId
     * @param array $field
     * @return string
     */
    public function loadFieldValue($value, $postId, $field)
    {
        $post = get_post($postId);

        return $post ? $post->post_content : '';
    }

    /**
     * Prevent saving data to custom field to avoid duplication
     *
     * @param mixed $value
     * @param int $postId
     * @param array $field
     * @return null
     */
    public function preventSavingField($value, $postId, $field)
    {
        return null;
    }
}
