<?php
/**
 * STB Provider Theme — functions.php
 */

// Enqueue styles and scripts
function stb_enqueue() {
    $v = wp_get_theme()->get('Version');
    wp_enqueue_style('stb-main',     get_template_directory_uri() . '/assets/css/main.min.css',   [], $v);
    if (stb_is_rtl_lang()) {
        wp_enqueue_style('stb-rtl',      get_template_directory_uri() . '/assets/css/rtl.min.css',    [], $v, 'screen');
    }
    wp_enqueue_script('stb-main',    get_template_directory_uri() . '/assets/js/main.min.js',     [], $v, true);

    // IBM Plex Sans + Bebas Neue for LTR, Vazirmatn for FA, Cairo for AR
    $font_families = [];
    $lang = stb_lang();
    if ($lang === 'fa') {
        $font_families[] = 'family=Vazirmatn:wght@300;400;500;600;700';
        $font_families[] = 'family=IBM+Plex+Sans:wght@300;400;500;600;700';
    } elseif ($lang === 'ar') {
        $font_families[] = 'family=Cairo:wght@300;400;500;600;700';
        $font_families[] = 'family=IBM+Plex+Sans:wght@300;400;500;600;700';
    } else {
        $font_families[] = 'family=IBM+Plex+Sans:wght@300;400;500;600;700';
        $font_families[] = 'family=Bebas+Neue';
    }
    $font_url = 'https://fonts.googleapis.com/css2?' . implode('&', $font_families) . '&display=swap';

    wp_enqueue_style('stb-fonts', $font_url, [], null);
}
add_action('wp_enqueue_scripts', 'stb_enqueue');

// Defer non-critical scripts to improve page load and LCP
add_filter('script_loader_tag', function($tag, $handle) {
    if (in_array($handle, ['stb-main', 'stb-prices'])) {
        return str_replace(' src', ' defer src', $tag);
    }
    return $tag;
}, 10, 2);

// Theme supports
add_action('after_setup_theme', function() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', ['search-form','comment-form','comment-list','gallery','caption']);
    add_theme_support('custom-logo');
    load_theme_textdomain('stb-theme', get_template_directory() . '/languages');
});

// Detect language direction
function stb_is_rtl_lang() {
    return in_array(stb_lang(), ['fa', 'ar', 'he', 'ur']);
}

// Register nav menus
register_nav_menus([
    'primary'  => __('Primary Navigation', 'stb-theme'),
    'primary-rtl' => __('Primary Navigation RTL', 'stb-theme'),
    'footer'   => __('Footer Links', 'stb-theme'),
]);

// Register custom post types
function stb_register_post_types() {
    // Blog / Articles
    register_post_type('stb_article', [
        'labels'      => ['name' => 'Articles', 'singular_name' => 'Article'],
        'public'      => true,
        'has_archive' => true,
        'rewrite'     => ['slug' => 'articles', 'with_front' => false],
        'supports'    => ['title', 'editor', 'thumbnail', 'excerpt', 'author'],
        'show_in_rest'=> true,
    ]);

    // Encyclopedia
    register_post_type('stb_encyclopedia', [
        'labels'      => [
            'name'          => 'Encyclopedia',
            'singular_name' => 'Term',
            'add_new_item'  => 'Add New Term',
            'edit_item'     => 'Edit Term',
            'search_items'  => 'Search Terms',
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => ['slug' => 'encyclopedia', 'with_front' => false],
        'supports'     => ['title', 'editor', 'excerpt', 'custom-fields'],
        'show_in_rest' => true,
        'menu_icon'    => 'dashicons-book-alt',
        'menu_position'=> 6,
    ]);

    // Encyclopedia Category Taxonomy
    register_taxonomy('ency_category', 'stb_encyclopedia', [
        'labels'       => ['name' => 'Categories', 'singular_name' => 'Category'],
        'public'       => true,
        'hierarchical' => true,
        'rewrite'      => ['slug' => 'encyclopedia/category'],
        'show_in_rest' => true,
    ]);

    // Webinars
    register_post_type('stb_webinar', [
        'labels'      => ['name' => 'Webinars', 'singular_name' => 'Webinar'],
        'public'      => true,
        'has_archive' => true,
        'rewrite'     => ['slug' => 'stb-webinars', 'with_front' => false],
        'supports'    => ['title', 'editor', 'thumbnail', 'excerpt'],
        'show_in_rest'=> true,
    ]);
}
add_action('init', 'stb_register_post_types');

// Helper: get current lang
function stb_lang() {
    // 1. WPML (production)
    if (defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE) return ICL_LANGUAGE_CODE;
    // 2. URL path prefix: /fa/, /ar/, /ru/, /es/
    $uri = $_SERVER['REQUEST_URI'] ?? '';
    if (preg_match('#/(fa|ar|ru|es)(/|\?|$)#', $uri, $m)) return $m[1];
    // 3. Query param ?lang= (explicit only, no cookie persistence)
    $ql = $_GET['lang'] ?? '';
    if (in_array($ql, ['fa','ar','ru','es','en'])) return $ql;
    // 4. Default: always English unless explicitly requested
    return 'en';
}
// Helper: append ?lang= to internal URLs when not English
function stb_url($path) {
    $lang = stb_lang();
    if ($lang !== 'en' && strpos($path, 'lang=') === false) {
        $sep = (strpos($path, '?') !== false) ? '&' : '?';
        return $path . $sep . 'lang=' . $lang;
    }
    return $path;
}


// Language: clear any old stb_lang cookie when visiting EN or plain URL
add_action('init', function(){
    // Clear old cookie if it exists
    if(isset($_COOKIE['stb_lang'])){
        setcookie('stb_lang', '', time()-3600, '/');
        unset($_COOKIE['stb_lang']);
    }
}, 1);

// Enqueue prices client
function stb_enqueue_prices() {
    $v = wp_get_theme()->get('Version');
    wp_enqueue_script('stb-prices', get_template_directory_uri() . '/assets/js/prices.js', [], $v, true);
    // Pass API root to JS (handles any subdirectory install)
    wp_localize_script('stb-prices', 'stbPricesConfig', [
        'apiUrl' => rest_url('stb/v1/prices'),
        'nonce'  => wp_create_nonce('wp_rest'),
    ]);
}
add_action('wp_enqueue_scripts', 'stb_enqueue_prices');


// Fix permalink conflicts: force page template for pages with conflicting slugs
add_filter('template_include', function($template) {
    if (is_page(['blog', 'webinar', 'encyclopedia'])) {
        $custom = get_page_template_slug();
        if ($custom && locate_template($custom)) {
            return locate_template($custom);
        }
    }
    return $template;
}, 99);

// Flush rewrite rules once after CPT slug change
add_action('init', function() {
    if (get_option('stb_flush_rewrites_v2') !== 'done') {
        flush_rewrite_rules();
        update_option('stb_flush_rewrites_v2', 'done');
    }
}, 999);


// ── Encyclopedia SEO Meta (legacy — schema only; meta/og handled by inc/seo.php) ─
add_action('wp_head', function() {
    if (!is_singular('stb_encyclopedia')) return;
    $pid = get_the_ID();
    // Keep the rich JSON-LD if it exists (DefinedTerm + related schema)
    $schema = get_post_meta($pid, '_ency_schema_json', true);
    if ($schema) {
        echo '<script type="application/ld+json">' . $schema . '</script>' . "
";
    }
}, 1);

// Provide encyclopedia title/desc to the new SEO module via filter,
// so inc/seo.php uses the term-specific meta from _ency_meta_desc / _ency_fa_meta_desc.
add_filter('stb_seo_data', function($data) {
    if (!is_singular('stb_encyclopedia')) return $data;
    global $post;
    if (!$post) return $data;
    $slug = $post->post_name;
    $en_desc = get_post_meta($post->ID, '_ency_meta_desc', true);
    $fa_desc = get_post_meta($post->ID, '_ency_fa_meta_desc', true);
    $en_title = get_post_meta($post->ID, '_ency_og_title', true) ?: (get_the_title($post) . ' | STB Encyclopedia');
    $fa_title_meta = get_post_meta($post->ID, '_ency_fa_title', true);
    $fa_title = ($fa_title_meta ?: get_the_title($post)) . ' | دانشنامه STB';
    $data[$slug] = [
        'en' => [
            'title' => $en_title,
            'desc'  => $en_desc ?: '',
            'keywords' => '',
            'schema_type' => 'DefinedTerm',
        ],
        'fa' => [
            'title' => $fa_title,
            'desc'  => $fa_desc ?: '',
            'keywords' => '',
            'schema_type' => 'DefinedTerm',
        ],
    ];
    return $data;
});

// ── Encyclopedia Sitemap ───────────────────────────────────────────────
add_filter('wp_sitemaps_post_types', function($post_types) {
    $post_types['stb_encyclopedia'] = get_post_type_object('stb_encyclopedia');
    return $post_types;
});
// Bilingual text helper
function stb_t($fa_text, $en_text) { return stb_lang()==='fa' ? $fa_text : $en_text; }

// ── Blog SEO Meta (legacy schema only — meta/og now handled by inc/seo.php) ──
add_action('wp_head', function() {
    if (!is_singular('post')) return;
    $pid = get_the_ID();
    $schema = get_post_meta($pid, '_blog_schema_json', true);
    if ($schema) {
        echo '<script type="application/ld+json">' . $schema . '</script>' . "
";
    }
}, 1);

// ── STB SEO bootstrap ──────────────────────────────────────────────────
require_once get_template_directory() . "/inc/init.php";

// ── Post Language Custom Field & Auto-detection ──────────────────────────
add_action('add_meta_boxes', function() {
    add_meta_box(
        'stb_post_lang_metabox',
        'Post Language (STB)',
        function($post) {
            $value = get_post_meta($post->ID, '_stb_lang', true);
            if (!$value) {
                $value = 'en';
            }
            wp_nonce_field('stb_save_post_lang', 'stb_post_lang_nonce');
            ?>
            <select name="stb_post_lang" style="width: 100%;">
                <option value="en" <?php selected($value, 'en'); ?>>English (en)</option>
                <option value="fa" <?php selected($value, 'fa'); ?>>Persian (fa)</option>
            </select>
            <?php
        },
        'post',
        'side',
        'default'
    );
});

add_action('save_post', function($post_id) {
    // If auto-save or wrong post type, exit early
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (get_post_type($post_id) !== 'post') return;

    if (!isset($_POST['stb_post_lang_nonce']) || !wp_verify_nonce($_POST['stb_post_lang_nonce'], 'stb_save_post_lang')) {
        // If not saving via form, auto-detect for new posts if not already set
        $current_lang = get_post_meta($post_id, '_stb_lang', true);
        if (!$current_lang) {
            $post = get_post($post_id);
            if ($post) {
                $title = $post->post_title;
                $slug = $post->post_name;
                // Detect Persian chars or -fa slug suffix
                if (preg_match('/[\x{0600}-\x{06FF}]/u', $title) || preg_match('/-fa$/', $slug)) {
                    update_post_meta($post_id, '_stb_lang', 'fa');
                    update_post_meta($post_id, 'ns_post_lang', 'fa');
                } else {
                    update_post_meta($post_id, '_stb_lang', 'en');
                    update_post_meta($post_id, 'ns_post_lang', 'en');
                }
            }
        }
        return;
    }

    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['stb_post_lang'])) {
        $lang = sanitize_text_field($_POST['stb_post_lang']);
        if (in_array($lang, ['en', 'fa'])) {
            update_post_meta($post_id, '_stb_lang', $lang);
            update_post_meta($post_id, 'ns_post_lang', $lang);
        }
    }
});
