<?php

namespace Webien\Setup;
use StoutLogic\AcfBuilder\FieldsBuilder;

/*
 * Clean up some WP stuff and add ACF options for them
 */

class AdminScripts
{

    static $acfGroup;

    public static function init()
    {

        // Add admin scripts
        add_action('admin_head', [__CLASS__, 'printAdminScripts'], 9999);
        // Also include on login screen
        add_action('login_head', [__CLASS__, 'printAdminScripts'], 9999);


        // Option page
        // Start ACF section
        self::$acfGroup = new FieldsBuilder(
            'webien_admin_scripts', ['title' => __('Admin HTML', 'webien')]
        );

        self::addAdminScriptControls();

        // End ACF section
        self::$acfGroup
            ->setLocation('options_page', '==', 'acf-options-webien');

        $acf_group_array = self::$acfGroup->build();
        // Set menu_order here (lower = appears higher)
        $acf_group_array['menu_order'] = 9;
        acf_add_local_field_group($acf_group_array);

    }


    public static function printAdminScripts()
    {
        $customHtml = get_field('webien_admin_custom_html', 'option');
        $loadInHeader = get_field('webien_admin_custom_html_load', 'option');

        if ($customHtml) {
            if ($loadInHeader) {
                echo $customHtml;
            } else {
                add_action('admin_footer', function() use ($customHtml) {
                    echo $customHtml;
                }, 9999);
            }
        }
    }



    private static function addAdminScriptControls()
    {
        self::$acfGroup
            ->addMessage('webien_admin_custom_html_msg', 'Knappar', [
                'label' => 'Använd denna editor för att inkludera egen CSS eller Javascript i wp-admin.',
                'instructions' => '',
                'message' => '<p>Detta är ren HTML, så kom ihåg att wrappa din CSS/javascript med <b>&lt;style&gt;</b> och <b>&lt;script&gt;</b> taggar.</p><div id="webien_admin_custom_html_editor"></div>',
                'esc_html' => 0,
                'new_lines' => ''
            ]);

        self::$acfGroup
            ->addTextarea('webien_admin_custom_html', [
                'label' => __('Egen HTML för wp-admin', 'webien'),
                'required' => 0,
                'new_lines' => '',
            ]);

        self::$acfGroup
            ->addTrueFalse('webien_admin_custom_html_load', [
                'label' => __('', 'webien'),
                'required' => 0,
                'instructions' => '',
                'conditional_logic' => [],
                'wrapper' => [
                ],
                'message' => __('Ladda i header', 'webien'),
                'default_value' => 1,
            ]);

    }

}