<?php
namespace Adforest\SetupWizard;

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

// Register AJAX handlers if not already
if ( ! has_action( 'wp_ajax_adforest_import_demo_step' ) ) {
    add_action( 'wp_ajax_adforest_import_demo_step', __NAMESPACE__ . '\\adforest_import_demo_step' );
}
if ( ! has_action( 'wp_ajax_adforest_reset_demo' ) ) {
    add_action( 'wp_ajax_adforest_reset_demo',      __NAMESPACE__ . '\\adforest_reset_demo' );
}

/**
 * Handles individual demo import steps via POST.
 */
function adforest_import_demo_step() {
    @set_time_limit(0);
    @ini_set('memory_limit','512M');

    $nonce     = sanitize_text_field(wp_unslash($_POST['nonce']      ?? ''));
    $demo      = sanitize_file_name(wp_unslash($_POST['demo']       ?? ''));
    $part      = sanitize_key(wp_unslash($_POST['part']       ?? ''));
    $mode      = sanitize_key(wp_unslash($_POST['import_mode'] ?? 'new'));
    $mark_done = ! empty($_POST['mark_done']);

    if (!wp_verify_nonce($nonce,'adforest_wizard_nonce') || !current_user_can('manage_options')) {
        wp_send_json_error(['message'=>__('Permission denied','adforest')],403);
    }

    $demo_dir = trailingslashit(__DIR__ . '/../demo/' . $demo);
    if (empty($demo) || !is_dir($demo_dir)) {
        wp_send_json_error(['message'=>__('Invalid demo folder.','adforest')]);
    }

    // Enforce allowed parts
    $allowed = ('existing' === $mode) ? ['pages','media','new-widgets','new-options'] : ['content','widgets','options'];

    if (!in_array($part,$allowed,true)) {
        wp_send_json_error(['message'=>__('Invalid part for selected mode.','adforest')],400);
    }

    // Bootstrap importer
    if (!defined('WP_LOAD_IMPORTERS')) define('WP_LOAD_IMPORTERS',true);
    if (!class_exists('WP_Import')) {
        $paths = [
            WP_PLUGIN_DIR . '/wordpress-importer/wordpress-importer.php',
            get_stylesheet_directory() . '/inc/setup-wizard-adf/wordpress-importer/wordpress-importer.php',
            get_template_directory() . '/inc/setup-wizard-adf/wordpress-importer/wordpress-importer.php',
        ];
        foreach ($paths as $p) if (file_exists($p)) { require_once $p; break; }
    }
    require_once ABSPATH . 'wp-admin/includes/class-wp-importer.php';
    require_once ABSPATH . 'wp-admin/includes/import.php';

    static $importer;
    if (null === $importer) {
        if (class_exists('WP_Import')) {
            $importer = new \WP_Import();
            $importer->fetch_attachments = true;
        } else {
            wp_send_json_error(['message'=>__('Importer not available.','adforest')],500);
        }
    }

    ob_start();
    try {
        switch ($part) {
            case 'content':
                $file = $demo_dir.'content.xml';
                if (!file_exists($file)) throw new \Exception(__('Content XML missing.','adforest'));
                $importer->import($file);
                break;

            case 'widgets':
                $file = $demo_dir.'widgets.wie';
                if (!file_exists($file)) throw new \Exception(__('Widgets file missing.','adforest'));
                $raw = file_get_contents($file);
                $data = is_serialized($raw)?maybe_unserialize($raw):json_decode($raw,true);
                if (!is_array($data)) throw new \Exception(__('Invalid widgets data.','adforest'));
                    $sidebars = get_option( 'sidebars_widgets', [] );
                    foreach ( $data as $w ) {
                        $opt_key   = 'widget_' . $w['widget_type'];
                        $instances = get_option( $opt_key, [] );
                        $instances[ $w['widget_num'] ] = $w['settings'];
                        update_option( $opt_key, $instances );

                        $sidebar = $w['sidebar'];
                        $wid     = $w['widget_type'] . '-' . $w['widget_num'];
                        if ( ! in_array( $wid, $sidebars[ $sidebar ] ?? [], true ) ) {
                            $sidebars[ $sidebar ][] = $wid;
                        }
                    }
                    update_option( 'sidebars_widgets', $sidebars );                
                break;                
            case 'new-widgets':
                $file = $demo_dir.'new-widgets.wie';
                if (!file_exists($file)) throw new \Exception(__('Widgets file missing.','adforest'));
                $raw = file_get_contents($file);
                $data = is_serialized($raw)?maybe_unserialize($raw):json_decode($raw,true);
                if (!is_array($data)) throw new \Exception(__('Invalid widgets data.','adforest'));
                        $sidebars = get_option( 'sidebars_widgets', [] );
                        foreach ( $data as $w ) {
                            $opt_key   = 'widget_' . $w['widget_type'];
                            $instances = get_option( $opt_key, [] );
                            $instances[ $w['widget_num'] ] = $w['settings'];
                            update_option( $opt_key, $instances );

                            $sidebar = $w['sidebar'];
                            $wid     = $w['widget_type'] . '-' . $w['widget_num'];
                            if ( ! in_array( $wid, $sidebars[ $sidebar ] ?? [], true ) ) {
                                $sidebars[ $sidebar ][] = $wid;
                            }
                        }
                        update_option( 'sidebars_widgets', $sidebars );                
                break;

            case 'options':
                $file = $demo_dir.'theme-options.json';
                if (!file_exists($file)) throw new \Exception(__('Theme options missing..','adforest'));
                $opts = json_decode(file_get_contents($file),true);
                if (!is_array($opts)) throw new \Exception(__('Invalid options data.','adforest'));
                 update_option( 'adforest_theme', $opts );
                break;                
            case 'new-options':
                $file = $demo_dir.'new-theme-options.json';
                if (!file_exists($file)) throw new \Exception(__('New Theme options missing.','adforest'));
                $opts = json_decode(file_get_contents($file),true);
                if (!is_array($opts)) throw new \Exception(__('Invalid options data.','adforest'));
                 //update_option( 'new007_adforest_theme', $opts );
                break;

            case 'pages':
                $file = $demo_dir.'pages.xml';
                if (!file_exists($file)) throw new \Exception(__('Pages XML missing.','adforest'));
                $importer->import($file);
                break;

            case 'media':
                $file = $demo_dir.'media.xml';
                if (!file_exists($file)) throw new \Exception(__('Media XML missing.','adforest'));
                add_filter('wp_import_posts_pre_parse', function($posts){
                    return array_filter($posts, fn($p)=>$p['post_type']=='attachment');
                });
                $importer->import($file);
                remove_all_filters('wp_import_posts_pre_parse');
                break;

            default:
                throw new \Exception(__('Unknown part.','adforest'));
        }

        if (in_array($part,['options','new-options'],true)) {
            update_option('adforest_imported_demo',$demo);
            update_option('adforest_imported_demo_label',ucfirst($demo));
        }
    } catch (\Exception $e) {
        ob_end_clean();
        wp_send_json_error(['message'=>$e->getMessage()],500);
    }
    ob_end_clean();

    wp_send_json_success(['part'=>$part]);
}

/** Reset demo flag */
function adforest_reset_demo() {
    check_ajax_referer('adforest_wizard_nonce','nonce');
    if(!current_user_can('manage_options')) wp_send_json_error();
    delete_option('adforest_imported_demo');
    delete_option('adforest_imported_demo_label');
    wp_send_json_success();
}

if(!function_exists('is_serialized')) {
    function is_serialized($data) {
        return is_string($data) && preg_match("/^(a|O|s|i|b|d):/",trim($data));
    }
}
