<?php

class FreshopREST extends WP_REST_Controller {

    public function __construct()
    {
        $this->register_routes();
    }

    /**
     * Register the routes for the objects of the controller.
     */
    public function register_routes() {
        $version = '1';
        $namespace = 'freshop/v' . $version;

        register_rest_route( $namespace, 'content/slider', array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => [&$this, 'load_slider_ajax'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args'            => []
            )
        ) );

        register_rest_route( $namespace, 'content/site-banner', array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => [&$this, 'load_site_banner_ajax'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args'            => []
            )
        ) );

        register_rest_route( $namespace, 'content/stores', array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => [&$this, 'load_stores_ajax'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args'            => []
            )
        ) );

        register_rest_route( $namespace, 'content/homepage', array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => [&$this, 'load_homepage_ajax'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args'            => []
            )
        ) );

        register_rest_route( $namespace, 'content/gift', array(
            array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => [&$this, 'load_gift_ajax'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args'            => []
            )
        ) );
    }

    /**
     * Get a collection of items
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function get_items( $request ) {
        $items = array(); //do a query, call another class, etc
        $data = array();
        foreach( $items as $item ) {
            $itemdata = $this->prepare_item_for_response( $item, $request );
            $data[] = $this->prepare_response_for_collection( $itemdata );
        }

        return $this->send_data($data);
    }

    /**
     * Return a Soliloquy slider for a site.
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_slider_ajax(WP_REST_Request $request) {
        $store_id       = $request->get_param('store_id');
        $slider_slug    = $request->get_param('slider_slug');
        $data        = [];

        // we have no way of passing store id or group id to soliloquy slider so set a global
        global $fp_selected_store;
        $fp_selected_store['id']          = $store_id;
        $fp_selected_store['group_id']    = get_store_group($store_id);

        $data['html'] = do_shortcode(sprintf('[soliloquy slug="%s"]', $slider_slug));
        // Soliloquy not installed:
        if(stristr($data['html'], '[soliloquy')) :
            return new WP_Error( 'freshop_no_slider', 'Soliloquy not installed.', array( 'status' => 404 ) );
        endif;
        return $this->send_data((object) $data);
    }

    /**
     * Return a Site Banner for a site.
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_site_banner_ajax(WP_REST_Request $request) {
        $store_id       = $request->get_param('store_id');
        $data        = [];

        // we have no way of passing store id or group id to soliloquy slider so set a global
        global $fp_selected_store;
        $fp_selected_store['id']          = $store_id;
        $fp_selected_store['group_id']    = get_store_group($store_id);

        $data['html'] = do_shortcode(sprintf('[fc-site-banner store_id="%s"]', $store_id));

        // Soliloquy not installed:
        if(stristr($data['html'], '[fc-site-banner')) :
            return new WP_Error( 'fc-site-banner', 'Site banner not installed.', array( 'status' => 404 ) );
        endif;

        return $this->send_data($data);
    }

    /**
     * Return an array of stores
     * Will filter by group_id if passed
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_homepage_ajax(WP_REST_Request $request) {
        $store_id = $request->get_param('store_id');
        $data = [];
        $homepage = get_post_by_store_group($store_id, 'home-page');

        if ($homepage != null/* && $homepage->post_name != 'default'*/) {
            $data['url'] = get_permalink($homepage->ID);

//                $templates[] = 'single-home-page.php';
//                global $post, $disable_home_header;
//                $post = $homepage;
//                $disable_home_header = true;
//                ob_start();
//                include(locate_template($templates, false, false));
//                $data['html'] = ob_get_clean();
        }


        return $this->send_data((object) $data);
    }

    /**
     * Return an array of stores
     * Will filter by group_id if passed
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_gift_ajax(WP_REST_Request $request) {
        $store_id = $request->get_param('store_id');
        $data = [];
        $gift = get_post_by_store_group($store_id, 'gift');

        if ($gift != null){
            $data['url'] = get_permalink($gift->ID);
        }


        return $this->send_data((object) $data);
    }

    /**
     * Return an array of stores
     * Will filter by group_id if passed
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_stores_ajax(WP_REST_Request $request) {
        $data = get_stores();

        return $this->send_data($data, 0);
    }

    protected function send_data($data, $cache = 300) {
        $response = new WP_REST_Response($data, 200);
        if(!$cache) return $response;

        $response->header('Cache-Control', sprintf('public, max-age=%s', $cache));
        $response->header('Pragma', '');
        return $response;
    }

    /**
     * Get one item from the collection
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Response
     */
    public function get_item( $request ) {
        //get parameters from request
        $params = $request->get_params();
        $item = array();//do a query, call another class, etc
        $data = $this->prepare_item_for_response( $item, $request );

        //return a response or error based on some conditional
        if ( 1 == 1 ) {
            return $this->send_data($data);
        }else{
            return new WP_Error( 'code', __( 'message', 'text-domain' ) );
        }
    }

    /**
     * Create one item from the collection
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Request
     */
    public function create_item( $request ) {

        $item = $this->prepare_item_for_database( $request );

        if ( function_exists( 'slug_some_function_to_create_item')  ) {
            $data = slug_some_function_to_create_item( $item );
            if ( is_array( $data ) ) {
                return new WP_REST_Response( $data, 200 );
            }
        }

        return new WP_Error( 'cant-create', __( 'message', 'text-domain'), array( 'status' => 500 ) );
    }

    /**
     * Update one item from the collection
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Request
     */
    public function update_item( $request ) {
        $item = $this->prepare_item_for_database( $request );

        if ( function_exists( 'slug_some_function_to_update_item')  ) {
            $data = slug_some_function_to_update_item( $item );
            if ( is_array( $data ) ) {
                return new WP_REST_Response( $data, 200 );
            }
        }

        return new WP_Error( 'cant-update', __( 'message', 'text-domain'), array( 'status' => 500 ) );

    }

    /**
     * Delete one item from the collection
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|WP_REST_Request
     */
    public function delete_item( $request ) {
        $item = $this->prepare_item_for_database( $request );

        if ( function_exists( 'slug_some_function_to_delete_item')  ) {
            $deleted = slug_some_function_to_delete_item( $item );
            if (  $deleted  ) {
                return new WP_REST_Response( true, 200 );
            }
        }

        return new WP_Error( 'cant-delete', __( 'message', 'text-domain'), array( 'status' => 500 ) );
    }

    /**
     * Check if a given request has access to get items
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|bool
     */
    public function get_items_permissions_check( $request ) {
        // A non-check for basic reading.
        return true;
    }

    /**
     * Check if a given request has access to get a specific item
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|bool
     */
    public function get_item_permissions_check( $request ) {
        return $this->get_items_permissions_check( $request );
    }

    /**
     * Check if a given request has access to create items
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|bool
     */
    public function create_item_permissions_check( $request ) {
        return current_user_can( 'edit_something' );
    }

    /**
     * Check if a given request has access to update a specific item
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|bool
     */
    public function update_item_permissions_check( $request ) {
        return $this->create_item_permissions_check( $request );
    }

    /**
     * Check if a given request has access to delete a specific item
     *
     * @param WP_REST_Request $request Full data about the request.
     * @return WP_Error|bool
     */
    public function delete_item_permissions_check( $request ) {
        return $this->create_item_permissions_check( $request );
    }

    /**
     * Prepare the item for create or update operation
     *
     * @param WP_REST_Request $request Request object
     * @return WP_Error|object $prepared_item
     */
    protected function prepare_item_for_database( $request ) {
        return array();
    }

    /**
     * Prepare the item for the REST response
     *
     * @param mixed $item WordPress representation of the item.
     * @param WP_REST_Request $request Request object.
     * @return mixed
     */
    public function prepare_item_for_response( $item, $request ) {
        return array();
    }

    /**
     * Get the query params for collections
     *
     * @return array
     */
    public function get_collection_params() {
        return array(
            'page'     => array(
                'description'        => 'Current page of the collection.',
                'type'               => 'integer',
                'default'            => 1,
                'sanitize_callback'  => 'absint',
            ),
            'per_page' => array(
                'description'        => 'Maximum number of items to be returned in result set.',
                'type'               => 'integer',
                'default'            => 10,
                'sanitize_callback'  => 'absint',
            ),
            'search'   => array(
                'description'        => 'Limit results to those matching a string.',
                'type'               => 'string',
                'sanitize_callback'  => 'sanitize_text_field',
            ),
        );
    }
}