<?php

namespace Edoobox\Base;

use Edoobox\Api\ShortcodeApi;
use Edoobox\Requests\Template;

class BodyTag {

    public function register() {
        $postIsNotBeingEdited = ! (isset($_REQUEST["context"]) && $_REQUEST["context"] === "edit");

        if (Auth::isGuest() && $postIsNotBeingEdited) {
            add_filter('body_class', [$this, 'add_data_attribute_to_body_class']);
            add_action('wp_body_open', [$this, 'output_data_bs_attribute'], 10);
            add_action('wp_footer', [$this, 'output_data_bs_attribute_fallback'], 10);
        }
    }

    public function add_data_attribute_to_body_class($classes) {
        // Return the classes unchanged (we're adding the attribute elsewhere)
        return $classes;
    }

    public function output_data_bs_attribute() {
        global $post;

        // Ensure this is only run once
        if (($GLOBALS['edoobox_body_class_count'] ?? 0) > 0) {
            return;
        }
        $GLOBALS['edoobox_body_class_count'] = 1 + ($GLOBALS['edoobox_body_class_count'] ?? 0);

        // Get attributes and template as before
        $attributes = ShortcodeApi::getAttributes($post);
        $template = new Template($attributes);
        $response = $template->fetch();
        $bootstrapVersion = Bootstrap::getVersion($response);

        // Output the data attribute in the body tag
        echo "<script>
            document.body.setAttribute('data-bs', '$bootstrapVersion');
        </script>";
    }

    // Fallback for themes that don't use wp_body_open
    public function output_data_bs_attribute_fallback() {
        if (!did_action('wp_body_open')) {
            $this->output_data_bs_attribute();
        }
    }
}
