<?php
    /**
     * Endpoints for custom control
     * 
     * @package Blog Bee
     * @since 1.0.0
     */

    namespace BBE;

    use BBE\Query_Manager as Query_Manager;
    use BBE\Cache_Manager as Cache_Manager;
    use WP_REST_Response;

    if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

    if( ! class_exists( __NAMESPACE__ . '\\Extend_Api' ) ) {
        /**
         * Register api
         * 
         * @since 1.0.0
         */
        class Extend_Api {
            /**
             * Route of the api
             * 
             * @since 1.0.0
             */
            protected $route = 'blog-bee/v1/extend';

            /**
             * Method that gets called when class is instantiated
             * 
             * @since 1.0.0
             */
            public function __construct() {
                $this->init();
            }

            /**
             * Register the api when class is called
             * 
             * @since 1.0.0
             */
            public function init() {
                add_action( 'rest_api_init', function(){
                    $routes = [
                        'get_posts' =>  'POST',
                        'get_taxonomy'  =>  'POST',
                        'get_users' =>  'POST',
                    ];
                    foreach( $routes as $method => $http ) {
                        register_rest_route(
                            $this->route,
                            $method,
                            [
                                'methods' => $http,
                                'callback' =>  [ $this, $method ],
                                'permission_callback' => '__return_true'
                            ]
                        );
                    }
                } );
            }

            /**
             * Get all posts
             * 
             * @since 1.0.0
             * @param   array   $request    Array containing items from $_REQUEST superglobal
             */
            public function get_posts( $request ) {
                if( ! current_user_can( 'edit_posts' ) ) return;

                $options = [];
                $query_args = [
                    'posts_per_page'    =>  100
                ];

                if ( isset( $request[ 'query_slug' ] ) ) $query_args[ 'post_type' ] = $request[ 'query_slug' ];

                if ( isset( $request[ 's' ] ) ) $query_args[ 's' ] = $request[ 's' ];

                if ( isset( $request[ 'exclude' ] ) ) {
                    $ids = explode( ',', $request[ 'exclude' ] );
                    $query_args[ 'post__not_in' ] = $ids;
                }

                $query = Query_Manager::fine_tune_query_attrs( $query_args, true );

                if( $query->have_posts() ) {
                    while( $query->have_posts() ) {
                        $query->the_post();
                        if ( isset( $request[ 'widget' ] ) && $request[ 'widget' ] ) {
                            $options[] = [
                                'id' => get_the_ID(),
                                'text' => html_entity_decode( get_the_title() ),
                            ];
                        } else {
                            $options[] = [
                                'value' => get_the_ID(),
                                'label' => html_entity_decode( get_the_title() ),
                            ];
                        }
                    }
                    wp_reset_postdata();
                }
                return $options;
            }

            /**
             * Get all taxonomy, category or tag
             * 
             * @param array $request Array containing items from $_REQUEST superglobal
             * @since 1.0.0
             */
            public function get_taxonomy( $request ) {
                if( ! current_user_can( 'edit_posts' ) ) return;

                $options = [];
                $query_args = [
                    'orderby' => 'name', 
                    'order' => 'DESC',
                    'hide_empty' => true,
                    'number' => 6,
                    'fields'    =>  'id=>name',
                    'pad_counts'    =>  false,
                    'update_term_meta_cache' => false,
                    'hierarchical' => false,
                ];
                if ( isset( $request[ 'query_slug' ] ) ) $query_args[ 'taxonomy' ] = $request[ 'query_slug' ];

                if ( isset( $request[ 's' ] ) ) $query_args[ 'name__like' ] = $request[ 's' ];

                if ( isset( $request[ 'exclude' ] ) ) $query_args[ 'exclude' ] = $request[ 'exclude' ];
            
                $terms = get_terms( $query_args );
                if( ! empty( $terms ) && is_array( $terms ) ) {
                    foreach( $terms as $id => $label ) {
                        if ( isset( $request[ 'widget' ] ) && $request[ 'widget' ] ) {
                            $options[] = [
                                'id' => absint( $id ),
                                'text' =>  sanitize_text_field( $label )
                            ];
                        } else {
                            $options[] = [
                                'value' => absint( $id ),
                                'label' =>  sanitize_text_field( $label )
                            ];
                        }
                    }
                }
                return $options;
            }


            /**
             * get all users
             * 
             * @param array $request Array containing items from $_REQUEST superglobal
             * @since 1.0.0
             */
            public function get_users( $request ) {
                if ( ! current_user_can( 'edit_posts' ) ) return;
        
                $query_args = [
                    'number' => 6,
                    'fields'    =>  [ 'ID', 'display_name' ]
                ];

                if ( isset( $request[ 'exclude' ] ) ) {
                    $ids = explode( ',', $request[ 'exclude' ] );
                    $query_args[ 'exclude' ] = $ids;
                }
        
                if ( isset( $request[ 's' ] ) ) $query_args[ 'search' ] = '*'. $request[ 's' ] .'*';
        
                $options = [];
                $user_query = new \WP_User_Query( $query_args );
        
                if ( ! empty( $user_query->get_results() ) ) {
                    foreach ( $user_query->get_results() as $user ) {
                        if ( isset( $request[ 'widget' ] ) && $request[ 'widget' ] ) {
                            $options[] = [
                                'id' => absint( $user->ID ),
                                'text' => sanitize_text_field( $user->display_name )
                            ];
                        } else {
                            $options[] = [
                                'value' => absint( $user->ID ),
                                'label' => sanitize_text_field( $user->display_name )
                            ];
                        }
                    }
                }

                wp_reset_postdata();
                return $options;
            }
        }
        new Extend_Api();
    }