<?php
/**
 * Author: Rymera Web Co.
 *
 * @package SAAI\REST
 */

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_REST;
use SAAI\Traits\Singleton_Trait;
use WP_REST_Request;
use WP_REST_Server;

/**
 * WC_Admin class.
 *
 * @since 1.0.0
 */
class WC_Admin extends Abstract_REST {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.0
     * @var WC_Admin $instance object
     */
    protected static $instance;

    /**
     * Register the routes.
     *
     * @return void
     */
    public function register_routes() {

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/product-meta-keys",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_product_possible_meta_keys' ),
                'permission_callback' => array( $this, 'get_item_permissions_check' ),
            )
        );
    }

    /**
     * Get product possible meta keys.
     *
     * @param WP_REST_Request $request The request object.
     *
     * @return \WP_REST_Response
     */
    public function get_product_possible_meta_keys( $request ) {

        global $wpdb;

        $response = $wpdb->get_col(
            "
SELECT DISTINCT pm.meta_key
FROM wp_postmeta pm
INNER JOIN wp_posts p ON pm.post_id = p.ID
WHERE p.post_type = 'product'
ORDER BY pm.meta_key;
"
        );

        return $this->rest_response( $response, $request );
    }

    /**
     * Checks if a given request has access to get a specific item.
     *
     * @param WP_REST_Request $request Full data about the request.
     *
     * @since 1.0.0
     * @return bool True if the request has read access for the item, WP_Error object otherwise.
     */
    public function get_item_permissions_check( $request ) {

        return current_user_can( 'manage_woocommerce' );
    }

}
