<?php
if (!defined('ABSPATH')) {
    exit;
}

function getSchematicEditButtonHtml($post = null, $term = null, $settings = false) {

    if (!$settings) {

        if (!$term && !$post) {
            return false;
        }

        if ($post) {
            $pageId = 'single';
            $objectId = $post->ID;
            $type = get_post_type($post);
            $types = get_post_types(array(
                'public' => true
                    ), 'objects');
        }

        if ($term) {
            $pageId = 'list';
            $objectId = $term->term_id;
            $type = $term->taxonomy;

            $types = get_taxonomies(array(
                'public' => true
                    ), 'objects');
        }

        if (isset($types) && isset($type)) {
            if (isset($types[$type])) {
                $current = $types[$type];
            } else {
                return;
            }
        } else {
            return;
        }

        $labelSingular = $current->labels->singular_name;
        $labelMultiple = $current->labels->all_items;
    }


    $data = get_option('_schematic_d_l');
    $_k = null;

    if ($data) {
        $unserialized = unserialize($data);

        if ($unserialized && isset($unserialized['key']) && !$unserialized['flag']) {
            if (strlen($unserialized['key']) === 20) {
                $_k = $unserialized['key'];
            }
        }
    }

    global $schematicIcon;

    $nonce = wp_create_nonce("schematic-nonce");

    if (!shouldSchemaPluginLoad()) {
        return false;
    }
    ?>
    <input id="wpSchemaInstallationUrl" type="hidden" value="<?php echo(admin_url('admin.php?page=wp-schema-installation')) ?>" />

    <input type="hidden" id="_schematic_d_l" value="<?php echo($_k); ?>" />

    <?php if ($settings == false) { ?>

        <span
            data-plugin-version="<?php echo(WPSCHEMA_VERSION) ?>"
            data-nonce="<?php echo($nonce); ?>"
            data-object-id="<?php echo($objectId); ?>"
            data-singular-name="<?php echo($labelSingular); ?>"
            data-multiple-name="<?php echo($labelMultiple); ?>"
            data-group-id="<?php echo($pageId); ?>"
            data-page-type="<?php echo($type); ?>"
            id="openSchematic">
            <span style="background-image: url(<?php echo($schematicIcon); ?>" class="schematic-icon"></span>
            Schema
        </span>

        <?php
    }
}

function getPluginSlug() {
    return('schematic');
}

function schematic_fetch_new_api_data() {
    global $schematicApi;

    if ($schematicApi) {
        $data = $schematicApi->verify_api_key();

        if ($data && $data->status == 'error') {
            update_option('_schematic_key_error', $data->data);
        } else {
            $array = array('key' => trim(strip_tags($data->key)), 'flag' => 'false');
            update_option('_schematic_d_l', serialize($array));
            delete_option('_schematic_key_error');
        }
    }
}

function invokeSchematicPhpFunctions($val) {
    $options = getSchematicOptions();

    if (strpos($val, '<?php ') !== false && $options['enable_php_functions'] === 'true') {

        $val = ltrim($val, '<?php ');
        $val = rtrim($val, ' ?>');

        global $dangerousPhpFunctions;

        $stringWithoutSpaces = preg_replace('/\s+/', '', $val);

        foreach ($dangerousPhpFunctions as $function) {
            if (strpos($stringWithoutSpaces, $function . '(') !== false) {
                return $function . ' - this word cannot be executed because we are not sure it is safe for your site. '
                        . 'Please use similar safer function.';
            }
        }

        ob_start();

        if (interface_exists('Throwable')) {
            try {
                eval($val);
            } catch (Throwable $t) {
                echo('Error: ' . $t->getMessage());
            }
        } else {
            eval($val);
        }

        $contents = ob_get_contents();

        ob_end_clean();

        return $contents;
    }

    return $val;
}

function schematicShortcodes($val) {
    if (strpos($val, '[') !== false && strpos($val, ']') !== false) {
        return apply_filters('schematic_shortcodes', $val);
    }

    return $val;
}

function getSchematicCatalogOptions() {
    return get_option('_schematic_catalog_options', array());
}

function setSchematicCatalogOptions($options) {
    update_option('_schematic_catalog_options', $options);
}

function setSchematicOptions($options) {
    update_option('_schematic_options', $options);
}

function getSchematicOptions($jsonResponse = false) {
    $opts = array(
        'json_format' => 'true',
        'microdata_format' => 'true',
        'confirmation_deleting_node' => 'true',
        'auto_collapse_group_nodes' => 'false',
        'highlight_nodes' => 'false',
        'enable_php_functions' => 'false',
        'compatability_mode' => 'false',
    );

    $options = get_option('_schematic_options', $opts);

    foreach ($opts as $id => $opt) {
        if (!isset($options[$id])) {
            $options[$id] = 'false';
        }
    }

    if (!$jsonResponse) {
        return $options;
    }

    echo json_encode($options);
}

function isSchematicInstalled() {
    return get_option('_schematic_installed');
}

function removeSchematicType($array, $pId, $cId = null) {
    foreach ($array as $id => $item) {
        if ($id == $pId) {
            if ($cId) {
                foreach ($item['children'] as $_id => $_item) {
                    if (isset($_item['objectType']) && $_item['objectType'] == $cId) {
                        unset($array[$id]['children'][$_id]);
                    }
                }
            } else {
                unset($array[$id]);
            }
        }
    }

    return $array;
}

function getSchematicChosenPages() {
    return get_option('_schematic_enabled_pages', array());
}

function isSchematicOptionChecked($option) {
    $options = getSchematicOptions();

    if ($options[$option] == 'true' || $options[$option] === true) {
        return true;
    }
}

function getSchematicPages() {
    $array = array();

    $array['homepage'] = array(
        'groupId' => 'homepage',
        'label' => 'Homepage',
        'children' => array()
    );

    $array['single'] = array(
        'groupId' => 'single',
        'label' => 'Single Pages (Posts)',
        'children' => array()
    );

    foreach (get_post_types('', 'objects') as $type) {
        if ($type->public) {
            $array['single']['children'][] = array('label' => $type->labels->name, 'objectType' => $type->name);
        }
    }

    $array['list'] = array(
        'groupId' => 'list',
        'label' => 'List Pages (Terms)',
        'children' => array()
    );
    foreach (get_taxonomies('', 'objects') as $tax) {
        if ($tax->public) {
            $array['list']['children'][] = array('label' => $tax->labels->name, 'objectType' => $tax->name);
        }
    }

    return apply_filters('schematic_types_filter', $array);
}

function getSchematicPageByType($type) {
    $pagesTypes = getSchematicPages();

    foreach ($pagesTypes as $typeGroup) {
        if (!$typeGroup['children'] && $typeGroup['groupId'] === $type) {
            return $typeGroup;
        }

        foreach ($typeGroup['children'] as $childrenGroup) {
            if ($childrenGroup['objectType'] === $type) {
                return $childrenGroup;
            }
        }
    }
}

function getSchematicPagesIdsByType($type) {
    $pagesTypes = getSchematicPages();

    $ids = array();

    if (isset($pagesTypes[$type])) {
        foreach ($pagesTypes[$type]['children'] as $page) {
            $ids[] = $page['objectType'];
        }
    }
    return $ids;
}

function getSchematicChosenPageLabelByType($type, $echo = false) {
    $page = getSchematicPageByType($type);

    if ($page) {
        if (!$echo) {
            return $page['label'];
        }
        echo($page['label']);
    }
}

function isSchematicPageChosen($type) {
    foreach (getSchematicChosenPages() as $page) {
        if ($page['objectType'] === $type) {
            return true;
        }
    }
}

function getSchematicPostSchema($post = null, $postPageGroup = null, $inAdmin = false) {

    if ($post) {
        if (is_int($post)) {
            $post = get_post($post);
        }
        if ($post && isset($post->ID)) {

            $schemaMode = get_post_meta($post->ID, '_magic_page_schema_enabled', true);
            $useGroupSettings = get_post_meta($post->ID, '_use_group_settings', true);

            if ($schemaMode && $schemaMode !== 'advanced' && !$inAdmin) {
                return array();
            }

            // per post, no group
            $postSchema = get_post_meta($post->ID, '_schematic_schema', true);
            if ($postSchema && !$useGroupSettings) {
                return ($postSchema);
            }

            // per group - posts and pages
            $groupId = $postPageGroup ? $postPageGroup : get_post_meta($post->ID, '_group_id', true);
            if ($groupId && ($useGroupSettings || $postPageGroup)) {
                $postSchema = get_option('_group_schema_' . $groupId . '_schematic_schema', array());

                if ($postSchema) {
                    return $postSchema;
                }
            }



            // per post type
            $postType = get_post_type($post);
            if (isSchematicPageChosen($postType)) {
                return get_option('_' . $postType . '_schematic_schema', array());
            }
        }
    }
}

function getSchematicListSchema($term = null, $taxonomy = null) {

    if ($term) {
        if (is_int($term) && $taxonomy) {
            $term = get_term_by('id', $term, $taxonomy);
        }

        if (is_object($term)) {
            $termSchema = get_term_meta($term->term_id, '_schematic_schema', true);
            if ($termSchema) {
                return ($termSchema);
            }
        }

        if (isSchematicPageChosen($term->taxonomy)) {
            return get_option('_' . $term->taxonomy . '_schematic_schema', array());
        }
    }
}

function getSchematicDataByType($id) {
    if ($id) {
        return get_option('_' . $id . '_schematic_schema');
    }
}

function updateSchematicSchemaOption($id, $schema) {
    if (!$schema) {
        delete_option('_' . $id . '_schematic_schema');
    } else {
        update_option('_' . $id . '_schematic_schema', $schema);
    }
}

function magicpageShortcodes($val) {
    if (function_exists('getMagicpageLocation')) {
        $term = getMagicpageLocation();
        return apply_all_filters($val, $term);
    }
    return $val;
}

function is_schematic_api_key_hidden() {
    return get_option('_schematic_api_key_hidden', '0');
}

function schematic_api_key_hidden_by() {
    return get_option('_schematic_api_key_hidden_by', null);
}

function schematic_hidden_by_check() {
    return ((schematic_api_key_hidden_by() && schematic_api_key_hidden_by() == get_current_user_id()) || !schematic_api_key_hidden_by());
}

function getPostTermList($fullTree) {
    global $post;

    $postType = get_post_type($post);
    $out = array();

    if ($post) {

        $args = array(
            'public' => true,
        );
        $taxonomies = get_taxonomies($args, 'objects');

        $taxonomyFound = '';
        foreach ($taxonomies as $taxonomy) {
            if (in_array($postType, $taxonomy->object_type)) {
                $taxonomyFound = $taxonomy;
                break;
            }
        }

        if ($taxonomyFound && $taxonomyFound->name) {
            $taxName = $taxonomyFound->name;
            $terms = wp_get_post_terms($post->ID, $taxName, array('fields' => 'all'));

            if ($fullTree) {
                foreach ($terms as $term) {
                    $out[] = array('name' => $term->name, 'url' => get_term_link($term->slug, $taxName));
                }
            } else {
                $term = end($terms);
                $out[] = array('name' => $term->name, 'url' => get_term_link($term->slug, $taxName));
            }
        }
    }

    return $out;
}

function getTermList($fullTree) {
    $out = array();

    $object = get_queried_object();

    if ($object) {
        $args = array(
            'child_of' => $object->ID,
        );

        $terms = get_terms($object->taxonomy, $args);

        if ($fullTree) {
            foreach ($terms as $term) {
                $out[] = array('name' => $term->name, 'url' => get_term_link($term->slug, $object->taxonomy));
            }
        } else {

            $out[] = array('name' => $object->name, 'url' => get_term_link($object->slug, $object->taxonomy));
        }
    }


    return $out;
}

function getPageTypeSchemaPlugin() {
    global $typenow;
    if (empty($typenow) && !empty($_GET['post'])) {
        $post = get_post($_GET['post']);
        $typenow = $post->post_type;
    }

    return $typenow;
}

function shouldSchemaPluginLoad() {
    global $pagenow;

    if ($pagenow === 'admin.php' && isset($_GET['page']) && $_GET['page'] === 'wp-schema') {
        return true;
    }

    // don't enable for mpp
    if (function_exists('magic_page_default_post_slug')) {
        if (getPageTypeSchemaPlugin() == magic_page_default_post_slug()) {
            return false;
        }
    }

    if ($pagenow == 'post-new.php' or $pagenow == 'post.php') {
        if (isSchematicPageChosen(getPageTypeSchemaPlugin())) {
            return true;
        }
    }

    if ($pagenow == 'term.php' && isset($_GET['taxonomy']) && $_GET['taxonomy']) {
        if (isSchematicPageChosen($_GET['taxonomy'])) {
            return true;
        }
    }


    return false;
}
