<?php

declare(strict_types=1);

namespace WPStack\Sandbox\WordPress;

final class DemoSeeder
{
    /**
     * @param array<string, mixed> $product
     */
    public function seed(int $blogId, string $selectedPlugin, array $product): void
    {
        switch_to_blog($blogId);

        try {
            $this->activatePlugins($product);
            $this->restrictAdministrator();
            $this->seedPosts((string) $product['name']);
            $this->seedOptions();
            $this->seedMedia();
            update_option('wpstack_demo_selected_plugin', $selectedPlugin, false);
            update_option('blog_public', 0);
            update_option('default_ping_status', 'closed');
            update_option('default_comment_status', 'closed');
        } finally {
            restore_current_blog();
        }
    }

    /**
     * @param array<string, mixed> $product
     */
    private function activatePlugins(array $product): void
    {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        $pluginFiles = array_values(
            array_unique(
                array_merge(
                    (array) ($product['dependencies'] ?? []),
                    [(string) $product['file']]
                )
            )
        );

        foreach ($pluginFiles as $pluginFile) {
            if (!file_exists(WP_PLUGIN_DIR . '/' . $pluginFile)) {
                throw new \RuntimeException('Required plugin is unavailable: ' . $pluginFile);
            }

            $result = activate_plugin($pluginFile, '', false, true);
            if (is_wp_error($result)) {
                throw new \RuntimeException($result->get_error_message());
            }
        }
    }

    private function restrictAdministrator(): void
    {
        $role = get_role('administrator');
        if (!$role) {
            return;
        }

        foreach (
            [
                'activate_plugins',
                'delete_plugins',
                'edit_plugins',
                'install_plugins',
                'update_plugins',
                'delete_themes',
                'edit_themes',
                'install_themes',
                'update_themes',
                'create_users',
                'delete_users',
                'edit_users',
                'promote_users',
                'remove_users',
                'unfiltered_html',
            ] as $capability
        ) {
            $role->remove_cap($capability);
        }
    }

    private function seedPosts(string $productName): void
    {
        if (get_option('wpstack_demo_seeded')) {
            return;
        }

        $posts = [
            ['The Complete WordPress Performance Checklist', 'A practical checklist for a fast, stable WordPress site.'],
            ['How to Keep Your Media Library Healthy', 'A sample article containing media references for Mediachecker.'],
            ['Building Accessible Product Pages', 'Good alternative text helps everyone understand visual content.'],
            ['Diagnosing a Slow Admin Dashboard', 'Measure requests, plugins, database calls, and autoloaded options.'],
        ];

        foreach ($posts as [$title, $content]) {
            wp_insert_post(
                [
                    'post_title' => $title,
                    'post_content' => $content,
                    'post_status' => 'publish',
                    'post_type' => 'post',
                ]
            );
        }

        $elementorPageId = wp_insert_post(
            [
                'post_title' => $productName . ' Demo',
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'page',
            ]
        );
        if ($elementorPageId && !is_wp_error($elementorPageId)) {
            update_post_meta($elementorPageId, '_elementor_edit_mode', 'builder');
            update_post_meta($elementorPageId, '_elementor_template_type', 'wp-page');
            update_post_meta(
                $elementorPageId,
                '_elementor_data',
                wp_slash(
                    wp_json_encode(
                        [
                            [
                                'id' => 'wpsdhero',
                                'elType' => 'container',
                                'isInner' => false,
                                'settings' => [],
                                'elements' => [
                                    [
                                        'id' => 'wpsdhead',
                                        'elType' => 'widget',
                                        'widgetType' => 'heading',
                                        'settings' => [
                                            'title' => 'Explore ' . $productName,
                                            'header_size' => 'h1',
                                        ],
                                        'elements' => [],
                                    ],
                                    [
                                        'id' => 'wpsdtext',
                                        'elType' => 'widget',
                                        'widgetType' => 'text-editor',
                                        'settings' => [
                                            'editor' => '<p>This prepared page provides realistic content for exploring the demo product.</p>',
                                        ],
                                        'elements' => [],
                                    ],
                                    [
                                        'id' => 'wpsdbutton',
                                        'elType' => 'widget',
                                        'widgetType' => 'button',
                                        'settings' => [
                                            'text' => 'Explore the demo',
                                            'link' => ['url' => home_url('/')],
                                        ],
                                        'elements' => [],
                                    ],
                                ],
                            ],
                        ]
                    )
                )
            );
        }

        update_option('wpstack_demo_seeded', 1, false);
    }

    private function seedOptions(): void
    {
        $payload = str_repeat('Sandbox demo cache data. ', 180);
        update_option('wpstack_demo_catalog_cache', $payload, true);
        update_option('wpstack_demo_legacy_widget_cache', $payload . $payload, true);
        update_option('wpstack_demo_transient_migration', str_repeat($payload, 2), true);
        update_option('wpstack_demo_notice_source', 'sandbox', false);
    }

    private function seedMedia(): void
    {
        if ((int) get_option('wpstack_demo_media_seeded', 0) === 1) {
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attachmentIds = [];

        foreach (
            [
                ['performance-report.png', [38, 99, 235], 'PERFORMANCE'],
                ['media-audit.png', [249, 115, 22], 'MEDIA AUDIT'],
                ['media-audit-copy.png', [249, 115, 22], 'MEDIA AUDIT'],
                ['accessibility.png', [219, 39, 119], 'ALT TEXT'],
            ] as [$filename, $rgb, $label]
        ) {
            $bytes = $this->createPng($rgb, $label);
            $upload = wp_upload_bits($filename, null, $bytes);
            if (!empty($upload['error'])) {
                continue;
            }

            $attachmentId = wp_insert_attachment(
                [
                    'post_mime_type' => 'image/png',
                    'post_title' => pathinfo($filename, PATHINFO_FILENAME),
                    'post_status' => 'inherit',
                ],
                $upload['file']
            );

            if ($attachmentId && !is_wp_error($attachmentId)) {
                wp_update_attachment_metadata(
                    $attachmentId,
                    wp_generate_attachment_metadata($attachmentId, $upload['file'])
                );
                $attachmentIds[] = (int) $attachmentId;
            }
        }

        $posts = get_posts(['numberposts' => 2, 'post_status' => 'publish']);
        foreach ($posts as $index => $post) {
            if (isset($attachmentIds[$index])) {
                set_post_thumbnail($post->ID, $attachmentIds[$index]);
            }
        }

        update_option('wpstack_demo_media_seeded', 1, false);
    }

    /**
     * @param array{0:int,1:int,2:int} $rgb
     */
    private function createPng(array $rgb, string $label): string
    {
        if (!function_exists('imagecreatetruecolor')) {
            return (string) base64_decode(
                'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
                true
            );
        }

        $image = imagecreatetruecolor(1200, 800);
        $background = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]);
        $foreground = imagecolorallocate($image, 255, 255, 255);
        imagefilledrectangle($image, 0, 0, 1200, 800, $background);
        imagestring($image, 5, 60, 70, 'PLUGIN DEMO', $foreground);
        imagestring($image, 5, 60, 110, $label, $foreground);
        ob_start();
        imagepng($image);
        $bytes = (string) ob_get_clean();
        imagedestroy($image);

        return $bytes;
    }
}
