<?php

namespace SEOAIC\thirdparty_plugins_meta_tags;

use SEOAIC\helpers\StringHelpers;

abstract class AbstractMetaTags
{
    protected $pluginID = '';
    protected $descriptionField = '';
    protected $keywordField = '';
    protected $socialMetaDescriptionFields = [
        'description',
        'og_description',
        'twitter_description',
    ];

    public function getPluginID()
    {
        return $this->pluginID;
    }

    protected function setSocialMetaDescriptions(int $postID, string $description = ''): void
    {
        if (!empty($this->socialMetaDescriptionFields)) {
            $description = StringHelpers::nl2space($description);

            foreach ($this->socialMetaDescriptionFields as $socialDescriptionField) {
                update_post_meta($postID, $socialDescriptionField, $description);
            }
        }
    }

    protected function getMetaFieldValue($postID = null, $fieldName = '')
    {
        if (
            !empty($postID)
            && is_numeric($postID)
            && !empty($fieldName)
        ) {
            return get_post_meta($postID, $fieldName, true);
        }
    }

    // default handler, can be overwritten in child classes
    public function setDescription($postID = null, $description = ''): bool
    {
        if (
            !empty($postID)
            && is_numeric($postID)
        ) {
            $description = StringHelpers::nl2space($description);

            $this->setSocialMetaDescriptions(intval($postID), $description);

            return update_post_meta($postID, $this->descriptionField, $description);
        }

        return false;
    }

    // default handler, can be overwritten in child classes
    public function setKeyword($postID = null, $keyword = '')
    {
        if (
            !empty($postID)
            && is_numeric($postID)
        ) {
            update_post_meta($postID, $this->keywordField, $keyword);
        }
    }

    public function isPluginActive()
    {
        // $activePlugins = apply_filters('active_plugins', get_option('active_plugins'));
        // return in_array($this->getPluginID(), $activePlugins);

        include_once ABSPATH . 'wp-admin/includes/plugin.php';

        return is_plugin_active($this->getPluginID());
    }

    public function getMetaDescriptionFieldName()
    {
        return $this->descriptionField;
    }

    public function getMetaKeywordFieldName()
    {
        return $this->keywordField;
    }

    public function getDescription($postID)
    {
        return $this->getMetaFieldValue($postID, $this->getMetaDescriptionFieldName());
    }

    public function getKeyword($postID)
    {
        return $this->getMetaFieldValue($postID, $this->getMetaKeywordFieldName());
    }
}
