<?php

namespace GriffinForms\Admin\Ajax;

class FormTheme extends \GriffinForms\Admin\Ajax\Single
{
    public function __construct()
    {
        parent::__construct();
        add_action('wp_ajax_exportTheme', array($this, 'exportTheme'));
    }

    /**
     * Exports theme as JSON file
     *
     * Validates the request, loads theme data using FormTheme Item class
     * (which properly decodes all properties), and returns JSON formatted
     * theme data ready for download.
     *
     * @return void
     */
    public function exportTheme()
    {
        // Ensure required data is present
        $this->checkPostData(['item_id']);

        // Sanitize input
        $item_id = absint(wp_unslash($_POST['item_id']));

        // Verify nonce
        $this->checkNonce('export_theme');

        // Load theme data using FormTheme Item class to get properly decoded values
        $theme_item = new \GriffinForms\Items\FormTheme();
        $theme_item->loadItem($item_id);

        // Check if theme was loaded successfully using getProp for protected property
        if (!$theme_item->getProp('id')) {
            $this->log->add(
                'warning',
                'formtheme',
                $item_id,
                get_current_user_id(),
                'Export failed: theme not found',
                'theme_export'
            );
            $this->returnError(__('Theme not found.', 'griffinforms-form-builder'));
        }

        // Helper function to safely extract style property using getProp
        $get_style = function($property) use ($theme_item) {
            $value = $theme_item->getProp($property);

            // If it's a string (JSON), decode it
            if (is_string($value)) {
                $decoded = json_decode($value, true);
                return is_array($decoded) ? $decoded : array();
            }

            // If it's already an array, return it
            return is_array($value) ? $value : array();
        };

        $style_keys = \GriffinForms\Items\FormTheme::getStylePropertyKeys();
        $styles = array();

        foreach ($style_keys as $style_key) {
            $styles[$style_key] = $get_style($style_key);
        }

        // Prepare export data with all style properties using getProp
        $export_data = array(
            'schema_version' => \GriffinForms\Items\FormTheme::THEME_SCHEMA_VERSION,
            'generated_at'   => current_time('mysql', true),
            'theme_name'     => $theme_item->getProp('name'),
            'theme_heading'  => $theme_item->getProp('heading') ?? '',
            'theme_description' => $theme_item->getProp('description') ?? '',
            'theme_category' => $theme_item->getProp('category') ?? 'default',
            'styles'         => $styles
        );

        // Set successful response
        $this->response['success'] = true;
        $this->response['msg']     = __('Theme exported successfully.', 'griffinforms-form-builder');
        $this->response['data']    = $export_data;
        $this->response['filename'] = sanitize_file_name($theme_item->getProp('name') . '.json');

        echo wp_json_encode($this->response);
        $this->log->add(
            'info',
            'formtheme',
            $item_id,
            get_current_user_id(),
            sprintf('Exported theme "%s"', $theme_item->getProp('name')),
            'theme_export'
        );
        wp_die();
    }
}
