<?php
/**
 * Admin UI Integration Class
 *
 * Handles admin interface integration with ACF field group editor
 *
 * @package CSCF_ACF
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * CSCF_ACF_Admin_UI Class
 */
class CSCF_ACF_Admin_UI
{

    /**
     * Field Serializer instance
     *
     * @var CSCF_ACF_Field_Serializer
     */
    private $serializer;

    /**
     * Field Importer instance
     *
     * @var CSCF_ACF_Field_Importer
     */
    private $importer;

    /**
     * Initialize the admin UI
     */
    public function init()
    {
        $this->serializer = new CSCF_ACF_Field_Serializer();
        $this->importer = new CSCF_ACF_Field_Importer();

        // Enqueue assets on ACF field group edit screen
        add_action('acf/field_group/admin_enqueue_scripts', array($this, 'enqueue_assets'));

        // Add custom field actions via JavaScript hooks
        add_action('acf/field_group/admin_footer', array($this, 'add_field_action_templates'));

        // AJAX handlers
        add_action('wp_ajax_cscf_acf_get_field', array($this, 'ajax_get_field'));
        add_action('wp_ajax_cscf_acf_paste_field', array($this, 'ajax_paste_field'));
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_assets()
    {
        // Enqueue popup JavaScript
        wp_enqueue_script(
            'cscf-acf-popup',
            CSCF_ACF_PLUGIN_URL . 'assets/js/field-json-popup.js',
            array('jquery'),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/js/field-json-popup.js'),
            true
        );

        // Enqueue main JavaScript
        wp_enqueue_script(
            'cscf-acf-admin',
            CSCF_ACF_PLUGIN_URL . 'assets/js/admin-field-actions.js',
            array('jquery', 'acf-input', 'cscf-acf-popup'),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/js/admin-field-actions.js'),
            true
        );

        // Localize script with AJAX URL and nonce
        wp_localize_script(
            'cscf-acf-admin',
            'cscfAcf',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('cscf_acf_nonce'),
                'strings' => array(
                    'copySuccess' => __('Field copied to clipboard!', 'cross-site-copy-field-for-acf'),
                    'copyError' => __('Failed to copy field. Please try again.', 'cross-site-copy-field-for-acf'),
                    'pasteSuccess' => __('Field pasted successfully!', 'cross-site-copy-field-for-acf'),
                    'pasteError' => __('Failed to paste field. Please check your clipboard data.', 'cross-site-copy-field-for-acf'),
                    'noClipboard' => __('Clipboard API not available. Please use HTTPS or localhost.', 'cross-site-copy-field-for-acf'),
                    'invalidData' => __('Invalid field data in clipboard.', 'cross-site-copy-field-for-acf'),
                ),
            )
        );

        // Enqueue variables CSS FIRST (all other CSS files depend on this)
        wp_enqueue_style(
            'cscf-acf-variables',
            CSCF_ACF_PLUGIN_URL . 'assets/css/variables.css',
            array(),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/css/variables.css')
        );

        // Enqueue popup CSS
        wp_enqueue_style(
            'cscf-acf-popup',
            CSCF_ACF_PLUGIN_URL . 'assets/css/json-popup.css',
            array('cscf-acf-variables'),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/css/json-popup.css')
        );

        // Enqueue main CSS
        wp_enqueue_style(
            'cscf-acf-admin',
            CSCF_ACF_PLUGIN_URL . 'assets/css/admin-styles.css',
            array('acf-input', 'cscf-acf-variables'),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/css/admin-styles.css')
        );

        // Enqueue upgrade modal CSS
        wp_enqueue_style(
            'cscf-acf-upgrade-modal',
            CSCF_ACF_PLUGIN_URL . 'assets/css/upgrade-modal.css',
            array('cscf-acf-variables'),
            filemtime(CSCF_ACF_PLUGIN_DIR . 'assets/css/upgrade-modal.css')
        );
    }

    /**
     * Add field action button templates
     */
    public function add_field_action_templates()
    {
        ?>
        <script type="text/html" id="tmpl-acf-copy-field-actions">
                                                                                                                   <a class="acf-icon acf-icon-copy acf-copy-field-btn" 
                                                                                                                       href="#" 
                                                                                                                       title="<?php esc_attr_e('Copy Field', 'cross-site-copy-field-for-acf'); ?>"
                                                                                                                                                                                                                                                                                                                                                       data-event="copy-field">
                                                                                                                                                                                                                                                                                                                                                        <i class="acf-icon -duplicate"></i>
                                                                                                                                                                                                                                                                                                                                                    </a>
                                                                                                                   <a class="acf-icon acf-icon-paste acf-copy-paste-field-btn" 
                                                                                                                       href="#" 
                                                                                                                       title="<?php esc_attr_e('Paste Field Below', 'cross-site-copy-field-for-acf'); ?>"
                                                                                                                                                                                                                                                                                                                                                       data-event="paste-field">
                                                                                                                                                                                                                                                                                                                                                        <i class="acf-icon -plus"></i>
                                                                                                                                                                                                                                                                                                                                                    </a>
                                                                                                                                                                                                                                                                                                                                                </script>
        <?php
    }

    /**
     * AJAX handler: Get field data for copying
     */
    public function ajax_get_field()
    {
        // Verify nonce
        check_ajax_referer('cscf_acf_nonce', 'nonce');

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'cross-site-copy-field-for-acf')));
        }

        // Get field key
        $field_key = isset($_POST['field_key']) ? sanitize_text_field(wp_unslash($_POST['field_key'])) : '';

        if (empty($field_key)) {
            wp_send_json_error(array('message' => __('Field key is required', 'cross-site-copy-field-for-acf')));
        }

        // Get field data
        $field = $this->serializer->get_field_by_key($field_key);

        if (!$field) {
            wp_send_json_error(array('message' => __('Field not found', 'cross-site-copy-field-for-acf')));
        }

        // Check license for field type
        $license = new CSCF_ACF_License();
        if (!$license->is_field_type_allowed($field['type'])) {
            $field_label = $license->get_field_type_label($field['type']);
            wp_send_json_error(array(
                'message' => sprintf(
                    /* translators: 1: Field type label, 2: Upgrade URL */
                    __('The "%1$s" field type requires Pro version. <a href="%2$s" target="_blank" style="color: #2271b1; text-decoration: underline;">Upgrade Now →</a>', 'cross-site-copy-field-for-acf'),
                    $field_label,
                    $license->get_upgrade_url()
                ),
                'requires_pro' => true,
                'field_type' => $field['type'],
                'upgrade_url' => $license->get_upgrade_url(),
            ));
        }

        // Return raw field array for JSON popup display
        wp_send_json_success(array('field' => $field));
    }

    /**
     * Handle AJAX request to paste field
     */
    public function ajax_paste_field()
    {
        try {
            check_ajax_referer('cscf_acf_nonce', 'nonce');

            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Unauthorized', 'cross-site-copy-field-for-acf')));
            }

            // Get data with proper unslashing and sanitization
            // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Field data is sanitized recursively using sanitize_field_data() immediately after
            $raw_field_data = isset($_POST['field_data']) ? wp_unslash($_POST['field_data']) : array();
            // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

            // Sanitize field data structure
            $field_data = $this->sanitize_field_data($raw_field_data);

            $group_key = isset($_POST['group_key']) ? sanitize_text_field(wp_unslash($_POST['group_key'])) : '';
            $parent_field_key = isset($_POST['parent_field_key']) ? sanitize_text_field(wp_unslash($_POST['parent_field_key'])) : '';

            if (empty($field_data) || empty($group_key)) {
                wp_send_json_error(array('message' => __('Missing required data', 'cross-site-copy-field-for-acf')));
            }

            // If group_key starts with 'post_', convert post ID to actual group key
            if (strpos($group_key, 'post_') === 0) {
                $post_id = intval(str_replace('post_', '', $group_key));
                $field_group = acf_get_field_group($post_id);

                if ($field_group && isset($field_group['key'])) {
                    $group_key = $field_group['key'];
                } else {
                    wp_send_json_error(array(
                        'message' => sprintf(
                            /* translators: %d: Post ID number */
                            __('Field group not found for post ID: %d', 'cross-site-copy-field-for-acf'),
                            $post_id
                        )
                    ));
                }
            }

            // Validate field data
            $validation = $this->importer->validate_field_data($field_data);

            if (is_wp_error($validation)) {
                wp_send_json_error(array('message' => $validation->get_error_message()));
            }

            // Check license for field type being pasted
            $license = new CSCF_ACF_License();
            $field_type = isset($field_data['type']) ? $field_data['type'] : '';

            if (!empty($field_type) && !$license->is_field_type_allowed($field_type)) {
                $field_label = $license->get_field_type_label($field_type);
                wp_send_json_error(array(
                    'message' => sprintf(
                        /* translators: 1: Field type label, 2: Upgrade URL */
                        __('The "%1$s" field type requires Pro version. <a href="%2$s" target="_blank" style="color: #2271b1; text-decoration: underline;">Upgrade Now</a>', 'cross-site-copy-field-for-acf'),
                        $field_label,
                        $license->get_upgrade_url()
                    ),
                    'requires_pro' => true,
                    'field_type' => $field_type,
                    'upgrade_url' => $license->get_upgrade_url(),
                ));
            }

            // Normalize field (generate new key, resolve name collisions)
            $normalized_field = $this->importer->normalize_field($field_data, $group_key, $parent_field_key);

            // Save field directly to database (preserves ALL data including choices, wrapper, sub_fields)
            $result = $this->importer->import_to_group($normalized_field, $group_key, $parent_field_key);

            if (is_wp_error($result)) {
                wp_send_json_error(array('message' => $result->get_error_message()));
            }

            // Success - field saved with cache cleared, will appear after reload
            wp_send_json_success(array(
                'message' => __('Field pasted successfully! Reloading...', 'cross-site-copy-field-for-acf'),
                'reload' => true,
            ));
        } catch (Exception $e) {
            wp_send_json_error(array('message' => 'Error: ' . $e->getMessage()));
        }
    }

    /**
     * Recursively sanitize field data
     *
     * @param mixed $data Raw data
     * @return mixed Sanitized data
     */
    private function sanitize_field_data($data)
    {
        if (is_array($data)) {
            $sanitized = array();
            foreach ($data as $key => $value) {
                // Sanitize key
                $key = sanitize_text_field($key);
                // Recursively sanitize value
                $sanitized[$key] = $this->sanitize_field_data($value);
            }
            return $sanitized;
        }

        if (is_string($data)) {
            // Allow basic HTML in strings (like field instructions)
            // wp_kses_post allows safe HTML tags common in WordPress content
            return wp_kses_post($data);
        }

        // Return other types as-is (bool, int, null, etc.)
        return $data;
    }
}
