<?php
namespace NeoLibraryBeta\NeoDemoContent; if (!defined("ABSPATH")) { die("neoWP direct access not allowed"); }







\NeoLibraryBeta\NeoGlobal\register_rest_endpoint("/wp-json/neo/demo-content-import", "POST", fn () => \NeoLibraryBeta\NeoGlobal\current_user_can__neo_demo_content__import(), function ($get_param) {
    
    if (\NeoLibraryBeta\NeoGlobal\site_host() === "neo-wp.com") { \NeoLibraryBeta\NeoGlobal\throw_global_exception("Should not import demo-content on prod! It will delete the demo content!"); }
    return \NeoLibraryBeta\NeoGlobal\synclock_dir(\NeoLibraryBeta\NeoGlobal\cache_path("neo-demo-content"), function () {
        $imported_items = [];
        $zip_path = \NeoLibraryBeta\NeoGlobal\cache_path("neo-demo-content") . "/import.zip";
        try {
            
            $response = \NeoLibraryBeta\NeoGlobal\curl_request("https://" . \NeoLibraryBeta\NeoGlobal\option__neo_wp_com() . "/wp-json/neo/demo-content", method: "GET", data: null, timeout: 60);
            \NeoLibraryBeta\NeoGlobal\fs_file_put_contents($zip_path, $response);
            
            global $wpdb;
            $post_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_name LIKE 'demo-%' OR post_name LIKE 'plugin-neo-%-icon'");
            foreach ($post_ids as $post_id) {
                wp_delete_post($post_id, true);
            }

            $zip = new \ZipArchive(); if ($zip->open($zip_path) !== true) { \NeoLibraryBeta\NeoGlobal\throw_global_exception("Unable to open downloaded zip"); }
            for ($i = 0, $count = $zip->numFiles; $i < $count; $i++) {
                $entry_name = $zip->getNameIndex($i);
                $content = $zip->getFromIndex($i);
                $slug = sanitize_title($entry_name);
                if (str_ends_with($entry_name, ".sql")) {
                    $lines = \NeoLibraryBeta\NeoGlobal\preg_split_better("/;\s*\n/", $content);
                    foreach ($lines as $sql) {
                        $sql = trim($sql);
                        if ($sql === "") { continue; }
                        try { $success = $wpdb->query($sql); if ($success === false) { \NeoLibraryBeta\NeoGlobal\throw_global_exception("Failed to SQL-import"); } }
                        catch (\Throwable $e) { \NeoLibraryBeta\NeoGlobal\global_log_with_module_name("neo-demo-content", "Demo content import error: " . $e->getMessage() . " for query " . $sql); }
                    }
                    $imported_items[] = ["filename" => $entry_name, "slug" => $slug];
                } else {
                    $dest_path = \NeoLibraryBeta\NeoGlobal\uploads_dir() . "/" . $entry_name; \NeoLibraryBeta\NeoGlobal\fs_file_put_contents($dest_path, $content);
                    $imported_items[] = ["filename" => $entry_name, "slug" => $slug];
                }
            }
            $zip->close();
        } finally { if (\NeoLibraryBeta\NeoGlobal\fs_file_exists($zip_path)) { \NeoLibraryBeta\NeoGlobal\fs_unlink($zip_path); } }
        return $imported_items;
    });
});


\NeoLibraryBeta\NeoGlobal\add_action_hook("neo_init", function () {
    if (\NeoLibraryBeta\NeoGlobal\is_playground()) { return; }
    $settings_render_callback = function () {
        ?><neo-setting-neo-library-beta>
            <div slot="left">
                <h3><?php \NeoLibraryBeta\NeoGlobal\echo_neo__("Import demo content", "Demo-Inhalte importieren") ?></h3>
                <p><?php \NeoLibraryBeta\NeoGlobal\echo_neo__("Import demo content from the neoWP website to this instance.", "Demo-Inhalte von der neoWP-Website in diese Instanz importieren."); ?></p>
            </div>
            <div slot="right">
                <neo-button-neo-library-beta class="neo-demo-content--button"><?php \NeoLibraryBeta\NeoGlobal\echo_neo__("Import demo content", "Demo-Inhalte importieren"); ?></neo-button-neo-library-beta>
            </div>
            <style>.neo-demo-content--results:empty { display: none; } </style>
            <div class="neo-demo-content--results"></div>
        </neo-setting-neo-library-beta>
        <script type="module">
            import { neo__ } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url() ?>/_global--translation.js";
            import { observeClick } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url() ?>/_global--observer.js";
            import { fetchEndpoint } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url(); ?>/_global--endpoint.js";
            import Swal from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url() ?>/_global-sweetalert2.js";
            observeClick(".neo-demo-content--button", async (buttonNode) => {
                if (!window.confirm(neo__("⚠️ Are you sure you want to import demo content? This will add a lot of content to your website.", "⚠️ Bist du sicher, dass du Demo-Inhalte importieren möchtest? Dadurch wird viel Inhalt zu deiner Website hinzugefügt."))) { return; }
                buttonNode.disabled = true;
                const originalHTML = buttonNode.innerHTML;
                buttonNode.innerHTML = "…";
                try {
                    const response = await fetchEndpoint("/wp-json/neo/demo-content-import", { method: "POST", suppressHttpCodeError: true } );
                    if (!response.ok) {
                        const errorText = await response.text();
                        Swal.fire({
                            icon: "error",
                            title: neo__("Error", "Fehler"),
                            text: errorText || neo__("An error occurred while importing demo content.", "Beim Importieren der Demo-Inhalte ist ein Fehler aufgetreten.")
                        });
                        return;
                    }
                    const importedItems = await response.json();
                    if (Array.isArray(importedItems) && importedItems.length > 0) {
                        let listHtml = "<ul>";
                        importedItems.forEach(item => { listHtml += "<li>" + item.filename + " (" + item.slug + ")" + "</li>"; });
                        listHtml += "</ul>";
                        document.querySelector(".neo-demo-content--results").innerHTML = listHtml;
                        Swal.fire({
                            icon: "success",
                            title: neo__("Success", "Erfolg"),
                            html: neo__("Demo content imported successfully. See list below:", "Demo-Inhalte erfolgreich importiert. Siehe Liste unten:") + listHtml
                        });
                    } else {
                        Swal.fire({
                            icon: "info",
                            title: neo__("No items imported", "Keine Einträge importiert"),
                            text: neo__("No demo content items were returned.", "Es wurden keine Demo-Inhalte zurückgegeben.")
                        });
                    }
                } catch (error) {
                    Swal.fire({
                        icon: "error",
                        title: neo__("Error", "Fehler"),
                        text: error.message || neo__("An unexpected error occurred.", "Ein unerwarteter Fehler ist aufgetreten.")
                    });
                } finally {
                    buttonNode.disabled = false;
                    buttonNode.innerHTML = originalHTML;
                }
            });
        </script>
        <?php
    };
    \NeoLibraryBeta\NeoGlobal\call_interface_func_implemented('\NeoLibraryBeta\NeoSettings\interface_add_neo_setting_20260326')("neo-demo-content", $settings_render_callback);
});


\NeoLibraryBeta\NeoGlobal\add_action_hook("wp_body_open", function () {
    if (!\NeoLibraryBeta\NeoGlobal\is_playground()) { return; }
    if (\NeoLibraryBeta\NeoGlobal\option__neo_demo_content__imported()) { return; } \NeoLibraryBeta\NeoGlobal\option__neo_demo_content__imported(true);
    ?>
    <style>
        @keyframes neo-demo-content--spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        #neo-demo-content--loading {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: #FFFFFF;
            display: flex; justify-content: center; align-items: center;
            z-index: 9999;
        }
        #neo-demo-content--loading { display: flex; flex-direction: column; justify-content: center; align-items: center; opacity: 0; animation: fadeIn 0.3s ease-in forwards; }
        @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } }
        .neo-demo-content--loading-spinner {
            width: 50px; height: 50px;
            border: 5px solid #E0E0E0; border-top: 5px solid #3858EA; border-radius: 50%;
            animation: neo-demo-content--spin 1s linear infinite;
        }
        #neo-demo-content--loading p {
            color: #000000;
            margin-top: 10px;
            font-weight: 400; font-family: -apple-system,BlinkMacSystemFont,sans-serif; font-size: 1.1rem
        }

        @media (prefers-color-scheme: dark) {
            #neo-demo-content--loading { background: #1E1E1E; }
            .neo-demo-content--loading-spinner { border: 5px solid #32363A; border-top: 5px solid #3858EA; }
            #neo-demo-content--loading p { color: #FFFFFF; }
        }
    </style>
    <div id="neo-demo-content--loading"><div class="neo-demo-content--loading-spinner"></div><p>Importing demo content...</p></div>
    <script type="module">
        import { fetchEndpoint } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url(); ?>/_global--endpoint.js";
        import { neoWarn } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url() ?>/_global--log.js";
        import { reloadPage } from "<?php echo \NeoLibraryBeta\NeoGlobal\plugin_url() ?>/_global-reload-page.js";
        try {

            await fetchEndpoint("/wp-json/neo/demo-content-import", { method: "POST" });

            if (((new URLSearchParams(location.search)).get("neo-demo-content--plugin") || "").startsWith("neo-")) {
                const hostname = (new URLSearchParams(location.search)).get("neo-demo-content--hostname") || <?php echo \NeoLibraryBeta\NeoGlobal\php_to_js_object(\NeoLibraryBeta\NeoGlobal\option__neo_wp_com())?>;
                let sandboxHomePageUrl = `https://${hostname}/sandbox-home-page/`;
                if (hostname === "neo.dev.neo-wp.com") { sandboxHomePageUrl += "?nocache"; }
                reloadPage("/demo-sandbox-home-page/?neo-demo-content--sandbox-home-page-url=" + encodeURIComponent(sandboxHomePageUrl));
            } else { reloadPage("/wp-admin/plugins.php"); }
        } catch (error) {
            neoWarn(error);
            alert("Error downloading demo content. " + error);
            reloadPage("/wp-admin");
        }
    </script>
    <?php
});
