<?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();
                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 (isset($GLOBALS['drts_entity'])
                    && $postId === $GLOBALS['drts_entity']->getId()
                    && ($page_id = $application->getComponent('WordPressContent')->getBundleSingleItemPageId($GLOBALS['drts_entity']->getBundleName()))
                ) {
                    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)) {
                if ($single) {
                    if (null === $value = $entity->getSingleFieldValue($field_name)) {
                        $value = '';
                    }
                    $value = [$value]; // WordPress looks for index 0 if single value returned by get_metadata filter is array
                } else {
                    $value = $entity->getFieldValue($field_name);
                    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()
    {
        $theme = wp_get_theme();
        if ($parent_theme = $theme->parent()) {
            $theme = $parent_theme;
        }
        $keys = [];
        $prefix = null;
        switch ($theme->get('Name')) {
            case 'Divi':
                $keys = ['_et_pb_page_layout', '_et_pb_use_builder', '_et_pb_post_hide_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', 'pyre_sidebar_position', 'pyre_sidebar_sticky'];
                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;
            default:
        }
        $keys[] = '_wp_page_template';
        self::$_themePostMetaKeys = [$keys, $prefix];
    }
}