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

class SchematicPublic {

    public function __construct() {
        add_action('wp_head', array($this, 'head'));
    }

    public function head() {
        $schemaElementsArray = array();

        if (is_home() && isSchematicPageChosen('homepage')) {
            $schemaElementsArray = getSchematicDataByType('homepage');
        } else if (is_single() || is_page()) {
            global $post;

            if ($post && isset($post->post_type) && isSchematicPageChosen($post->post_type)) {
                $schemaElementsArray = getSchematicPostSchema($post);
            }
        } else if (is_category() or is_tax() or is_tag()) {
            global $wp_query;
            $object = $wp_query->get_queried_object();

            if ($object && $object->taxonomy && isSchematicPageChosen($object->taxonomy)) {
                $schemaElementsArray = getSchematicListSchema($object);
            }
        }

        if (!$schemaElementsArray) {
            return false;
        }

        $output = array();

        global $schematicSchemaBuilder;

        foreach ($schemaElementsArray as $id => $schema) {

            if ($schematicSchemaBuilder && $schema) {
                $output[$id] = $schematicSchemaBuilder->converter($schema);
            } else {

                if (!empty($schema)) {
                    $output[$id] = 'PHP version too old (unsupported)';
                }
            }
        }

        if ($output) {
            ?>

            <script type="application/ld+json"> <?php
            echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            ?></script> <?php
        }
    }

}

new SchematicPublic();
