<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce\REST;

use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class SliderController extends WP_REST_Controller {

    /**
     * Endpoint namespace
     *
     * @var string
     */
    protected $namespace = 'app-bridge/v1/pocket-store';

    /**
     * Route name
     *
     * @var string
     */
    protected $base = 'slides';

    public const OPTION_KEY = 'pocket_store_app_customer_sliders';

    /**
     * Register all routes releated with stores
     *
     * @return void
     */
    public function register_routes() {
        register_rest_route(
            $this->namespace, '/' . $this->base, array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => '__return_true',
				),

				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'create_item_permission' ),
					'args'                => array(
						'slides' => array(
							'required'    => true,
							'type'        => 'object',
							'description' => __( 'An array of slides', 'app-bridge' ),
						),
					),
				),
            )
        );
    }

    /**
     * Get slides
     *
     * @since 1.0.0
     *
     * @param \WP_REST_Request $request
     *
     * @return WP_REST_Response
     */
    public function get_item( $request ) {
        $slides = get_option( self::OPTION_KEY, array() );

        return rest_ensure_response( $slides );
    }

    /**
     * Create item permission callback
     *
     * @since 1.0.0
     *
     * @return bool
     */
    public function create_item_permission() {
        return current_user_can( 'manage_options' );
    }

    /**
     * Create/update slides
     *
     * @since 1.0.0
     *
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response|WP_Error
     */
    public function create_item( $request ) {

        if ( empty( $request['slides'] ) ) {
            return new WP_Error( 'rest_invalid_data', __( 'Slides cannot be empty', 'app-bridge' ) );
        }

        $slides = array();

        foreach ( $request['slides'] as $slide ) {
            $image = ! empty( $slide['image'] ) ? sanitize_url( $slide['image'] ) : null;

            if ( $image ) {
                $is_clickable = ! empty( $slide['is_clickable'] ) ? wp_validate_boolean( $slide['is_clickable'] ) : false;
                $type = ! empty( $slide['type'] ) ? sanitize_text_field( $slide['type'] ) : null;
                $type_id = ! empty( $slide['type_id'] ) ? absint( $slide['type_id'] ) : 0;
                $url = ! empty( $slide['url'] ) ? sanitize_url( $slide['url'] ) : null;

                if ( $type && $type_id && 'product' !== $type && ! term_exists( $type_id, $type ) ) {
                    return new WP_Error(
                        'rest_invalid_term',
                        sprintf(
							// translators: 1: term id, 2: taxonomy.
                            __( 'Invalid term id %1$d for taxonomy %2$s', 'app-bridge' ),
                            $type_id, $type
                        )
                    );
                }

                $slides[] = array(
                    'image'        => $image,
                    'is_clickable' => $is_clickable,
                    'type'         => $type,
                    'type_id'      => $type_id,
                    'url'          => $url,
                );
            }
        }

        update_option( self::OPTION_KEY, $slides );

        return rest_ensure_response( $slides );
    }
}
