<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php
namespace WPU;

/**
 * Template Handler — renders virtual posts as real WordPress posts
 * Integrates with themes, SEO plugins, and canonical URLs
 * Architecture from v-posts-manager TemplateHandler
 */
class TemplateHandler {

    private $posts_manager;

    public function __construct(PostsManager $posts_manager) {
        $this->posts_manager = $posts_manager;
    }

    /**
     * Early setup — create WP_Post object before WordPress queries
     */
    public function early_setup_post($wp) {
        if (empty($wp->query_vars['v_post'])) return;

        $slug = sanitize_title($wp->query_vars['v_post']);
        $post_data = $this->posts_manager->get_post($slug);

        if (!$post_data) return;

        // Access control check
        if (!AccessControl::can_access()) {
            return; // Will become 404
        }

        $wp_post = $this->build_wp_post_object($post_data);

        // Cache the post object for WordPress internals
        wp_cache_set($wp_post->ID, $wp_post, 'posts');

        // Set up global post
        $GLOBALS['wpu_current_post'] = $post_data;
    }

    /**
     * Prevent 404 for virtual posts
     */
    public function prevent_404($query) {
        if (!$query->is_main_query()) return;

        $slug = $query->get('v_post');
        if (empty($slug)) return;

        $slug = sanitize_title($slug);
        if ($this->posts_manager->post_exists($slug) && AccessControl::can_access()) {
            $query->is_404 = false;
            $query->is_singular = true;
            $query->is_single = true;
        }
    }

    /**
     * Handle template rendering
     */
    public function handle_template() {
        if (empty($GLOBALS['wpu_current_post'])) return;

        $post_data = $GLOBALS['wpu_current_post'];

        // Access control — return 404 if not allowed
        if (!AccessControl::can_access()) {
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
            return;
        }

        $this->render_post($post_data);
        exit;
    }

    /**
     * Render post using theme's single template
     */
    private function render_post($post_data) {
        global $wp_query, $post;

        $wp_post = $this->build_wp_post_object($post_data);

        // Set up WordPress globals
        $post = $wp_post;
        $wp_query->post = $wp_post;
        $wp_query->posts = [$wp_post];
        $wp_query->post_count = 1;
        $wp_query->found_posts = 1;
        $wp_query->is_singular = true;
        $wp_query->is_single = true;
        $wp_query->is_404 = false;
        $wp_query->queried_object = $wp_post;
        $wp_query->queried_object_id = $wp_post->ID;

        setup_postdata($wp_post);

        // Add meta description
        if (!empty($post_data['meta_description'])) {
            $desc = esc_attr($post_data['meta_description']);
            add_action('wp_head', function () use ($desc) {
                echo '<meta name="description" content="' . $desc . '">' . "\n";
            }, 1);

            // Yoast SEO integration
            add_filter('wpseo_metadesc', function () use ($desc) {
                return $desc;
            });

            // Rank Math integration
            add_filter('rank_math/frontend/description', function () use ($desc) {
                return $desc;
            });
        }

        // Fix canonical URL
        $url = PostsManager::get_post_url($post_data['v_slug']);
        add_filter('get_canonical_url', function () use ($url) { return $url; });
        add_filter('wpseo_canonical', function () use ($url) { return $url; });
        add_filter('rank_math/frontend/canonical', function () use ($url) { return $url; });
        add_action('wp_head', function () use ($url) {
            echo '<link rel="canonical" href="' . esc_url($url) . '">' . "\n";
        }, 1);

        // Set HTTP status
        status_header(200);
        header('X-WPU-Post: 1');

        // Render via our dedicated template file. This bypasses the theme's
        // single.php (which sites often override with Elementor-Pro or
        // BuddyBoss custom templates that drop post_content on the floor)
        // while still keeping the site chrome through get_header/get_footer
        // inside the template.
        $tpl = WPU_PLUGIN_DIR . 'templates/virtual-post.php';
        if (file_exists($tpl)) {
            include $tpl;
        } else {
            // Bare-bones fallback if the template file is somehow missing.
            get_header();
            echo '<main><article>';
            echo '<h1>' . esc_html($post_data['post_title']) . '</h1>';
            echo '<div>' . apply_filters('the_content', $post_data['post_content']) . '</div>';
            echo '</article></main>';
            get_footer();
        }
    }

    /**
     * Build a WP_Post object from post data array
     */
    private function build_wp_post_object($post_data) {
        $post = new \WP_Post((object)[
            'ID'                    => $post_data['ID'],
            'post_author'           => $post_data['post_author'],
            'post_date'             => $post_data['post_date'],
            'post_date_gmt'         => $post_data['post_date_gmt'] ?? $post_data['post_date'],
            'post_content'          => $post_data['post_content'],
            'post_title'            => $post_data['post_title'],
            'post_excerpt'          => '',
            'post_status'           => 'publish',
            'comment_status'        => 'closed',
            'ping_status'           => 'closed',
            'post_password'         => '',
            'post_name'             => $post_data['post_name'],
            'to_ping'               => '',
            'pinged'                => '',
            'post_modified'         => $post_data['post_modified'] ?? $post_data['post_date'],
            'post_modified_gmt'     => $post_data['post_modified'] ?? $post_data['post_date'],
            'post_content_filtered' => '',
            'post_parent'           => 0,
            'guid'                  => $post_data['guid'],
            'menu_order'            => 0,
            'post_type'             => $post_data['post_type'],
            'post_mime_type'        => '',
            'comment_count'         => 0,
            'filter'                => 'raw',
        ]);

        // Custom properties
        $post->is_vpost = true;
        $post->v_slug = $post_data['v_slug'];

        return $post;
    }
}
