<?php
/**
 * REST API Class
 *
 * Provides REST API endpoints for field copy/paste operations
 *
 * @package CSCF_ACF
 */

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

/**
 * ACF_Copy_Addon_Rest_API Class
 */
class CSCF_ACF_Rest_API
{

    /**
     * API namespace
     *
     * @var string
     */
    private $namespace = 'cscf-acf/v1';

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

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

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

        add_action('rest_api_init', array($this, 'register_routes'));
    }

    /**
     * Register REST API routes
     */
    public function register_routes()
    {
        // Copy field endpoint
        register_rest_route(
            $this->namespace,
            '/copy',
            array(
                'methods' => 'POST',
                'callback' => array($this, 'copy_field'),
                'permission_callback' => array($this, 'check_permissions'),
                'args' => array(
                    'field_key' => array(
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                        'validate_callback' => function ($param) {
                            return !empty($param);
                        },
                    ),
                ),
            )
        );

        // Paste field endpoint
        register_rest_route(
            $this->namespace,
            '/paste',
            array(
                'methods' => 'POST',
                'callback' => array($this, 'paste_field'),
                'permission_callback' => array($this, 'check_permissions'),
                'args' => array(
                    'field_data' => array(
                        'required' => true,
                        'type' => 'string',
                    ),
                    'group_key' => array(
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                    'after_field_key' => array(
                        'required' => false,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                        'default' => '',
                    ),
                ),
            )
        );
    }

    /**
     * Check user permissions
     *
     * @return bool
     */
    public function check_permissions()
    {
        return current_user_can('manage_options');
    }

    /**
     * Copy field endpoint callback
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function copy_field($request)
    {
        $field_key = $request->get_param('field_key');

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

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

        // Serialize field
        $encoded_data = $this->serializer->serialize_field($field);

        if (empty($encoded_data)) {
            return new WP_REST_Response(
                array('message' => __('Failed to serialize field', 'cross-site-copy-field-for-acf')),
                500
            );
        }

        return new WP_REST_Response(
            array(
                'success' => true,
                'data' => $encoded_data,
            ),
            200
        );
    }

    /**
     * Paste field endpoint callback
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function paste_field($request)
    {
        $encoded_data = $request->get_param('field_data');
        $group_key = $request->get_param('group_key');
        $after_field_key = $request->get_param('after_field_key');

        // Decode field data
        $field_data = $this->importer->decode_field_data($encoded_data);

        if (!$field_data) {
            return new WP_REST_Response(
                array('message' => __('Failed to decode field data', 'cross-site-copy-field-for-acf')),
                400
            );
        }

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

        if (is_wp_error($validation)) {
            return new WP_REST_Response(
                array('message' => $validation->get_error_message()),
                400
            );
        }

        // Normalize field
        $normalized_field = $this->importer->normalize_field($field_data, $group_key);

        // Insert field
        $result = $this->importer->insert_field_after($group_key, $after_field_key, $normalized_field);

        if (is_wp_error($result)) {
            return new WP_REST_Response(
                array('message' => $result->get_error_message()),
                500
            );
        }

        return new WP_REST_Response(
            array(
                'success' => true,
                'message' => __('Field pasted successfully', 'cross-site-copy-field-for-acf'),
                'field' => $normalized_field,
            ),
            200
        );
    }
}
