<?php
namespace SabaiApps\Directories\Component\WordPressContent\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity;

class MetadataHelper extends Entity\Helper\UrlHelper
{
    static protected $_themePostMetaKeys;

    public function post(Application $application, $value, $postId, $metaKey, $single)
    {
        if ((!$post_type = get_post_type($postId))
            || !$application->getComponent('WordPressContent')->hasPostType($post_type)
        ) return $value;

        if (!empty($metaKey)) {
            if (!isset(self::$_themePostMetaKeys)) {
                self::_loadThemePostMetaKeys($application);
                self::$_themePostMetaKeys = $application->Filter('wordpresscontent_theme_post_meta_keys', self::$_themePostMetaKeys);
            }

            if (in_array($metaKey, self::$_themePostMetaKeys[0])
                || (isset(self::$_themePostMetaKeys[1]) && strpos($metaKey, self::$_themePostMetaKeys[1]) === 0)
            ) {
                // Fetch page layout setting configured for the custom single item page.
                if (is_single()
                    && ($page_id = $application->getComponent('WordPressContent')->getBundleSingleItemPageId($post_type))
                ) {
                    remove_filter('get_post_metadata', [$application, 'WordPressContent_Metadata_post'], 10); // prevent loop
                    $value = get_post_meta($page_id, $metaKey, $single);
                    if ($single) $value = [$value];  // WordPress looks for index 0 if single value returned by get_metadata filter is array
                    add_filter('get_post_metadata', [$application, 'WordPressContent_Metadata_post'], 10, 4);
                }
                return $value;
            }
        }

        return $this->_getMetadata($application, 'post', $postId, $metaKey, $single, $value);
    }

    public function term(Application $application, $value, $termId, $metaKey, $single)
    {
        if ((!$taxonomy = \SabaiApps\Directories\Component\WordPressContent\WordPressContentComponent::getTermTaxonomy($termId))
            || !$application->getComponent('WordPressContent')->hasTaxonomy($taxonomy)
        ) return $value;

        return $this->_getMetadata($application, 'term', $termId, $metaKey, $single, $value);
    }

    protected function _getMetadata(Application $application, $entityType, $entityId, $metaKey, $single, $value)
    {
        if (!empty($metaKey)) {
            if (strpos($metaKey, '_drts_') !== 0
                || (!$field_name = substr($metaKey, strlen('_drts_')))
            ) {
                return $value; // meta key must start with _drts_ when requesting for a specific field
            }
        }

        if ($entity = $application->Entity_Entity($entityType, $entityId)) {
            if (isset($field_name)) {
                $key = null;
                if ($pos = strpos($field_name, '__')) {
                    $key = substr($field_name, $pos + 2);
                    $field_name = substr($field_name, 0, $pos);
                }
                if ($single) {
                    if (null === $value = $entity->getSingleFieldValue($field_name, $key)) {
                        $value = '';
                    }
                    $value = [$value]; // WordPress looks for index 0 if single value returned by get_metadata filter is array
                } else {
                    $value = $entity->getFieldValue($field_name, $key);
                    if ($value === null
                        || $value === false
                    ) {
                        $value = [];
                    }
                }
            } else {
                // Need to call get_post_meta() again since returning a non null value
                // with get_post_metadata filter will not include other meta values.
                remove_filter('get_post_metadata', [$application, 'WordPressContent_Metadata_post'], 10); // prevent loop
                $value = get_post_meta($entity->getId());
                add_filter('get_post_metadata', [$application, 'WordPressContent_Metadata_post'], 10, 4);

                // Add all field values
                $_value = $entity->getFieldValues();
                foreach (array_keys($_value) as $field_name) {
                    if (!isset($_value[$field_name])) continue;

                    $value['_drts_' . $field_name] = is_array($_value[$field_name]) ? $_value[$field_name] : [$_value[$field_name]];
                }
            }
        }
        return $value;
    }

    protected static function _loadThemePostMetaKeys(Application $application)
    {
        $keys = [];
        $prefix = null;
        switch ($application->getComponent('WordPressContent')->getThemeSlug()) {
            case 'divi':
                $keys = ['_et_pb_page_layout', '_et_pb_use_builder', '_et_pb_post_hide_nav', '_et_pb_side_nav'];
                break;
            case 'extra':
                $keys = ['_extra_sidebar', '_extra_sidebar_location'];
                break;
            case 'salient':
                $prefix = '_nectar_';
                break;
            case 'avada':
                $keys = ['sbg_selected_sidebar_replacement', 'sbg_selected_sidebar_2_replacement'];
                $prefix = 'pyre_';
                break;
            case 'astra':
                $keys = ['site-post-title', 'site-sidebar-layout', 'site-content-layout', 'ast-main-header-display', 'footer-sml-layout', 'ast-featured-img', 'theme-transparent-header-meta'];
                break;
            case 'enfold':
                $keys = ['layout', 'sidebar', 'footer', 'header_title_bar', 'header_transparency'];
                break;
            case 'total':
                $prefix = 'wpex_';
                $keys = ['sidebar'];
                break;
            case 'x';
                $prefix = '_x_';
                break;
            case 'the7':
                $prefix = '_dt_';
                break;
            case 'betheme':
                $prefix = 'mfn-';
                break;
            case 'genesis':
                $prefix = 'genesis_layout';
                break;
            default:
        }
        $keys[] = '_wp_page_template';
        self::$_themePostMetaKeys = [$keys, $prefix];
    }
}