<?php
/**
 * STB Theme — JSON-LD Schema Generator
 * Emits structured data (Organization, WebSite, FinancialService,
 * BreadcrumbList, etc.) inside <head> via wp_head.
 *
 * @package STB
 */

if (!defined('ABSPATH')) exit;

/**
 * Organization data — single source for all schema.
 */
function stb_schema_org_node() {
    $base = stb_seo_canonical_base();
    return [
        '@type'         => 'Organization',
        '@id'           => $base . '#organization',
        'name'          => stb_seo_org_name(),
        'legalName'     => stb_seo_org_legal(),
        'alternateName' => ['STB Brokers', 'STB'],
        'url'           => $base . '/',
        'logo'          => [
            '@type' => 'ImageObject',
            'url'   => stb_seo_org_logo_url(),
        ],
        'identifier'    => [
            '@type' => 'PropertyValue',
            'propertyID' => 'Saint Lucia Company Registration',
            'value' => '2023-00478',
        ],
        'address'       => [
            '@type'           => 'PostalAddress',
            'addressCountry'  => 'LC',
            'addressLocality' => 'Castries',
        ],
        'foundingDate'  => '2023',
        'areaServed'    => 'Worldwide',
        'knowsAbout'    => [
            'Forex Trading', 'CFD Trading', 'PAMM Investment',
            'Copy Trading', 'Proprietary Trading', 'Trading Education',
            'MetaTrader 5', 'Online Brokerage'
        ],
        'subOrganization' => [
            ['@type' => 'Organization', 'name' => 'STB Brokers',    'description' => 'Forex & CFD brokerage division'],
            ['@type' => 'Organization', 'name' => 'STB Investment', 'description' => 'PAMM and managed investment division'],
            ['@type' => 'Organization', 'name' => 'STB Venture',    'description' => 'Proprietary trading division'],
            ['@type' => 'Organization', 'name' => 'STB Academy',    'description' => 'Trading education division'],
            ['@type' => 'Organization', 'name' => 'STB Society',    'description' => 'Partner and community division'],
        ],
        'contactPoint'  => [
            [
                '@type' => 'ContactPoint',
                'contactType' => 'customer support',
                'availableLanguage' => ['English', 'Persian'],
            ],
            [
                '@type' => 'ContactPoint',
                'contactType' => 'sales',
                'availableLanguage' => ['English', 'Persian'],
            ],
        ],
    ];
}

function stb_schema_website_node() {
    $base = stb_seo_canonical_base();
    return [
        '@type'    => 'WebSite',
        '@id'      => $base . '#website',
        'url'      => $base . '/',
        'name'     => stb_seo_org_name(),
        'inLanguage' => ['en', 'fa'],
        'publisher' => ['@id' => $base . '#organization'],
        'potentialAction' => [
            '@type'       => 'SearchAction',
            'target'      => [
                '@type'       => 'EntryPoint',
                'urlTemplate' => $base . '/?s={search_term_string}',
            ],
            'query-input' => 'required name=search_term_string',
        ],
    ];
}

/**
 * Build BreadcrumbList from current request.
 */
function stb_schema_breadcrumb_node() {
    $base  = stb_seo_canonical_base();
    $lang  = function_exists('stb_lang') ? stb_lang() : 'en';
    $home  = $lang === 'fa' ? 'خانه' : 'Home';

    $items = [[
        '@type'    => 'ListItem',
        'position' => 1,
        'name'     => $home,
        'item'     => $base . '/',
    ]];

    if (is_singular()) {
        $title = get_the_title();
        $items[] = [
            '@type'    => 'ListItem',
            'position' => 2,
            'name'     => wp_strip_all_tags($title),
            'item'     => stb_seo_current_url($lang),
        ];
    } elseif (is_post_type_archive('stb_encyclopedia')) {
        $items[] = [
            '@type'    => 'ListItem',
            'position' => 2,
            'name'     => $lang === 'fa' ? 'دانشنامه' : 'Encyclopedia',
            'item'     => stb_seo_current_url($lang),
        ];
    } elseif (is_home() && !is_front_page()) {
        $items[] = [
            '@type'    => 'ListItem',
            'position' => 2,
            'name'     => $lang === 'fa' ? 'مقالات بازار' : 'Market Articles',
            'item'     => stb_seo_current_url($lang),
        ];
    }

    if (count($items) < 2) return null;

    return [
        '@type'           => 'BreadcrumbList',
        'itemListElement' => $items,
    ];
}

/**
 * Map a schema_type string from seo-data to a JSON-LD node for the current page.
 */
function stb_schema_page_node() {
    $lang  = function_exists('stb_lang') ? stb_lang() : 'en';
    $entry = stb_get_seo_entry(null, $lang);
    $type  = isset($entry['schema_type']) ? $entry['schema_type'] : '';
    $url   = stb_seo_current_url($lang);
    $base  = stb_seo_canonical_base();
    $title = isset($entry['title']) ? $entry['title'] : (function_exists('wp_get_document_title') ? wp_get_document_title() : '');
    $desc  = isset($entry['desc']) ? $entry['desc'] : '';

    if (!$type || $type === 'Organization+WebSite') return null;

    // Single post -> Article
    if (is_singular('post')) {
        return [
            '@type'         => 'BlogPosting',
            'mainEntityOfPage' => $url,
            'headline'      => wp_strip_all_tags(get_the_title()),
            'description'   => $desc ?: wp_trim_words(wp_strip_all_tags(get_the_content()), 30, '…'),
            'datePublished' => get_the_date('c'),
            'dateModified'  => get_the_modified_date('c'),
            'inLanguage'    => $lang === 'fa' ? 'fa' : 'en',
            'author'        => [
                '@type' => 'Organization',
                'name'  => stb_seo_org_name(),
                '@id'   => $base . '#organization',
            ],
            'publisher'     => ['@id' => $base . '#organization'],
        ];
    }

    // Encyclopedia entry
    if (is_singular('stb_encyclopedia')) {
        return [
            '@type'         => 'DefinedTerm',
            'name'          => wp_strip_all_tags(get_the_title()),
            'description'   => $desc ?: wp_trim_words(wp_strip_all_tags(get_the_content()), 40, '…'),
            'url'           => $url,
            'inDefinedTermSet' => [
                '@type' => 'DefinedTermSet',
                'name'  => 'STB Trading Encyclopedia',
                'url'   => $base . '/encyclopedia/',
            ],
        ];
    }

    $node = [
        '@type'      => $type,
        'url'        => $url,
        'name'       => wp_strip_all_tags($title),
        'inLanguage' => $lang === 'fa' ? 'fa' : 'en',
        'isPartOf'   => ['@id' => $base . '#website'],
    ];
    if ($desc) $node['description'] = $desc;

    // Add provider for FinancialService / Service / FinancialProduct / Offer / Course / Event
    if (in_array($type, ['FinancialService', 'Service', 'FinancialProduct', 'Offer', 'Course', 'Event'], true)) {
        $node['provider'] = ['@id' => $base . '#organization'];
    }

    return $node;
}

/**
 * Inject the full @graph JSON-LD into <head>.
 */
add_action('wp_head', 'stb_render_schema', 5);

function stb_render_schema() {
    $graph = [];

    // Always include Organization + WebSite
    $graph[] = stb_schema_org_node();
    $graph[] = stb_schema_website_node();

    // Page-specific node
    $page = stb_schema_page_node();
    if ($page) $graph[] = $page;

    // Breadcrumb
    $bc = stb_schema_breadcrumb_node();
    if ($bc) $graph[] = $bc;

    $payload = [
        '@context' => 'https://schema.org',
        '@graph'   => $graph,
    ];

    $json = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    echo "\n<!-- STB Schema -->\n";
    echo '<script type="application/ld+json">' . "\n" . $json . "\n" . '</script>' . "\n";
    echo "<!-- /STB Schema -->\n";
}
