<?php

namespace Webien\AI\Dashboard;

class Dashboard
{
    private $nodeApi;
    private $apiEventsUrl;
    //private $nodeApi = 'https://chat.webien.io/api';

    function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'admin_enqueues'], 10);
        add_action('in_admin_header', [$this, 'add_admin_markup'], 10, 3);
        add_filter('admin_footer_text', [$this, 'admin_bottom_text']);

        add_filter('upload_mimes', [$this, 'handle_json_upload']);

        // Set node api
        // If on .test domain use local api
        if(strpos($_SERVER['HTTP_HOST'], '.test') !== false){
            $this->nodeApi = 'http://localhost:3000';
        } else {
            $this->nodeApi = 'https://chat.webien.io/api';
        }



    }

    function admin_enqueues()
    {

        $ver = WEBIEN_AI_VERSION;

        wp_enqueue_style('webien-ai-dashboard', WEBIEN_AI_PLUGIN_URI. '/dist/dashboard.css', [], $ver);
        wp_enqueue_script('webien-ai-dashboard', WEBIEN_AI_PLUGIN_URI . '/dist/dashboard.js', [], $ver, true);
        wp_localize_script( 'webien-ai-dashboard', 'webien', [
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'statusFile' => esc_url_raw(WEBIEN_AI_PLUGIN_URI . '/src/Dashboard/uploadStatus.txt'),
        ]);


        // Add inline script before above handle
        $options = get_option('webien_ai_assistant');
        if(!$options){
            $options = ['id' => null, 'file_id' => null, 'vector_store_id' => null];
        } else {
            $options = json_decode($options);
        }

        $settings = [
            'assistant' => $options,
            'file' => get_option('webien_ai_file') ?: 'Du har inte genererat någon fil än.',
        ];
        wp_add_inline_script('webien-ai-dashboard', 'const webienAiSettings = ' . json_encode($settings) . ';', 'before');

    }


    // Allow json file upload
    function handle_json_upload($mimes) {
        $mimes['json'] = 'text/plain';
        return $mimes;
    }




    function admin_bottom_text()
    {
        echo '<span class=webien-admin-footer-text">Thank you for using <b>Webien</b>! More information and documentation at <a href="https://webien.io" target="_blank">Webien.io</a></span>';
    }

    function add_admin_markup()
    {
        include_once __DIR__ . '/view.php';
    }





    function updateAssistant()
    {

        $newSource = filter_var($_POST['newSource'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

        $sourceFiles = false;

        if($newSource) {
            $sourceFiles = $this->generate();
        }

        $assistant = get_option('webien_ai_assistant');
        $assistantName = $_SERVER['HTTP_HOST'] ?? 'rand-' . time();

        $ch = curl_init($this->nodeApi . '/assistant');

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $instructions = get_field('webien_ai_system_prompt', 'option') . ' ' . get_field('webien_ai_system_prompt_extra', 'option');

        $body = [
            'source_files' => $sourceFiles,
            'assistant' => $assistant,
            'name' => $assistantName,
            'model' => get_field('webien_ai_model', 'option'),
            'instructions' => $instructions,
        ];

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);
        $response = curl_exec($ch);

        curl_close($ch);

        $data = json_decode($response, true);

        $assistant = [
            'id' => $data['id'],
            'vector_store_id' => $data['vector_store_id'],
        ];

        // Check if option exists
        if(get_option('webien_ai_assistant')){
            update_option('webien_ai_assistant', json_encode($assistant));
        } else {
            add_option( 'webien_ai_assistant', json_encode($assistant), false );
        }


        // If there were files downloaded during the process, delete them
        if($sourceFiles) {
            $uploads =  wp_upload_dir();
            $upload_dir = $uploads['basedir'] . '/webien/webien-ai/downloads';
            if (file_exists($upload_dir)) {
                array_map('unlink', glob("$upload_dir/*.*"));
                rmdir($upload_dir);
            }
        }


        wp_send_json_success(['assistant' => $assistant, 'files' => $sourceFiles]);
        die();

    }



    public function generate(): array|bool
    {
        // Check what source we are using
        $source = get_field('webien_ai_source', 'option');

        if(empty($source) || $source === 'site') {
            return $this->generateSourceFromSite();
        } elseif($source === 'google_drive') {
            return (new GoogleDrive())->download();
        } else {
            return false;
        }

    }



    public function generateSourceFromSite(): array
    {

        // Gather data from ACF
        $postTypes = get_field('webien_ai_posttypes', 'option');
        $taxonomies = get_field('webien_ai_taxonomies', 'option');

        $postTypeArr = [];
        $taxonomyArr = [];

        // --- Taxonomies
        foreach ($taxonomies as $taxonomy) {
            $name = $taxonomy['webien_ai_select_taxonomy'];

            $args = [
                'taxonomy' => $name,
                'hide_empty' => false,
            ];
            // If wpml is active limit to SE
            if(defined('ICL_LANGUAGE_CODE')){
                $args['lang'] = 'sv';
            }


            $terms = get_terms($args);

            $termArr = [];
            foreach ($terms as $term) {
                $termArr[] = [
                    'name' => $term->name,
                    'link' => get_term_link($term),
                    'description' => $term->description,
                ];

                // Meta fields
                if(!empty($taxonomy['meta'])) {
                    foreach ($taxonomy['meta'] as $field) {
                        $metaValue = get_term_meta($term->term_id, $field['name'], true);
                        if(!empty($metaValue)){
                            $termArr[$term->name][$field['label']] = $field['meta_prefix'] . $metaValue;
                        }
                    }
                }
            }

            $taxonomyArr[] = [
                'taxonomy' => $name,
                'terms' => $termArr,
            ];
        }




        // --- Post types
        foreach ($postTypes as $postType) {

            $args = [
                'post_type' => $postType['webien_ai_select_posttype'],
                'posts_per_page' => -1,
                'post_status' => 'publish',
                'fields' => 'ids',
            ];

            // If wpml is active limit to SE
            if(defined('ICL_LANGUAGE_CODE')){
                $args['lang'] = 'sv';
                $args['suppress_filters'] = false;
            }
            $posts = get_posts($args);

            foreach ($posts as $id) {
                $postArr = [];

                foreach ($postType['include'] as $include) {

                    if($include === 'title') {
                        $postArr['title'] = get_the_title($id);
                    }
                    if($include === 'content') {
                        $postArr['content'] = $this->extractReadableContent(apply_filters('the_content', get_post_field('post_content', $id)));
                    }
                    if($include === 'link') {
                        $postArr['link'] = get_permalink($id);
                    }

                    if($include === 'categories') {
                        // Get all taxonomies and terms related to this post
                        $taxonomies = get_object_taxonomies($postType['webien_ai_select_posttype']);
                        $taxArr = [];
                        foreach ($taxonomies as $tax) {



                            // Make sure the tax is in the taxonomy list from earlier
                            foreach ($taxonomyArr as $taxArrItem) {

                                if($taxArrItem['taxonomy'] === $tax){
                                    $terms = get_the_terms($id, $tax);
                                    if(!empty($terms)){
                                        $termArr = [];
                                        foreach ($terms as $term) {
                                            $termArr[] = $term->name;
                                        }
                                        $taxArr[$tax] = $termArr;
                                    }
                                }
                            }


                        }
                        $postArr['taxonomies'] = $taxArr;
                    }
                }

                // Meta fields
                if(!empty($postType['meta'])) {
                    foreach ($postType['meta'] as $field) {
                        $metaValue = get_post_meta($id, $field['name'], true);
                        if(!empty($metaValue)){
                            $label = preg_replace('/[^a-zA-ZåäöÅÄÖ]/', '-', $field['label']);
                            $postArr[$label] = $field['meta_prefix'] . $metaValue;
                        }
                    }
                }


                $postTypeArr[] = $postArr;
            }

        }


        $mainArr = [
            'posts' => $postTypeArr,
            'taxonomies' => $taxonomyArr
        ];


        // Generate a json file from main arr
        $json = json_encode($mainArr);

        // Set the path to uploads folder
        $uploads =  wp_upload_dir();

        $upload_dir = $uploads['basedir'] . '/webien/webien-ai';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0775, true);
        }

        $jsonPath = $upload_dir . '/data.json';
        file_put_contents($jsonPath, $json);

        // Save as option
        $jsonUrl = $uploads['baseurl'] . '/webien/webien-ai/data.json';
        update_option('webien_ai_file', $jsonUrl);


        return [$jsonUrl];

    }



    function extractReadableContent($content) {
        // 1. Ta bort <figure> och dess innehåll
        $content = preg_replace('/<figure.*?>.*?<\/figure>/is', '', $content);

        // 2. Ta bort <img>-taggar
        $content = preg_replace('/<img[^>]+>/i', '', $content);

        // 3. Ersätt <a href="">text</a> med "text (url)"
        $content = preg_replace_callback('/<a[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)<\/a>/is', function($matches) {
            $text = strip_tags($matches[2]);
            $url = $matches[1];
            return $text . ' (' . $url . ')';
        }, $content);

        // 4. Rensa alla rubriktaggar från attribut
        $content = preg_replace_callback('/<h([1-6])[^>]*>(.*?)<\/h\1>/is', function($matches) {
            $level = $matches[1];
            $text = strip_tags($matches[2]);
            return "<h$level>$text</h$level>";
        }, $content);

        // 5. Ta bort alla andra HTML-taggar
        $content = strip_tags($content, '<h1><h2><h3><h4><h5><h6>');

        // 6. Ta bort radbrytningar
        $content = str_replace(["\n", "\r"], ' ', $content);

        // 7. Trimma onödiga mellanslag
        $content = preg_replace('/\s+/', ' ', $content);

        return trim($content);
    }




    public function addOptionPage()
    {
        if( function_exists('acf_add_options_page') ) {

            acf_add_options_page(array(
                'page_title'    => '',
                'menu_title'    => 'Webien AI',
                'menu_slug'     => 'webien-ai',
                'capability'    => 'manage_options',
                'icon_url'      => 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(WEBIEN_AI_PLUGIN_PATH . '/assets/images/assistant-white.svg')),
                'redirect'      => false
            ));

            // ACF
            $this->add_options();

        }
    }


    public function add_options()
    {
        $acf = new \StoutLogic\AcfBuilder\FieldsBuilder(
            'webien_ai_settings', ['title' => __('Webien AI', 'webien')]
        );
        $acf
            ->addMessage('message_field', 'Message', [
                'label' => '',
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'message' => 'Se över inställningar nedan som kommer att påverka hur AI:n fungerar.
<br>
<div id="webien-ai-dashboard">
<div class="loader" v-show="loading">
<div v-if="status" class="msg">{{statusText}}</div>
<div class="bar"><div class="inner"></div> </div>
</div>
<div class="check">
<div class="item"><span class="check-settings" :class="settingsClass"></span>Inställningar</div>
<div class="item"><span class="check-file"></span>Genererad källa</div>
</div>


<fieldset>
<legend>Innan du sparar, kom ihåg att klicka på <b>Uppdatera</b> uppe i Publicera boxen först</legend>
<div class="btns">
<button type="button" id="update-ai" class="button button-primary button-large">Spara instruktioner & inställningar</button>
<button type="button" id="generate-file" class="button button-secondary button-large">Generera ny datakälla</button>
</div>
</fieldset>
' .
                    /*
<div class="meta">

<div class="file">Fakta fil: <b><span>{{file}}</span></b></div>
<div class="file">Assistent id: <b><span>{{file}}</span></b></div>
<div class="file">Vector store id: <b><span>{{file}}</span></b></div>
<div class="file">Fil id: <b><span>{{file}}</span></b></div>

</div>
*/
                    '</div>',
                'new_lines' => 'wpautop',
                'esc_html' => 0,
            ])
            ->addTextarea('webien_ai_system_prompt', [
                'label' => __('System prompt', 'webien'),
                'instructions' => __('Denna prompt skickas med som en instruktion till AI:n och sätter reglerna för hela konversationen.', 'webien'),
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'placeholder' => '',
                'maxlength' => '',
                'rows' => '4',
                'new_lines' => '',
                'default_value' => 'Du är en assistent som enbart får svara baserat på information som hittas i det bifogade dokumentet via File Search. Om ingen relevant information hittas i dokumentet, svara med: "Jag kunde inte hitta något svar, vänligen prova en annan fråga eller kontakta kundtjänst." Du får inte gissa eller använda allmän kunskap. Använd så mycket formatering med markdown som möjligt. Fetmarkera namn, värden eller andra nyckelord. Använd tabeller, listor och länkar i ditt svar. Länkar ligger ofta under attributet: "link". Posternas titel ligger under attributet "title" och väger tungt i din sökning. Svara alltid på svenska. Språket ska vara lättsamt men korrekt utan slang. Du ska inte som sista mening uppmuntra att ställa en ny fråga.',
            ])
            ->addTextarea('webien_ai_system_prompt_extra', [
                'label' => __('System prompt - extra', 'webien'),
                'instructions' => __('Tillägg till systemprompten som kan innehålla specifika instruktioner för denna installation.', 'webien'),
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'placeholder' => '',
                'maxlength' => '',
                'rows' => '4',
                'new_lines' => '',
                'default_value' => '',
            ])
            ->addTextarea('webien_ai_first_msg', [
                'label' => __('Första meddelande', 'webien'),
                'instructions' => __('Visas när chatten startas.', 'webien'),
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'placeholder' => '',
                'maxlength' => '',
                'rows' => '2',
                'new_lines' => '',
                'default_value' => 'Välkommen! Vad vill du veta? Jag hjälper dig så gott jag kan.',
            ])
            ->addTrueFalse('webien_ai_show_on_site', [
                'label' => __('Visa knapp', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'message' => __('Visa alltid chattknappen på webbplatsen.', 'webien'),
                'default_value' => 1,
                'ui' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
            ])
            ->addTrueFalse('webien_ai_show_info', [
                'label' => __('Visa info', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'message' => 'Visa metadata i chatten.',
                'default_value' => 1,
                'ui' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
            ])
            ->addText('webien_ai_api_key', [
                'label' => __('API nyckel', 'webien'),
                'instructions' => '&nbsp;',
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => 'intro-nyckel',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addUser('webien_ai_limit_user', [
                'label' => __('Limitera för användare', 'webien'),
                'instructions' => 'Visar endast chatten för specade användare. Tomt = alla',
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'role' => '',
                'allow_null' => 0,
                'multiple' => 1,
                'return_format' => 'id',

            ])
            ->addSelect('webien_ai_model', [
                'label' => __('AI modell', 'webien'),
                'instructions' => 'Priser varierar beroende på modell. <a href="https://platform.openai.com/docs/pricing" target="_blank">Visa &rarr;</a>',
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [
                    'gpt-4o' => 'gpt-4o',
                    'gpt-4-turbo' => 'gpt-4-turbo',
                    'gpt-4o-mini' => 'gpt-4o-mini',
                    'gpt-3.5-turbo' => 'gpt-3.5-turbo',
                ],
                'default_value' => [],
                'allow_null' => 0,
                'multiple' => 0,
                'ui' => 0,
                'ajax' => 0,
                'return_format' => 'value',
                'placeholder' => '',
            ])
            ->addSelect('webien_ai_source', [
                'label' => __('Välj din datakälla', 'webien'),
                'instructions' => __('Vartifrån datakällan ska komma ifrån.', 'webien'),
                'required' => 0,
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [
                    'site' => 'Denna webbplats',
                    'google_drive' => 'Google drive',
                ],
                'default_value' => [
                    'site',
                ],
                'allow_null' => 0,
                'multiple' => 0,
                'ui' => 0,
                'ajax' => 0,
                'return_format' => 'value',
                'placeholder' => '',
            ])
            ->addRepeater('webien_ai_posttypes', [
                'button_label' => 'Lägg till posttyp',
                'layout' => 'block',
                'label' => 'Posttyper',
                'conditional_logic' => [
                    [
                        [
                            'field' => 'webien_ai_source',
                            'operator' => '==',
                            'value' => 'site',
                        ],
                    ],
                ],
            ])
            ->addSelect('webien_ai_select_posttype', [
                'label' => __('Posttyp', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [],
                'default_value' => [],
                'allow_null' => 0,
                'multiple' => 0,
                'ui' => 0,
                'ajax' => 0,
                'return_format' => 'value',
                'placeholder' => '',
            ])
            ->addCheckbox('include', [
                'label' => __('Inkludera', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [
                    'title' => 'Titel',
                    'content' => 'Innehåll',
                    'link' => 'Länk',
                    'categories' => 'Kategorier',
                ],
                'allow_custom' => 0,
                'save_custom' => 0,
                'default_value' => [

                ],
                'layout' => 'vertical',
                'toggle' => 1,
                'return_format' => 'value',
            ])
            ->addRepeater('meta', [
                'button_label' => 'Lägg till metafält',
                'layout' => 'table',
            ])
            ->addText('label', [
                'label' => 'Meta etikett',
                'instructions' => 'Meta fältets etikett för AI:n',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addText('meta_prefix', [
                'label' => 'Meta prefix',
                'instructions' => 'Addera text innan värdet om det behövs',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addText('name', [
                'label' => 'Meta namn',
                'instructions' => 'Postmetafältets namn',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->endRepeater()
            ->endRepeater()

            // Taxonomies
            ->addRepeater('webien_ai_taxonomies', [
                'button_label' => 'Lägg till taxanomi',
                'layout' => 'block',
                'label' => 'Taxanomier',
                'conditional_logic' => [
                    [
                        [
                            'field' => 'webien_ai_source',
                            'operator' => '==',
                            'value' => 'site',
                        ],
                    ],
                ],
            ])
            ->addSelect('webien_ai_select_taxonomy', [
                'label' => __('Taxanomi', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [],
                'default_value' => [],
                'allow_null' => 0,
                'multiple' => 0,
                'ui' => 0,
                'ajax' => 0,
                'return_format' => 'value',
                'placeholder' => '',
            ])
            ->addCheckbox('include', [
                'label' => __('Inkludera', 'webien'),
                'instructions' => '',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'choices' => [
                    'title' => 'Titel',
                    'description' => 'Beskrivning',
                    'terms' => 'Termer',
                    'link' => 'Länk',
                ],
                'allow_custom' => 0,
                'save_custom' => 0,
                'default_value' => [

                ],
                'layout' => 'vertical',
                'toggle' => 1,
                'return_format' => 'value',
            ])
            ->addRepeater('meta', [
                'button_label' => 'Lägg till metafält',
                'layout' => 'table',
            ])
            ->addText('label', [
                'label' => 'Meta etikett',
                'instructions' => 'Meta fältets etikett för AI:n',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addText('meta_prefix', [
                'label' => 'Meta prefix',
                'instructions' => 'Addera text innan värdet om det behövs',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addText('name', [
                'label' => 'Meta namn',
                'instructions' => 'Postmetafältets namn',
                'required' => 0,
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->endRepeater()
            ->endRepeater()


            // --- Google drive fields

            ->addGroup('webien_ai_google_drive', [
                'label' => __('Google drive', 'webien'),
                'instructions' => __('Använd dokument från en mapp i din Google Drive som datakälla. För att generera åtkomst, se <a target="_blank" href="https://webien.io/webien-ai/docs#google-drive">dokumentationen</a>.', 'webien'),
                'layout' => 'block',
                'sub_fields' => [],
                'wrapper' => [
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ],
                'conditional_logic' => [
                    [
                        [
                            'field' => 'webien_ai_source',
                            'operator' => '==',
                            'value' => 'google_drive',
                        ],
                    ],
                ],
            ])

            ->addText('webien_ai_google_drive_folder_id', [
                'label' => __('Google drive folder id', 'webien'),
                'instructions' => __('Id på din Google Drive mapp. Hittas i slutet av URL:en. Alla giltiga dokument i mappen kommer att läsas in.', 'webien'),
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'default_value' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
                'maxlength' => '',
            ])
            ->addFile('webien_ai_google_drive_service_account', [
                'label' => __('Service account credentials', 'webien'),
                'instructions' => __('Ladda upp den genererade json filen för ditt service account.', 'webien'),
                'wrapper' => [
                    'width' => '50',
                    'class' => '',
                    'id' => '',
                ],
                'return_format' => 'id',
                'library' => 'all',
                'multiple' => 0,
            ])
            ->endGroup()


            ->setLocation('options_page', '==', 'webien-ai');

        acf_add_local_field_group($acf->build());
    }








    function handle_server_events() {

        $data = [
            'status' => 'ok',
            'message' => 'Server events are working',
        ];

        $response = new \WP_REST_Response($data, 200);

        $response->header( 'Content-Type', 'text/event-stream' );
        $response->header( 'Cache-Control', 'no-cache' );
        $response->header( 'Access-Control-Allow-Origin', '*' ); //(this if you need to connect on the externale resource)

        return $response;

    }


}