<?php

declare(strict_types=1);

namespace WPStack\Sandbox\WordPress;

use WPStack\Sandbox\Infrastructure\SessionRepository;

final class Installer
{
    public static function activate(bool $networkWide = false): void
    {
        if (!is_multisite()) {
            wp_die(esc_html__('WPStack Sandbox Manager requires WordPress Multisite.', 'wpstack-sandbox'));
        }

        (new SessionRepository())->install();

        switch_to_blog(get_main_site_id());
        self::ensureLandingPage();
        restore_current_blog();

        update_network_option(get_current_network_id(), 'wpstack_sandbox_version', WPSTACK_SANDBOX_VERSION);
    }

    public static function maybeUpgrade(): void
    {
        $networkId = get_current_network_id();
        $installed = (string) get_network_option(
            $networkId,
            'wpstack_sandbox_version',
            ''
        );
        if ($installed === WPSTACK_SANDBOX_VERSION) {
            return;
        }

        (new SessionRepository())->install();

        update_network_option($networkId, 'wpstack_sandbox_version', WPSTACK_SANDBOX_VERSION);
    }

    public static function deactivate(): void
    {
        wp_clear_scheduled_hook('wpstack_demo_cleanup');
    }

    private static function ensureLandingPage(): void
    {
        $pageId = (int) get_option('wpstack_demo_page_id', 0);
        if ($pageId > 0 && get_post($pageId)) {
            return;
        }

        $pageId = wp_insert_post(
            [
                'post_title' => 'WPStack Plugin Demos',
                'post_name' => 'plugin-demos',
                'post_content' => '[wpstack_demo_board]',
                'post_status' => 'publish',
                'post_type' => 'page',
                'comment_status' => 'closed',
            ],
            true
        );

        if (!is_wp_error($pageId)) {
            update_option('wpstack_demo_page_id', (int) $pageId);
            update_option('show_on_front', 'page');
            update_option('page_on_front', (int) $pageId);
            update_option('blog_public', 0);
        }
    }
}
