<?php

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

final class BBC_Render
{
    const MAX_HTML_BYTES = 2097152;

    public static function boot()
    {
        add_action('template_redirect', array(__CLASS__, 'start'));
    }

    public static function start()
    {
        $uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
        if (is_admin() || wp_doing_ajax() || (defined('REST_REQUEST') && REST_REQUEST) || is_feed() || is_robots() || is_trackback() || strpos($uri, 'sitemap') !== false || !is_front_page()) return;
        if (function_exists('wp_is_json_request') && wp_is_json_request()) return;
        if (!BBC_Placements::all()) return;
        ob_start(array(__CLASS__, 'render'));
    }

    public static function render($html)
    {
        $status = http_response_code();
        if ($status >= 400 || !is_string($html) || strlen($html) > self::MAX_HTML_BYTES || stripos($html, '<html') === false) return $html;
        foreach (headers_list() as $header) {
            if (stripos($header, 'content-type:') === 0 && stripos($header, 'text/html') === false) return $html;
        }
        $insertion = '';
        foreach (BBC_Placements::all() as $entry) {
            $marker = 'bbc:' . $entry['placement_id'] . ':start';
            if (strpos($html, $marker) === false) {
                $insertion .= BBC_Placements::marked_html($entry['placement_id'], $entry['html']);
            }
        }
        if ($insertion === '') return $html;
        $position = strripos($html, '</body>');
        return $position === false ? $html . $insertion : substr($html, 0, $position) . $insertion . substr($html, $position);
    }
}
