<?php

namespace SWPanel;

defined('ABSPATH') || die('No direct access.');

use SWPanel\APIClient;
use SWPanel\WpRestClient;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class SettingsManager {
    protected static function config($extra = []) {
        $config = [            
            'id' => get_option('swpanel_ai_site_id', ''),
            'title' => html_entity_decode(get_option('blogname', ''), ENT_QUOTES | ENT_HTML5, 'UTF-8'),
            'description' => html_entity_decode(get_option('blogdescription', ''), ENT_QUOTES | ENT_HTML5, 'UTF-8'),
            'tones' => array(
                html_entity_decode(get_option('swpanel_ai_tone', ''), ENT_QUOTES | ENT_HTML5, 'UTF-8')
            ),
            'language' => get_locale(),
            'version' => get_plugin_data(WP_PLUGIN_DIR . "/swpanel-ai/swpanel-ai.php")['Version'],
            'wpversion' => get_bloginfo('version'),
            'improved_description' => html_entity_decode(get_option('swpanel_ai_improved_description', ''), ENT_QUOTES | ENT_HTML5, 'UTF-8'),
        ];
        if (!empty($extra) && is_array($extra)) {
            $config = array_merge($config, $extra);
        }
        return $config;
    }

    public static function getConceptData() {
        return [
            'title' => get_option('blogname'),
            'description' => get_option('blogdescription'),
            'tone' => get_option('swpanel_ai_tone', ''),
            'all_tones' => [[
                    'title' => __('Formal', 'swpanel-ai'),
                    'description' => __('Ideal for businesses, professionals, or projects that want to convey seriousness and trust.', 'swpanel-ai'),
                ], [
                    'title' => __('Informal', 'swpanel-ai'),
                    'description' => __('Perfect for more approachable, creative businesses or those with a friendly and casual tone.', 'swpanel-ai'),
            ]]
        ];
    }

    public static function saveConceptData($post) {
        $modified = get_option('swpanel_ai_run_description_keywords_task', 0);
        $new_title = strtoupper(sanitize_text_field(wp_unslash($post['site_title'])));
        $old_title = html_entity_decode(get_option('blogname'), ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $new_description = ucfirst(sanitize_text_field(wp_unslash($post['site_description'])));
        $old_description = html_entity_decode(get_option('blogdescription'), ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $new_tones = sanitize_text_field(wp_unslash($post['site_tone']));
        $old_tones = html_entity_decode(get_option('swpanel_ai_tone', ''), ENT_QUOTES | ENT_HTML5, 'UTF-8');
        if ($new_title !== $old_title || $new_description !== $old_description || $new_tones !== $old_tones || !get_option('swpanel_ai_improved_description') || !get_option('swpanel_ai_images')) {
            $modified = 1;
            update_option('blogname', $new_title);
            update_option('blogdescription', $new_description);
            update_option('swpanel_ai_tone', $new_tones);
        }
        update_option('swpanel_ai_run_description_keywords_task', $modified);
        update_option('swpanel_ai_run_creating_task', $modified);
        update_option('swpanel_ai_run_create_previews_task', $modified);
        update_option('swpanel_ai_run_headers_task', $modified);
    }


    public static function getDescriptionKeywords() {
        try {
            $improved_description = ucfirst(APIClient::post("/description", self::config()));
            $modified = get_option('swpanel_ai_run_headers_task', 0);
            $old_description = html_entity_decode(get_option('swpanel_ai_improved_description'), ENT_QUOTES | ENT_HTML5, 'UTF-8');
            if ($improved_description !== $old_description) {
                update_option('swpanel_ai_improved_description', sanitize_text_field($improved_description));
                $modified = 1;
            }
            update_option('swpanel_ai_run_headers_task', $modified);
            update_option('swpanel_ai_run_creating_task', $modified);
            update_option('swpanel_ai_run_create_previews_task', $modified);
            $keywords = APIClient::post("/keywords", self::config());
            $lang = get_locale();
            update_option('swpanel_ai_keywords', array_map('sanitize_text_field', $keywords));
            $images = APIClient::get("/search/images?keyword={$keywords[0]}&page=1&per_page=10&lang={$lang}");
            if (empty($images)) {
			    // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                throw new \Exception(__("We couldn't find any images matching your content. Please try modifying your title or description to be more specific or descriptive.", 'swpanel-ai'));
            }
            update_option('swpanel_ai_images', $images);
            delete_option('swpanel_ai_run_description_keywords_task');
            wp_send_json_success();
        } catch (\Exception $e) {
            update_option('swpanel_ai_run_description_keywords_task', 1);
            if (strpos($e->getMessage(), "504 Gateway Time-out") !== false) {     
                wp_send_json_error([
                    'message' => __("The request timed out. Please try again or check api status.", 'swpanel-ai'),
                ]);
            }
            wp_send_json_error([
                'message' => $e->getMessage(),
            ]);
        }
    }

    public static function getHeaders() {
        try {
            $headers = APIClient::post('/headers', self::config());
            update_option('swpanel_ai_headers', array_map(function($item) {
                return ucfirst(sanitize_text_field($item));
            }, $headers ?? []));
            $titles = APIClient::post('/titles', self::config());
            update_option('swpanel_ai_titles', array_map(function($item) {
                return ucfirst(sanitize_text_field($item));
            }, $titles ?? []));
            delete_option('swpanel_ai_run_headers_task');
            wp_send_json_success();
        } catch (\Exception $e) {
            update_option('swpanel_ai_run_headers_task', 1);
            if (strpos($e->getMessage(), "504 Gateway Time-out") !== false) {     
                wp_send_json_error([
                    'message' => __("The request timed out. Please try again or check api status.", 'swpanel-ai'),
                ]);
            }
            wp_send_json_error([
                'message' => $e->getMessage(),
            ]);
        }
    }

    public static function getStructureData() {
        return get_option('swpanel_ai_page_type', 'single');
    }

    public static function saveStructureData($page_type) {
        $modified = get_option('swpanel_ai_run_creating_task', 0);
        $new_structure = sanitize_text_field($page_type);
        $old_structure = get_option('swpanel_ai_page_type');
        if ($new_structure !== $old_structure) {
            update_option('swpanel_ai_page_type', $new_structure);
            $modified = 1;
        }
        update_option('swpanel_ai_run_creating_task', $modified);
        update_option('swpanel_ai_run_create_previews_task', $modified);
        if (!get_option('swpanel_ai_headers') || !get_option('swpanel_ai_titles')) {
            update_option('swpanel_ai_run_headers_task', 1);
            update_option('swpanel_ai_run_creating_task', 1);
            update_option('swpanel_ai_run_create_previews_task', 1);
        }
    }

    public static function getStyleData() {
        try {
            $variations = WpRestClient::get('/wp/v2/global-styles/themes/twentytwentyfive/variations');
            return [
                'variations' => array_slice($variations, 0, 8),
                'selected_variation' => get_option('swpanel_ai_style'),
                'message_error' => __('The activated theme is invalid or an internal API error occurred.', 'swpanel-ai' ),
            ];
        } catch (\Exception $e) {
            return [
                'variations' => [],
                'selected_variation' => '',
                'message_error' => __('The activated theme is invalid or an internal API error occurred.', 'swpanel-ai')
            ];
        }
    }

    public static function saveStyleData($style) {
        $modified = get_option('swpanel_ai_run_creating_task', 0);
        $new_style = json_decode($style, true);
        $old_style = get_option('swpanel_ai_style');
        if ($new_style !== $old_style) {
            $modified = 1;
            update_option('swpanel_ai_style', $new_style);
        }
        update_option('swpanel_ai_run_creating_task', $modified);
    }

    public static function createPreviewPages() {
        try {
            SettingsManager::updateStyle(get_option('swpanel_ai_style'));
            if (!get_option('swpanel_ai_run_create_previews_task') && !empty(get_option('swpanel_ai_preview_pages', []))){
                wp_send_json_success(get_option('swpanel_ai_preview_pages'));
            }
            $section_labels = [
                'services'  => __('SERVICES', 'swpanel-ai'),
                'witnesses' => __('WITNESSES', 'swpanel-ai'),
                'events'    => __('EVENTS', 'swpanel-ai'),
                'features'  => __('FEATURES', 'swpanel-ai'),
                'gallery'   => __('GALLERY', 'swpanel-ai'),
                'portfolio' => __('PORTFOLIO', 'swpanel-ai'),
                'blog'      => __('BLOG', 'swpanel-ai'),
                'about-us'  => __('ABOUT US', 'swpanel-ai'),
                'contact'   => __('CONTACT', 'swpanel-ai'),
            ];

            SettingsManager::deletePreviewPosts();

            $sections = APIClient::post("/sections", self::config());
            update_option('swpanel_ai_sections', $sections);

            if (in_array('blog', $sections)) {
                $posts_data = [];
                $previews = APIClient::post("/posts-previews", [
                    'headers' => get_option('swpanel_ai_titles'),
                    'images' => get_option('swpanel_ai_images'),
                    'count' => 3
                ]);
                foreach ($previews as $index => $preview) {
                    $post_id = SettingsManager::createPost(
                        $preview['header'],
                        $preview['content'],
                        $preview['image']['url'],
                    );
                    \add_post_meta($post_id, 'made_with_swpanel_ai_preview', 1);
                    $posts_data[] = [
                        'slug' => $preview['slug'],
                        'header' => $preview['header'],
                        'image' => $preview['image'],
                    ];
                }
                update_option('swpanel_ai_preview_posts_data', $posts_data);

                $blog_page_id = wp_insert_post([
                    'post_title' => "blog-preview",
                    'post_content' => "",
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_name' => 'blog-preview',
                    'page_template' => 'template-swpanel-ai'
                ]);
                if (!$blog_page_id) {
			        // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                    throw new \Exception(__('Unable to create the page. Please try again.', 'swpanel-ai'));
                }
                \add_post_meta($blog_page_id, 'made_with_swpanel_ai_preview', 1);
                update_option('page_for_posts', $blog_page_id);
            }

            $previews = APIClient::post("/previews", [
                'headers' => get_option('swpanel_ai_headers'),
                'images' => get_option('swpanel_ai_images'),
                'sections' => $sections,
                'count' => 12
            ]);
            $pages = [];
            $pages_data = [];
            foreach ($previews as $index => $preview) {
                $navbar_pages = [];
                $nav_id = \wp_insert_post([
                    'post_type' => 'wp_navigation',
                    'post_title' => 'navigation',
                    'post_status' => 'publish',
                    'post_content' => ''
                ]);
                \add_post_meta($nav_id, 'made_with_swpanel_ai_preview', 1);
                $header_id = WpRestClient::post('/wp/v2/template-parts', [
                    'title'    => 'preview-header'. $index,
                    'slug'    => 'preview-header'. $index,
                    'theme'   => 'twentytwentyfive',
                    'type'    => 'wp_template_part',
                    'area'    => 'header',
                    'content' => str_replace(
                        '#id', $nav_id,
                        $preview['header']['content']
                    ),
                    'status'  => 'publish'
                ]);
                $footer_id = WpRestClient::post('/wp/v2/template-parts', [
                    'title'    => 'preview-footer' . $index,
                    'slug'    => 'preview-footer' . $index,
                    'theme'   => 'twentytwentyfive',
                    'type'    => 'wp_template_part',
                    'area'    => 'footer',
                    'content' => str_replace(
                        '#id', $nav_id,
                        $preview['footer']['content']
                    ),
                    'status'  => 'publish'
                ]);
                $template_id = WpRestClient::post('/wp/v2/templates', [
                    'title' => 'preview-template' . $index,
                    'slug' => 'preview-template' . $index,
                    'content' => str_replace(
                        ['#header', '#footer'],
                        ['preview-header' . $index, 'preview-footer' . $index],
                        $preview['template']['content']
                    ),
                    'status'  => 'publish'
                ]);
                $content = '';
                $pattern_data = [];
                foreach ($preview['patterns'] as $pattern) {
                    if ('single' == get_option('swpanel_ai_page_type', 'single')) {
                        $content .= $pattern['content'];
                    } else {
                        $new_multi_page_id = wp_insert_post([
                            'post_title'   => 'preview-title-' . $pattern['section'] . $index,
                            'post_content' => $pattern['content'],
                            'post_status'  => 'publish',
                            'post_type'    => 'page',
                            'post_name'   => 'preview-name-' . $pattern['section'] . $index,
                            'page_template' => 'preview-template' . $index,
                        ]);
                        \add_post_meta($new_multi_page_id, 'made_with_swpanel_ai_preview', 1);
                        if ($pattern['section'] == 'about-us'){
                            $pages[] = [
                                'id'  => $new_multi_page_id,
                                'url' => add_query_arg('noadminbar', 1, get_permalink($new_multi_page_id)),
                            ];
                            $new_page_id = $new_multi_page_id;
                        }
                        $navbar_pages[] = [
                            'url'    => add_query_arg('noadminbar', 1, get_permalink($new_multi_page_id)),
                            'label' => isset($section_labels[$pattern['section']])
                                ? $section_labels[$pattern['section']]
                                : esc_html($pattern['section']),
                        ];
                    }
                    $pattern_data[] = [
                        'section' => $pattern['section'],
                        'slug' => $pattern['slug'],
                        'header' => $pattern['header'],
                        'images' => $pattern['images'],
                    ];
                }
                if ('single' == get_option('swpanel_ai_page_type', 'single')) {
                    $new_page_id = wp_insert_post([
                        'post_title'   => 'preview-title' . $index,
                        'post_content' => $content,
                        'post_status'  => 'publish',
                        'post_type'    => 'page',
                        'post_name'   => 'preview-name' . $index,
                        'page_template' => 'preview-template' . $index,
                    ]);
                    \add_post_meta($new_page_id, 'made_with_swpanel_ai_preview', 1);
                    $pages[] = [
                        'id'  => $new_page_id,
                        'url' => add_query_arg('noadminbar', 1, get_permalink($new_page_id)),
                    ];
                    foreach ($sections as $section) {
                        $navbar_pages[] = [
                            'url'    => add_query_arg('noadminbar', 1, get_permalink($new_page_id)) . '#' . $section,
                            'label' => isset($section_labels[$section])
                                ? $section_labels[$section]
                                : esc_html($section),
                        ];
                    }
                }
                $pages_data[$new_page_id] = [
                    'template' => $preview['template']['slug'],
                    'header'   => $preview['header']['slug'],
                    'footer'   => $preview['footer']['slug'],
                    'patterns' => $pattern_data
                ];

                $navbar_content = APIClient::post("/navbar", [
                    'pages' => $navbar_pages
                ]);
                wp_update_post([
                    'ID' => $nav_id,
                    'post_content' => $navbar_content,
                ]);
            }

            update_option('swpanel_ai_preview_pages', $pages);
            update_option('swpanel_ai_preview_pages_data', $pages_data);

            delete_option('swpanel_ai_run_create_previews_task');
            wp_send_json_success($pages);
        } catch (\Exception $e) {
            update_option('swpanel_ai_run_create_previews_task', 1);
            if (strpos($e->getMessage(), "504 Gateway Time-out") !== false) {     
                wp_send_json_error([
                    'message' => __("The request timed out. Please try again or check api status.", 'swpanel-ai'),
                ]);
            }
            wp_send_json_error([
                'message' => $e->getMessage(),
            ]);
        }
    }

    public static function setTemplatePages() {
        if (empty(get_option('swpanel_ai_preview_pages', []))) {
            update_option('swpanel_ai_run_create_previews_task', 1);
        }
    }

    public static function saveTemplatePagesData($preview_id) {
        $pages_data = get_option('swpanel_ai_preview_pages_data');
        if (isset($pages_data[$preview_id])) {
            $selected_id = $preview_id;
        } else {
            $keys = array_map('intval', array_keys($pages_data));
            $closest = $keys[0];
            $min_diff = abs($preview_id - $closest);

            foreach ($keys as $key) {
                $diff = abs($preview_id - $key);
                if ($diff < $min_diff) {
                    $closest = $key;
                    $min_diff = $diff;
                }
            }
            $selected_id = $closest;
        }

        update_option('swpanel_ai_preview_id', $selected_id);
        update_option('swpanel_ai_run_creating_task', 1);
    }

    public static function createTask() {
        as_schedule_single_action(time(), 'swpanel_ai_long_task', array(), '', true);
        set_transient('swpanel_ai_background_task', ['status' => 'pending'], 5 * MINUTE_IN_SECONDS);
        SettingsManager::update_creating_step(0);
        delete_option('swpanel_ai_run_creating_task');
        wp_send_json_success();
    }

    public static function update_creating_step($index) {
        $steps = [
            __("Waiting for the process to start", 'swpanel-ai'),
            __("Retrieving the selected page structure", 'swpanel-ai'),
            __("Removing previously created pages", 'swpanel-ai'),
            __("Building the header, footer, and navigation menu", 'swpanel-ai'),
            __("Generating content for each section", 'swpanel-ai'),
            __("Creating the pages and sections", 'swpanel-ai'),
        ];
        $statusData = [
            'status' => 'started',
            'steps' => [
                [
                    'text' => __('Generating a unique description and selecting relevant keywords', 'swpanel-ai'),
                    'status' => 'done'
                ], [
                    'text' => __("Looking for the best ideas for your site's titles and images", 'swpanel-ai'),
                    'status' => 'done'
                ], [
                    'text' => __('Building preview pages', 'swpanel-ai'),
                    'status' => 'done'
                ]
            ]
        ];
        foreach ($steps as $i => $text) {
            if ($i < $index) {
                $status = 'done';
            } elseif ($i === $index) {
                $status = 'started';
            } else {
                $status = 'pending';
            }
            $statusData['steps'][] = [
                'text' => $text,
                'status' => $status
            ];
        }
        set_transient('swpanel_ai_background_task', $statusData, 5 * MINUTE_IN_SECONDS);
    }
    
    public static function creatingPage() {
        try {
            $preview_data = get_option('swpanel_ai_preview_pages_data');
            $preview_id = get_option('swpanel_ai_preview_id');

            $section_labels = [
                'services'  => __('SERVICES', 'swpanel-ai'),
                'witnesses' => __('WITNESSES', 'swpanel-ai'),
                'events'    => __('EVENTS', 'swpanel-ai'),
                'features'  => __('FEATURES', 'swpanel-ai'),
                'gallery'   => __('GALLERY', 'swpanel-ai'),
                'portfolio' => __('PORTFOLIO', 'swpanel-ai'),
                'blog'      => __('BLOG', 'swpanel-ai'),
                'about-us'  => __('ABOUT US', 'swpanel-ai'),
                'contact'   => __('CONTACT', 'swpanel-ai'),
            ];

            SettingsManager::update_creating_step(1);

            if (!isset($preview_data[$preview_id])) {
			    // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                throw new \Exception(__('The selected preview is invalid. Please try again or go back and choose a different preview.', 'swpanel-ai'));
            }
            $template_slug = $preview_data[$preview_id]['template'];
            $header_slug = $preview_data[$preview_id]['header'];
            $footer_slug = $preview_data[$preview_id]['footer'];
            $template_content = APIClient::get("/template/$template_slug");
            $header_content = APIClient::get("/header/$header_slug");
            $footer_content = APIClient::get("/footer/$footer_slug");

            $domain = home_url();
            $parsed_dom = wp_parse_url($domain);

            SettingsManager::update_creating_step(2);

            SettingsManager::deleteCreatedPosts();

            $nav_id = \wp_insert_post([
                'post_type' => 'wp_navigation',
                'post_title' => __('Navigation SWPanel-AI', 'swpanel-ai'),
                'post_status' => 'publish',
                'post_content' => ''
            ]);
            if (!$nav_id) {
			    // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                throw new \Exception(__('Unable to create the main navigation. Please try again.', 'swpanel-ai'));
            }
            \add_post_meta($nav_id, 'made_with_swpanel_ai', 1);
			$header_post_id = wp_insert_post([
				'post_title'   => __('Header SWPanel-AI', 'swpanel-ai'),
				'post_name'    => 'header-swpanel-ai',
				'post_content' => str_replace('#id', $nav_id, $header_content),
				'post_status'  => 'publish',
				'post_type'    => 'wp_template_part',
			]);
			wp_set_object_terms($header_post_id, 'header', 'wp_template_part_area');
			wp_set_object_terms($header_post_id, 'twentytwentyfive', 'wp_theme');
			$footer_post_id = wp_insert_post([
				'post_title'   => __('Footer SWPanel-AI', 'swpanel-ai'),
				'post_name'    => 'footer-swpanel-ai',
				'post_content' => str_replace('#id', $nav_id, $footer_content),
				'post_status'  => 'publish',
				'post_type'    => 'wp_template_part',
			]);
			wp_set_object_terms($footer_post_id, 'footer', 'wp_template_part_area');
			wp_set_object_terms($footer_post_id, 'twentytwentyfive', 'wp_theme');
			$template_post_id = wp_insert_post([
				'post_title'   => __('Template SWPanel-AI', 'swpanel-ai'),
				'post_name'    => 'template-swpanel-ai',
				'post_content' => str_replace(
                    ['#header', '#footer'],
                    ['header-swpanel-ai', 'footer-swpanel-ai'],
                    $template_content
                ),
				'post_status'  => 'publish',
				'post_type'    => 'wp_template',
			]);
			wp_set_object_terms($template_post_id, 'twentytwentyfive', 'wp_theme');

            SettingsManager::update_creating_step(3);

            $sections = get_option('swpanel_ai_sections', []);
            if (in_array('blog', $sections)) {
                $posts_data = get_option('swpanel_ai_preview_posts_data');
                foreach ($posts_data as $index => $post) {
                    $post_content = APIClient::post("/post/", self::config([
                        'slug' => $post['slug'],
                        'header' => $post['header'],
                    ]));
                    $post_id = SettingsManager::createPost(
                        $post['header'],
                        $post_content,
                        $post['image']['url'],
                    );
                    \add_post_meta($post_id, 'made_with_swpanel_ai', 1);
                }
    
                $blog_page_id = wp_insert_post([
                    'post_title' => "BLOG SWPanel-AI",
                    'post_content' => "",
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_name' => 'blog',
                    'page_template' => 'template-swpanel-ai'
                ]);
                if (!$blog_page_id) {
			        // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                    throw new \Exception(__('Unable to create the page. Please try again.', 'swpanel-ai'));
                }
                \add_post_meta($blog_page_id, 'made_with_swpanel_ai', 1);
                update_option('page_for_posts', $blog_page_id);
            }

            $navbar_pages = [];
            $page_content = '';
            foreach ($preview_data[$preview_id]['patterns'] as $pattern) {
                $page_content .= APIClient::post("/pattern/",  self::config([
                    'slug'    => $pattern['slug'],
                    'section' => $pattern['section'],
                    'header' => $pattern['header'],
                    'images' => $pattern['images'],
                ]));
                        
                if ('single' != get_option('swpanel_ai_page_type', 'single')) {
                    $new_page_id = wp_insert_post([
                        'post_title' => isset($section_labels[$pattern['section']])
                                ? $section_labels[$pattern['section']]
                                : esc_html($pattern['section']),
                        'post_content' => $page_content,
                        'post_status'  => 'publish',
                        'post_type'    => 'page',
                        'post_name' => isset($section_labels[$pattern['section']])
                                ? $section_labels[$pattern['section']]
                                : esc_html($pattern['section']),
                        'page_template' => 'template-swpanel-ai'
                    ]);
                    if (!$new_page_id) {
			            // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                        throw new \Exception(__('Unable to create the page. Please try again.', 'swpanel-ai'));
                    }
                    \add_post_meta($new_page_id, 'made_with_swpanel_ai', 1);
                    if ($pattern['section'] == 'about-us'){
                        update_option('show_on_front', 'page');
                        update_option('page_on_front', $new_page_id);
                    }
                    $page_content = '';
                    
                    $navbar_pages[] = [
                        'url'    => get_permalink($new_page_id),
                        'label' => isset($section_labels[$pattern['section']])
                                ? $section_labels[$pattern['section']]
                                : esc_html($pattern['section']),
                    ];
                }
            }

            SettingsManager::update_creating_step(4);

            if ('single' == get_option('swpanel_ai_page_type', 'single')) {
                $new_page_id = wp_insert_post([
                    'post_title'   => __('Home SWPanel-AI', 'swpanel-ai'),
                    'post_content' => $page_content,
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_name'   => __('Home SWPanel-AI', 'swpanel-ai'),
                    'page_template' => 'template-swpanel-ai'
                ]);
                if (!$new_page_id) {
			        // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                    throw new \Exception(__('Unable to create the page. Please try again.', 'swpanel-ai'));
                }
                \add_post_meta($new_page_id, 'made_with_swpanel_ai', 1);
                update_option('show_on_front', 'page');
                update_option('page_on_front', $new_page_id);
                foreach ($preview_data[$preview_id]['patterns'] as $pattern) {
                    $navbar_pages[] = [
                        'url'   => $parsed_dom['host'] . '#' . $pattern['section'],
                        'label' => isset($section_labels[$pattern['section']])
                                ? $section_labels[$pattern['section']]
                                : esc_html($pattern['section']),
                    ];
                }
            }

            SettingsManager::update_creating_step(5);

            $navbar_content = APIClient::post("/navbar", self::config([
                'pages' => $navbar_pages
            ]));
            $update_id = wp_update_post([
                'ID' => $nav_id,
                'post_content' => $navbar_content,
            ]);
            if (!$update_id) {
			    // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                throw new \Exception(__('Unable to update the navigation menu. Please try again.', 'swpanel-ai'));
            }

            SettingsManager::deletePreviewPosts();
            update_option('swpanel_ai_redirect', 1);
            set_transient('swpanel_ai_background_task', [
                'status' => 'done',
            ], 5 * MINUTE_IN_SECONDS);
        } catch (\Exception $e) {
            update_option('swpanel_ai_run_creating_task', 1);
            set_transient('swpanel_ai_background_task', [
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 5 * MINUTE_IN_SECONDS);
        }
    }

    public static function updateStyle($style) {
        $post_id = \WP_Theme_JSON_Resolver::get_user_global_styles_post_id();
        WpRestClient::post("/wp/v2/global-styles/{$post_id}",[
            'id'      => $post_id,
            'settings' => $style['settings'] ?? [],
            "styles"=> $style['styles'] ?? [],
        ]);
    }

    public static function deletePreviewPosts() {
        delete_option('swpanel_ai_preview_pages');
        $posts = get_posts([
            'numberposts' => -1,
            'post_type' => ['page', 'post', 'wp_navigation'],
            'fields' => 'ids',
        ]);
        foreach ($posts as $post_id) {
            if (get_post_meta($post_id, 'made_with_swpanel_ai_preview', true)) {
                $thumbnail_id = get_post_thumbnail_id($post_id);
                if ($thumbnail_id) {
                    wp_delete_attachment($thumbnail_id, true);
                }
                $attachments = get_children([
                    'post_parent' => $post_id,
                    'post_type'   => 'attachment',
                    'fields'      => 'ids',
                ]);
                foreach ($attachments as $attachment_id) {
                    wp_delete_attachment($attachment_id, true);
                }
                wp_delete_post($post_id, true);
            }
        }
        $posts = get_posts([
            'numberposts' => -1,
            'post_type'   => ['wp_template', 'wp_template_part'],
            'fields'      => 'ids',
        ]);
        foreach ($posts as $post_id) {
            $slug = get_post_field('post_name', $post_id);
            if (strpos($slug, 'preview-') !== false) {
                wp_delete_post($post_id, true);
            }
        }
    }

    public static function deleteCreatedPosts() {
        $posts = get_posts([
            'numberposts' => -1,
            'post_type' => ['page', 'post', 'wp_navigation'],
            'fields' => 'ids',
        ]);
        foreach ($posts as $post_id) {
            if (get_post_meta($post_id, 'made_with_swpanel_ai', true)) {
                wp_delete_post($post_id, true);
            }
        }
        $posts = get_posts([
            'numberposts' => -1,
            'post_type'   => ['wp_template', 'wp_template_part'],
            'fields'      => 'ids',
        ]);
        foreach ($posts as $post_id) {
            $slug = get_post_field('post_name', $post_id);
            if (strpos($slug, 'swpanel-ai') !== false) {
                wp_delete_post($post_id, true);
            }
        }
    }

    public static function saveBearerToken($post){
        try {
            update_option('swpanel_ai_license_token_entered', 1);
            $license_token = $post['swpanel_ai_license_token'];
            $license_secret = $post['swpanel_ai_license_secret'];
            $decoded = JWT::decode($license_token, new Key($license_secret, 'HS256'));
            update_option('swpanel_ai_license_token', $decoded->token);
            update_option('swpanel_ai_url', $decoded->url);
            delete_transient('swpanel_ai_license_status');
        } catch (\Exception $e) {
            delete_option('swpanel_ai_license_token');
            delete_option('swpanel_ai_url');
            delete_transient('swpanel_ai_license_status');
        }
    }

    public static function createPost($title, $content, $image_url) {
        $post_id = wp_insert_post([
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => 'publish',
            'post_type'    => 'post',
        ]);
        if (!$post_id) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__('Unable to create post. Please try again.', 'swpanel-ai'));
        }
        if ( ! function_exists('media_sideload_image') ) {
            require_once( ABSPATH . 'wp-admin/includes/media.php' );
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
        }
        $tmp_file = download_url($image_url);
        if (is_wp_error($tmp_file)) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__('Unable to download image. Please try again.', 'swpanel-ai'));
        }
        $file_array = [
            'name'     => 'swpanel-ai-post-image.jpg',
            'tmp_name' => $tmp_file,
        ];
        $attachment_id = media_handle_sideload($file_array, 0);
        if (!$attachment_id) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__('Unable to download image. Please try again.', 'swpanel-ai'));
        }
        set_post_thumbnail($post_id, $attachment_id);
        return $post_id;
    }
}
