<?php
/**
 * API admin settings class.
 *
 * @package SaveToWishlist\Classes\API
 * @since 1.0.0
 */
namespace SaveToWishlist\Classes\API;

use SaveToWishlist\Abstracts\Singleton;

/**
 * Class API Admin Settings
 *
 * This class creates an API for the plugin.
 */
class API_Admin_Settings extends Singleton {
    use \SaveToWishlist\Traits\API_Permissions;

    /**
     * The API namespace.
     *
     * @since 1.0.0
     * @access private
     * @var string
     */
    private $api_namespace = 'saveto-wishlist/v1';

    /**
     * Base route.
     *
     * @since 1.0.0
     * @access private
     * @var string
     */
    private $base = 'admin/settings';

    /**
     * Run the application.
     *
     * @since 1.0.0
     * @access public
     */
    public function run() {
        // Register the API.
        add_action( 'rest_api_init', array( $this, 'register_api' ) );
    }

    /**
     * Register the API.
     */
    public function register_api() {

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base . '/save',
            array(
                array(
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'save_registered_settings' ),
                ),
            )
        );

        \register_rest_route(
            $this->api_namespace,
            '/' . $this->base . '/action',
            array(
                array(
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'permission_callback' => array( $this, 'check_admin_permission' ),
                    'callback'            => array( $this, 'trigger_action' ),
                ),
            )
        );
    }

    /*
    |--------------------------------------------------------------------------
    | REST API callback methods.
    |--------------------------------------------------------------------------
     */

    /**
     * Save registered settings.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function save_registered_settings( $request ) {
        $params            = $request->get_params();
        $settings_messages = array(
            'status'  => 'success',
            'message' => esc_html__( 'Settings saved successfully.', 'saveto-wishlist-lite-for-woocommerce' ),
        );
        if ( ! empty( $params ) ) {
            $options = array();
            foreach ( $params as $param ) {
                if ( is_array( $param ) && isset( $param['key'] ) ) {
                    $value       = isset( $param['value'] ) ? $param['value'] : '';
                    $final_value = $value;

                    if ( ! is_array( $value ) ) {
                        // Validate if value is true or false.
                        if ( 'true' === trim( $value ) ) {
                            $final_value = 'yes';
                        } elseif ( 'false' === trim( $value ) ) {
                            $final_value = 'no';
                        }
                    }

                    $options[ $param['key'] ] = $final_value;
                }
            }

            if ( ! empty( $options['action'] ) ) {
                // trigger the custom group save action.
                $settings_messages = apply_filters( 'stwlite_group_settings_' . $options['action'], $options );
            } else {
                foreach ( $options as $option_name => $option_value ) {
                    $setting_value = $option_value;
                    $arr_value     = json_decode( $setting_value, true );
                    if ( is_array( $arr_value ) ) {
                        $setting_value = $arr_value;
                    }

                    // Update or create.
                    update_option( $option_name, $setting_value, 'no' );
                }
            }
        }

        $response = $settings_messages;

        return rest_ensure_response( $response );
    }

    /**
     * Trigger custom action.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @since  1.0.0
     * @access public
     *
     * @return WP_REST_Response
     */
    public function trigger_action( $request ) {
        $params            = $request->get_params();
        $settings_messages = array(
            'status'  => 'success',
            'message' => esc_html__( 'Action triggered successfully.', 'saveto-wishlist-lite-for-woocommerce' ),
        );

        if ( ! empty( $params ) && ! empty( $params['action'] ) ) {
            // trigger the custom group save action.
            $settings_messages = apply_filters( 'stwlite_trigger_' . $params['action'], $params );
        }

        $response = array(
            'status'  => $settings_messages['status'],
            'message' => $settings_messages['message'],
        );

        // Check if there is a redirect.
        if ( ! empty( $settings_messages['redirect'] ) ) {
            $response['redirect'] = $settings_messages['redirect'];
        }

        return rest_ensure_response( $response );
    }
}
