<?php namespace Tussendoor\Reloadify\Http\Endpoints;

use ReloadifyScoped\Illuminate\Database\Eloquent\ModelNotFoundException;
use Tussendoor\Reloadify\Concerns\Http\HasAuthentication;
use Tussendoor\Reloadify\Exceptions\FilterException;
use Tussendoor\Reloadify\Http\Filters\AbandonedCartFilter;
use Tussendoor\Reloadify\Models\AbandonedCart\AbandonedCart;
use WP_Error;
use WP_REST_Request;

class AbandonedCartEndpoint
{

    use HasAuthentication;

    /**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wc/v3';

    /**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'reloadify/shopping_cart';

    /**
	 * Register the routes for this class
	 *
	 * @return void
	 */
	public function register_routes()
	{

        /**
         * To retrieve all carts
         * @see /wp-json/wc/v3/reloadify/shopping_carts
         */
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . 's',
			[
                'methods' => \WP_REST_Server::READABLE,
				'callback' => [$this, 'returnAbandonedCarts'],
                'permission_callback'  => [$this, 'checkPermissions'],
            ]
		);

        /**
         * To retrieve a specific cart
         * @see /wp-json/wc/v3/reloadify/shopping_cart/<id>
         */
        register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)',
			[
                'methods' => \WP_REST_Server::READABLE,
				'callback' => [$this, 'getAbandonedCartItem'],
                'permission_callback'  => [$this, 'checkPermissions'],
            ]
		);
	}

    /**
	 * When no search query was added to the url we return all the saved abandoned carts
	 *
	 * @param  \WP_REST_Request $request
	 * @return \WP_Error|array
	 */
	public function returnAbandonedCarts(WP_REST_Request $request)
    {
        try {
            $filter = new AbandonedCartFilter($request);
            $carts = AbandonedCart::filter($filter)->with('meta')->get();
        } catch (FilterException $e) {
            return new WP_Error('filter_exception', $e->getMessage(), ['status' => $e->getCode()]);
        }

        return $carts->toArray();
	}

	/**
	 * When a specific abandoned cart ID is requested we search and return this cart
	 *
	 * @example /wp-json/wc/v3/reloadify/shopping_cart/2
	 *
	 * @param  \WP_REST_Request $request
	 * @return \WP_Error|array
	 */
	public function getAbandonedCartItem(WP_REST_Request $request)
    {

        $cart_id = (int) $request->get_param('id');

        try {
            $cart = AbandonedCart::findOrFail($cart_id);
        } catch (ModelNotFoundException $th) {
            return new WP_Error('search_exception', 'No abandoned cart found based on this ID!', ['status' => 404]);
        }

		return $cart->toArray();
	}

}
