<?php
/**
 * ------------------------------------------------------------------
 * Customizer Field Exporter & Preset Importer
 * ------------------------------------------------------------------
 */

// ১. Export Customizer Fields Schema to JSON
function starterblog_export_customizer_fields_json()
{
    if (isset($_GET['starterblog_action']) && 'export_fields_schema' === $_GET['starterblog_action']) {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized Access');
        }

        // Fetch all registered fields from theme config
        $config_fields = class_exists('StarterBlog_Customizer') ? StarterBlog_Customizer::get_config() : array();

        $fields_schema = array();
        $current_mods = get_theme_mods();

        foreach ($config_fields as $key => $field) {
            // Strip 'setting|' prefix if exists
            $setting_id = str_replace(array('setting|', 'section|', 'panel|'), '', $key);

            // Only export settings/controls
            if (isset($field['type']) && !in_array($field['type'], array('panel', 'section'), true)) {
                $fields_schema[$setting_id] = array(
                    'type' => isset($field['type']) ? $field['type'] : 'text',
                    'label' => isset($field['label']) ? $field['label'] : (isset($field['title']) ? $field['title'] : ''),
                    'default' => isset($field['default']) ? $field['default'] : '',
                    'current_value' => isset($current_mods[$setting_id]) ? $current_mods[$setting_id] : (isset($field['default']) ? $field['default'] : ''),
                    'choices' => isset($field['choices']) ? $field['choices'] : array(),
                );
            }
        }

        $export_data = array(
            'theme' => 'starter-blog',
            'version' => '1.0.0',
            'fields' => $fields_schema,
        );

        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename=starterblog-fields-schema.json');
        echo wp_json_encode($export_data, JSON_PRETTY_PRINT);
        exit;
    }
}
add_action('admin_init', 'starterblog_export_customizer_fields_json');


// ২. Import Customizer Preset JSON
// Flexible Import Customizer Preset JSON
function starterblog_import_customizer_preset_json()
{
    if (isset($_POST['starterblog_import_preset_nonce']) && wp_verify_nonce($_POST['starterblog_import_preset_nonce'], 'starterblog_import_preset')) {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized Access');
        }

        if (isset($_FILES['preset_json_file']['tmp_name']) && !empty($_FILES['preset_json_file']['tmp_name'])) {
            $json_content = file_get_contents($_FILES['preset_json_file']['tmp_name']);
            $data = json_decode($json_content, true);

            if (is_array($data)) {
                // Determine if 'preset_mods', 'fields', or flat JSON array
                if (isset($data['preset_mods']) && is_array($data['preset_mods'])) {
                    $mods_to_import = $data['preset_mods'];
                } elseif (isset($data['fields']) && is_array($data['fields'])) {
                    $mods_to_import = array();
                    foreach ($data['fields'] as $key => $meta) {
                        if (isset($meta['current_value'])) {
                            $mods_to_import[$key] = $meta['current_value'];
                        }
                    }
                } else {
                    // Direct flat array
                    unset($data['theme'], $data['version']);
                    $mods_to_import = $data;
                }

                // Save all theme mods
                foreach ($mods_to_import as $mod_key => $mod_value) {
                    set_theme_mod($mod_key, $mod_value);
                }

                // Clear theme auto CSS cache if applicable
                remove_theme_mod('starterblog__css');

                wp_redirect(admin_url('themes.php?page=starterblog&preset_imported=1'));
                exit;
            }
        }
    }
}
add_action('admin_init', 'starterblog_import_customizer_preset_json');


// ৩. Admin UI Buttons in Theme Options Page
function starterblog_render_preset_tools_ui()
{
    ?>
    <div class="cd-box"
        style="margin-top: 20px; padding: 20px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
        <h2>🛠️ Customizer Preset & Schema Generator</h2>
        <p>Export all registered customizer fields to JSON schema or import a creative JSON preset file.</p>

        <div style="display: flex; gap: 20px; align-items: center; margin-top: 15px;">
            <!-- Export Button -->
            <div>
                <a href="<?php echo esc_url(admin_url('admin.php?page=starterblog&starterblog_action=export_fields_schema')); ?>"
                    class="button button-primary">
                    📥 Export All Customizer Fields (JSON)
                </a>
            </div>

            <!-- Import Form -->
            <form method="post" enctype="multipart/form-data" style="display: flex; gap: 10px; align-items: center;">
                <?php wp_nonce_field('starterblog_import_preset', 'starterblog_import_preset_nonce'); ?>
                <input type="file" name="preset_json_file" accept=".json" required>
                <button type="submit" class="button button-secondary">📤 Import Preset JSON</button>
            </form>
        </div>

        <?php if (isset($_GET['preset_imported'])): ?>
            <div style="margin-top: 15px; color: green; font-weight: bold;">
                ✅ Preset Settings Imported Successfully!
            </div>
        <?php endif; ?>
    </div>
    <?php
}
add_action('starterblog/dashboard/main', 'starterblog_render_preset_tools_ui', 1);