<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\Cutover;

use Help4BuilderSuite\Contracts\ModuleContract;
use Help4BuilderSuite\Support\AdminRequest;
use Help4BuilderSuite\Support\FeatureFlags;
use Help4BuilderSuite\Support\Settings;
use WP_Post;

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

final class Module implements ModuleContract
{
    private const OPTION_KEY = 'h4bs_cutover_settings';
    private const OPTION_PREV_BLOG_PUBLIC = 'h4bs_cutover_prev_blog_public';

    public function key(): string
    {
        return 'cutover';
    }

    public function boot(): void
    {
        add_action('admin_menu', [$this, 'registerAdminPage']);
        add_action('admin_post_h4bs_cutover_save', [$this, 'handleSave']);
        add_action('admin_post_h4bs_cutover_export', [$this, 'handleExport']);
        add_action('admin_post_h4bs_cutover_import', [$this, 'handleImport']);
        add_action('template_redirect', [$this, 'maybeRenderMaintenanceSplash'], 0);
    }

    public function registerAdminPage(): void
    {
        add_submenu_page(
            'h4bs-settings',
            __('Migration and Cutover', 'help4-builder-suite'),
            __('Migration and Cutover', 'help4-builder-suite'),
            'manage_options',
            'h4bs-cutover',
            [$this, 'renderAdminPage']
        );
    }

    public function renderAdminPage(): void
    {
        if (! current_user_can('manage_options')) {
            return;
        }

        $settings = $this->settings();
        $notice = AdminRequest::queryKey('h4bs_notice');
        $imported = max(0, AdminRequest::queryAbsInt('h4bs_imported'));
        $updated = max(0, AdminRequest::queryAbsInt('h4bs_updated'));
        ?>
        <div class="wrap h4bs-admin-wrap">
            <h1><?php esc_html_e('Migration and Cutover', 'help4-builder-suite'); ?></h1>
            <p><?php esc_html_e('Use this tool to export/import site structure and run a safe maintenance splash during live deployment.', 'help4-builder-suite'); ?></p>

            <?php if ($notice === 'cutover_saved') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Cutover maintenance settings saved.', 'help4-builder-suite'); ?></p></div>
            <?php elseif ($notice === 'bundle_imported') : ?>
                <?php /* translators: 1: Created item count. 2: Updated item count. */ ?>
                <div class="notice notice-success is-dismissible"><p><?php echo esc_html(sprintf(__('Migration bundle imported. Created: %1$d, Updated: %2$d.', 'help4-builder-suite'), $imported, $updated)); ?></p></div>
            <?php elseif ($notice === 'bundle_import_failed') : ?>
                <div class="notice notice-error is-dismissible"><p><?php esc_html_e('Migration bundle import failed. Verify JSON file and try again.', 'help4-builder-suite'); ?></p></div>
            <?php endif; ?>

            <div class="card" style="max-width:980px;padding:18px;margin-top:18px;">
                <h2><?php esc_html_e('1) Live Maintenance Splash', 'help4-builder-suite'); ?></h2>
                <p><?php esc_html_e('Enable this on help4wordpress.com right before deployment starts. Logged-in admins can still access wp-admin.', 'help4-builder-suite'); ?></p>

                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <?php wp_nonce_field('h4bs_cutover_save', 'h4bs_cutover_save_nonce'); ?>
                    <input type="hidden" name="action" value="h4bs_cutover_save">
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><?php esc_html_e('Enable maintenance mode', 'help4-builder-suite'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="maintenance_enabled" value="1" <?php checked($settings['maintenance_enabled'] === '1'); ?>>
                                    <?php esc_html_e('Show splash to public visitors (HTTP 503)', 'help4-builder-suite'); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="h4bs-maint-title"><?php esc_html_e('Splash headline', 'help4-builder-suite'); ?></label></th>
                            <td><input type="text" id="h4bs-maint-title" class="regular-text" name="maintenance_title" value="<?php echo esc_attr($settings['maintenance_title']); ?>"></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="h4bs-maint-message"><?php esc_html_e('Splash message', 'help4-builder-suite'); ?></label></th>
                            <td><textarea id="h4bs-maint-message" class="large-text" rows="3" name="maintenance_message"><?php echo esc_textarea($settings['maintenance_message']); ?></textarea></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="h4bs-maint-contact-url"><?php esc_html_e('Contact URL', 'help4-builder-suite'); ?></label></th>
                            <td><input type="url" id="h4bs-maint-contact-url" class="regular-text" name="maintenance_contact_url" value="<?php echo esc_attr($settings['maintenance_contact_url']); ?>"></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="h4bs-maint-contact-label"><?php esc_html_e('Contact button label', 'help4-builder-suite'); ?></label></th>
                            <td><input type="text" id="h4bs-maint-contact-label" class="regular-text" name="maintenance_contact_label" value="<?php echo esc_attr($settings['maintenance_contact_label']); ?>"></td>
                        </tr>
                    </table>
                    <?php submit_button(__('Save Maintenance Settings', 'help4-builder-suite')); ?>
                </form>
            </div>

            <div class="card" style="max-width:980px;padding:18px;margin-top:18px;">
                <h2><?php esc_html_e('2) Export Migration Bundle (source site)', 'help4-builder-suite'); ?></h2>
                <p><?php esc_html_e('Exports pages, Help4 templates, Help4 settings, and builder metadata to one JSON file.', 'help4-builder-suite'); ?></p>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <?php wp_nonce_field('h4bs_cutover_export', 'h4bs_cutover_export_nonce'); ?>
                    <input type="hidden" name="action" value="h4bs_cutover_export">
                    <?php submit_button(__('Download Migration Bundle JSON', 'help4-builder-suite'), 'secondary'); ?>
                </form>
            </div>

            <div class="card" style="max-width:980px;padding:18px;margin-top:18px;">
                <h2><?php esc_html_e('3) Import Migration Bundle (destination site)', 'help4-builder-suite'); ?></h2>
                <p><?php esc_html_e('Upload the JSON bundle exported from staging. This will upsert pages/templates and apply Help4 settings.', 'help4-builder-suite'); ?></p>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data">
                    <?php wp_nonce_field('h4bs_cutover_import', 'h4bs_cutover_import_nonce'); ?>
                    <input type="hidden" name="action" value="h4bs_cutover_import">
                    <input type="file" name="h4bs_bundle_file" accept=".json,application/json" required>
                    <?php submit_button(__('Import Migration Bundle', 'help4-builder-suite')); ?>
                </form>
            </div>
        </div>
        <?php
    }

    public function handleSave(): void
    {
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized request.', 'help4-builder-suite'));
        }
        check_admin_referer('h4bs_cutover_save', 'h4bs_cutover_save_nonce');

        $post = wp_unslash($_POST);
        $current = $this->settings();
        $next = $current;
        $next['maintenance_enabled'] = ! empty($post['maintenance_enabled']) ? '1' : '0';
        $next['maintenance_title'] = sanitize_text_field((string) ($post['maintenance_title'] ?? $current['maintenance_title']));
        $next['maintenance_message'] = sanitize_textarea_field((string) ($post['maintenance_message'] ?? $current['maintenance_message']));
        $next['maintenance_contact_url'] = esc_url_raw((string) ($post['maintenance_contact_url'] ?? $current['maintenance_contact_url']));
        $next['maintenance_contact_label'] = sanitize_text_field((string) ($post['maintenance_contact_label'] ?? $current['maintenance_contact_label']));

        if ($next['maintenance_contact_url'] === '') {
            $next['maintenance_contact_url'] = 'https://help4wordpress.com/contact';
        }
        if ($next['maintenance_contact_label'] === '') {
            $next['maintenance_contact_label'] = 'Contact Help4 WordPress';
        }

        $wasEnabled = $current['maintenance_enabled'] === '1';
        $isEnabled = $next['maintenance_enabled'] === '1';
        if (! $wasEnabled && $isEnabled) {
            update_option(self::OPTION_PREV_BLOG_PUBLIC, (string) get_option('blog_public', '1'), false);
            update_option('blog_public', '0', false);
        } elseif ($wasEnabled && ! $isEnabled) {
            $previous = (string) get_option(self::OPTION_PREV_BLOG_PUBLIC, '1');
            update_option('blog_public', $previous, false);
            delete_option(self::OPTION_PREV_BLOG_PUBLIC);
        }

        update_option(self::OPTION_KEY, $next, false);
        wp_safe_redirect(add_query_arg(['page' => 'h4bs-cutover', 'h4bs_notice' => 'cutover_saved'], admin_url('admin.php')));
        exit;
    }

    public function handleExport(): void
    {
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized request.', 'help4-builder-suite'));
        }
        check_admin_referer('h4bs_cutover_export', 'h4bs_cutover_export_nonce');

        $bundle = $this->buildMigrationBundle();
        $filename = 'help4-migration-bundle-' . gmdate('Ymd-His') . '.json';
        $payload = wp_json_encode($bundle, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        if (! is_string($payload) || $payload === '') {
            wp_die(esc_html__('Unable to generate migration bundle.', 'help4-builder-suite'));
        }

        nocache_headers();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        echo $payload; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    public function handleImport(): void
    {
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized request.', 'help4-builder-suite'));
        }
        check_admin_referer('h4bs_cutover_import', 'h4bs_cutover_import_nonce');

        $file = isset($_FILES['h4bs_bundle_file']) && is_array($_FILES['h4bs_bundle_file'])
            ? map_deep(wp_unslash($_FILES['h4bs_bundle_file']), 'sanitize_text_field')
            : [];
        $tmp = isset($file['tmp_name']) ? (string) $file['tmp_name'] : '';
        $size = isset($file['size']) ? absint($file['size']) : 0;
        if ($tmp === '' || ! is_uploaded_file($tmp) || $size <= 0 || $size > 25 * 1024 * 1024) {
            $this->redirectImportFailed();
        }

        $raw = file_get_contents($tmp);
        if (! is_string($raw) || trim($raw) === '') {
            $this->redirectImportFailed();
        }

        $bundle = json_decode($raw, true);
        if (! is_array($bundle)) {
            $this->redirectImportFailed();
        }

        try {
            $result = $this->importMigrationBundle($bundle);
        } catch (\Throwable $e) {
            $this->redirectImportFailed();
            return;
        }

        wp_safe_redirect(
            add_query_arg(
                [
                    'page' => 'h4bs-cutover',
                    'h4bs_notice' => 'bundle_imported',
                    'h4bs_imported' => (string) (int) ($result['created'] ?? 0),
                    'h4bs_updated' => (string) (int) ($result['updated'] ?? 0),
                ],
                admin_url('admin.php')
            )
        );
        exit;
    }

    public function maybeRenderMaintenanceSplash(): void
    {
        $settings = $this->settings();
        if ($settings['maintenance_enabled'] !== '1') {
            return;
        }
        if (is_admin() || wp_doing_ajax() || wp_doing_cron()) {
            return;
        }
        if (defined('REST_REQUEST') && REST_REQUEST) {
            return;
        }
        if (is_user_logged_in() && current_user_can('manage_options')) {
            return;
        }

        status_header(503);
        nocache_headers();
        header('Retry-After: 900');
        ?>
        <!doctype html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo('charset'); ?>">
            <meta name="viewport" content="width=device-width,initial-scale=1">
            <meta name="robots" content="noindex,nofollow,noarchive">
            <title><?php echo esc_html($settings['maintenance_title']); ?></title>
            <style>
                :root { color-scheme: dark; }
                * { box-sizing: border-box; }
                body {
                    margin: 0;
                    min-height: 100vh;
                    font-family: "Inter", "Segoe UI", Arial, sans-serif;
                    background: radial-gradient(circle at 20% 10%, #12314a 0%, #071321 55%, #050b14 100%);
                    color: #f4f7fb;
                    display: grid;
                    place-items: center;
                    padding: 24px;
                }
                .h4-splash {
                    width: min(760px, 100%);
                    background: rgba(11, 24, 39, 0.82);
                    border: 1px solid rgba(191, 209, 231, 0.18);
                    border-radius: 20px;
                    padding: clamp(24px, 4vw, 42px);
                    box-shadow: 0 28px 65px rgba(0, 0, 0, 0.38);
                    text-align: center;
                }
                .h4-splash h1 {
                    margin: 0 0 12px;
                    font-size: clamp(30px, 4.5vw, 52px);
                    line-height: 1.05;
                    letter-spacing: -0.02em;
                    color: #fff;
                }
                .h4-splash p {
                    margin: 0;
                    font-size: clamp(16px, 2vw, 21px);
                    line-height: 1.6;
                    color: #d8e1ec;
                }
                .h4-splash a {
                    display: inline-block;
                    margin-top: 24px;
                    padding: 12px 20px;
                    border-radius: 11px;
                    background: linear-gradient(135deg, #a5bece, #6f8797);
                    color: #fff;
                    text-decoration: none;
                    font-weight: 700;
                    letter-spacing: 0.01em;
                }
                .h4-splash small {
                    display: block;
                    margin-top: 16px;
                    opacity: 0.9;
                }
            </style>
        </head>
        <body>
            <main class="h4-splash" role="main">
                <h1><?php echo esc_html($settings['maintenance_title']); ?></h1>
                <p><?php echo esc_html($settings['maintenance_message']); ?></p>
                <a href="<?php echo esc_url($settings['maintenance_contact_url']); ?>" target="_blank" rel="noopener"><?php echo esc_html($settings['maintenance_contact_label']); ?></a>
                <small><?php echo esc_html__('Help4 WordPress', 'help4-builder-suite'); ?></small>
            </main>
        </body>
        </html>
        <?php
        exit;
    }

    /**
     * @return array{
     *   maintenance_enabled:string,
     *   maintenance_title:string,
     *   maintenance_message:string,
     *   maintenance_contact_url:string,
     *   maintenance_contact_label:string
     * }
     */
    private function settings(): array
    {
        $defaults = [
            'maintenance_enabled' => '0',
            'maintenance_title' => 'Help4 WordPress is being upgraded',
            'maintenance_message' => 'We are deploying a new Help4WordPress.com experience right now. For immediate assistance, contact us on Help4 WordPress.',
            'maintenance_contact_url' => 'https://help4wordpress.com/contact',
            'maintenance_contact_label' => 'Contact Help4 WordPress',
        ];
        $saved = get_option(self::OPTION_KEY, []);
        if (! is_array($saved)) {
            $saved = [];
        }

        foreach ($defaults as $key => $defaultValue) {
            if (! isset($saved[$key]) || ! is_string($saved[$key])) {
                $saved[$key] = $defaultValue;
            }
        }

        $saved['maintenance_enabled'] = $saved['maintenance_enabled'] === '1' ? '1' : '0';
        return $saved;
    }

    /**
     * @return array<string, mixed>
     */
    private function buildMigrationBundle(): array
    {
        $frontPageId = (int) get_option('page_on_front', 0);
        $postsPageId = (int) get_option('page_for_posts', 0);
        $frontPageSlug = $frontPageId > 0 ? (string) get_post_field('post_name', $frontPageId) : '';
        $postsPageSlug = $postsPageId > 0 ? (string) get_post_field('post_name', $postsPageId) : '';

        $bundle = [
            'meta' => [
                'tool' => 'Help4 Builder Suite',
                'version' => defined('H4BS_VERSION') ? (string) H4BS_VERSION : 'unknown',
                'generated_at_utc' => gmdate('Y-m-d H:i:s') . ' UTC',
                'source_home_url' => home_url('/'),
            ],
            'options' => [
                'blogname' => (string) get_option('blogname', ''),
                'blogdescription' => (string) get_option('blogdescription', ''),
                'permalink_structure' => (string) get_option('permalink_structure', ''),
                'show_on_front' => (string) get_option('show_on_front', 'posts'),
                'page_on_front_slug' => $frontPageSlug,
                'page_for_posts_slug' => $postsPageSlug,
            ],
            'h4bs' => [
                'feature_flags' => get_option(FeatureFlags::OPTION_KEY, []),
                'settings' => get_option(Settings::OPTION_KEY, []),
            ],
            'posts' => $this->exportPosts(),
        ];

        return $bundle;
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    private function exportPosts(): array
    {
        $query = new \WP_Query(
            [
                'post_type' => ['page', 'h4_template'],
                'post_status' => ['publish', 'draft', 'private', 'pending'],
                'posts_per_page' => -1,
                'orderby' => ['post_type' => 'ASC', 'menu_order' => 'ASC', 'ID' => 'ASC'],
                'no_found_rows' => true,
                'cache_results' => false,
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
            ]
        );

        $rows = [];
        foreach ($query->posts as $post) {
            if (! $post instanceof WP_Post) {
                continue;
            }
            $parentSlug = '';
            $parentType = '';
            if ($post->post_parent > 0) {
                $parentSlug = (string) get_post_field('post_name', $post->post_parent);
                $parentType = (string) get_post_field('post_type', $post->post_parent);
            }

            $rows[] = [
                'source_id' => (int) $post->ID,
                'post_type' => (string) $post->post_type,
                'post_name' => (string) $post->post_name,
                'post_title' => (string) $post->post_title,
                'post_status' => (string) $post->post_status,
                'post_content' => (string) $post->post_content,
                'post_excerpt' => (string) $post->post_excerpt,
                'menu_order' => (int) $post->menu_order,
                'parent_slug' => $parentSlug,
                'parent_type' => $parentType,
                'meta' => $this->exportPostMeta((int) $post->ID),
            ];
        }

        wp_reset_postdata();
        return $rows;
    }

    /**
     * @return array<string, mixed>
     */
    private function exportPostMeta(int $postId): array
    {
        $all = get_post_meta($postId);
        $meta = [];
        foreach ($all as $key => $values) {
            if (! is_string($key) || $key === '') {
                continue;
            }
            if (! str_starts_with($key, '_h4_') && $key !== '_wp_page_template') {
                continue;
            }
            if (! is_array($values) || $values === []) {
                continue;
            }
            if (count($values) === 1) {
                $meta[$key] = maybe_unserialize($values[0]);
                continue;
            }
            $meta[$key] = array_map('maybe_unserialize', $values);
        }
        return $meta;
    }

    /**
     * @param array<string, mixed> $bundle
     * @return array{created:int,updated:int}
     */
    private function importMigrationBundle(array $bundle): array
    {
        $posts = is_array($bundle['posts'] ?? null) ? $bundle['posts'] : [];
        if ($posts === []) {
            throw new \RuntimeException('Bundle is missing posts.');
        }

        $this->importHelp4Options($bundle);

        $created = 0;
        $updated = 0;
        $map = [];

        foreach ($posts as $row) {
            if (! is_array($row)) {
                continue;
            }
            $type = sanitize_key((string) ($row['post_type'] ?? ''));
            $slug = sanitize_title((string) ($row['post_name'] ?? ''));
            if (! in_array($type, ['page', 'h4_template'], true) || $slug === '') {
                continue;
            }

            $existingId = $this->findPostIdBySlugAndType($slug, $type);
            $status = sanitize_key((string) ($row['post_status'] ?? 'publish'));
            if (! in_array($status, ['publish', 'draft', 'private', 'pending'], true)) {
                $status = 'draft';
            }
            $data = [
                'post_type' => $type,
                'post_name' => $slug,
                'post_title' => wp_strip_all_tags((string) ($row['post_title'] ?? '')),
                'post_status' => $status,
                'post_content' => (string) ($row['post_content'] ?? ''),
                'post_excerpt' => (string) ($row['post_excerpt'] ?? ''),
                'menu_order' => (int) ($row['menu_order'] ?? 0),
                'post_parent' => 0,
            ];

            if ($existingId > 0) {
                $data['ID'] = $existingId;
                $postId = wp_update_post($data, true);
                if (is_wp_error($postId) || ! $postId) {
                    continue;
                }
                $updated++;
            } else {
                $postId = wp_insert_post($data, true);
                if (is_wp_error($postId) || ! $postId) {
                    continue;
                }
                $created++;
            }

            $postId = (int) $postId;
            $map[$type . ':' . $slug] = $postId;

            $meta = is_array($row['meta'] ?? null) ? $row['meta'] : [];
            foreach ($meta as $metaKey => $metaValue) {
                if (! is_string($metaKey) || $metaKey === '') {
                    continue;
                }
                if (! str_starts_with($metaKey, '_h4_') && $metaKey !== '_wp_page_template') {
                    continue;
                }
                update_post_meta($postId, $metaKey, $metaValue);
            }
        }

        foreach ($posts as $row) {
            if (! is_array($row)) {
                continue;
            }
            $type = sanitize_key((string) ($row['post_type'] ?? ''));
            $slug = sanitize_title((string) ($row['post_name'] ?? ''));
            $parentSlug = sanitize_title((string) ($row['parent_slug'] ?? ''));
            $parentType = sanitize_key((string) ($row['parent_type'] ?? $type));
            if ($slug === '' || $parentSlug === '') {
                continue;
            }
            $childId = (int) ($map[$type . ':' . $slug] ?? 0);
            $parentId = (int) ($map[$parentType . ':' . $parentSlug] ?? 0);
            if ($childId <= 0 || $parentId <= 0) {
                continue;
            }
            wp_update_post(['ID' => $childId, 'post_parent' => $parentId]);
        }

        $this->importFrontPageOptions($bundle);
        flush_rewrite_rules(false);
        wp_cache_flush();

        return ['created' => $created, 'updated' => $updated];
    }

    /**
     * @param array<string, mixed> $bundle
     */
    private function importHelp4Options(array $bundle): void
    {
        $h4 = is_array($bundle['h4bs'] ?? null) ? $bundle['h4bs'] : [];
        $flagsRaw = is_array($h4['feature_flags'] ?? null) ? $h4['feature_flags'] : [];
        $settingsRaw = is_array($h4['settings'] ?? null) ? $h4['settings'] : [];

        $flagDefaults = (new FeatureFlags())->defaults();
        $flags = [];
        foreach ($flagDefaults as $key => $default) {
            $flags[$key] = isset($flagsRaw[$key]) ? rest_sanitize_boolean($flagsRaw[$key]) : (bool) $default;
        }
        update_option(FeatureFlags::OPTION_KEY, $flags, false);

        $settingsDefaults = Settings::defaults();
        $settings = $settingsDefaults;
        foreach ($settingsDefaults as $key => $defaultValue) {
            if (! array_key_exists($key, $settingsRaw)) {
                continue;
            }
            $value = $settingsRaw[$key];
            if (is_array($defaultValue)) {
                $settings[$key] = is_array($value) ? $value : $defaultValue;
            } else {
                $settings[$key] = is_scalar($value) ? (string) $value : (string) $defaultValue;
            }
        }
        foreach (Settings::lockedEndpointDefaults() as $key => $value) {
            $settings[$key] = $value;
        }
        update_option(Settings::OPTION_KEY, $settings, false);
    }

    /**
     * @param array<string, mixed> $bundle
     */
    private function importFrontPageOptions(array $bundle): void
    {
        $options = is_array($bundle['options'] ?? null) ? $bundle['options'] : [];
        $showOnFront = sanitize_key((string) ($options['show_on_front'] ?? 'posts'));
        if (! in_array($showOnFront, ['posts', 'page'], true)) {
            $showOnFront = 'posts';
        }

        $permalinkStructure = (string) ($options['permalink_structure'] ?? '');
        if ($permalinkStructure !== '') {
            update_option('permalink_structure', $permalinkStructure, false);
        }
        if (isset($options['blogname'])) {
            update_option('blogname', sanitize_text_field((string) $options['blogname']), false);
        }
        if (isset($options['blogdescription'])) {
            update_option('blogdescription', sanitize_text_field((string) $options['blogdescription']), false);
        }

        update_option('show_on_front', $showOnFront, false);
        if ($showOnFront === 'page') {
            $frontSlug = sanitize_title((string) ($options['page_on_front_slug'] ?? ''));
            $postsSlug = sanitize_title((string) ($options['page_for_posts_slug'] ?? ''));
            if ($frontSlug !== '') {
                $frontId = $this->findPostIdBySlugAndType($frontSlug, 'page');
                if ($frontId > 0) {
                    update_option('page_on_front', $frontId, false);
                }
            }
            if ($postsSlug !== '') {
                $postsId = $this->findPostIdBySlugAndType($postsSlug, 'page');
                if ($postsId > 0) {
                    update_option('page_for_posts', $postsId, false);
                }
            }
        }
    }

    private function findPostIdBySlugAndType(string $slug, string $postType): int
    {
        $post = get_page_by_path($slug, OBJECT, $postType);
        if ($post instanceof WP_Post) {
            return (int) $post->ID;
        }
        return 0;
    }

    private function redirectImportFailed(): void
    {
        wp_safe_redirect(add_query_arg(['page' => 'h4bs-cutover', 'h4bs_notice' => 'bundle_import_failed'], admin_url('admin.php')));
        exit;
    }
}
