<?php
namespace MasterAddons\Inc\Admin\Theme_Builder\Api;

defined( 'ABSPATH' ) || exit;

class Select2_API extends Handler_API {

    public function config(){
        $this->prefix = 'select2';
    }

    /**
     * Override parent permission check to allow users with edit_posts capability
     * This is called by WordPress REST API on each request
     */
    public function check_for_permission(){
        // These endpoints feed editor-only post/page/term pickers, so require
        // the same capability needed to edit content. The REST API validates the
        // X-WP-Nonce cookie nonce before this callback runs for logged-in users.
        return current_user_can('edit_posts');
    }


    public function get_post_list(){

        if(!current_user_can('edit_posts')){
            return;
        }

        $query_args = [
            'post_type'         => 'post',
            'post_status'       => 'publish',
            'posts_per_page'    => 15,
        ];

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['post__in'] = $ids;
        }
        if(isset($this->request['s'])){
            $query_args['s'] = $this->request['s'];
        }

        $query = new \WP_Query($query_args);
        $options = [];
        if($query->have_posts()):
            while ($query->have_posts()) {
                $query->the_post();
                $options[] = [ 'id' => get_the_ID(), 'text' => get_the_title() ];
            }
        endif;

        return ['results' => $options];
        wp_reset_postdata();
    }

    public function get_page_list(){
        if(!current_user_can('edit_posts')){
            return;
           }
        $query_args = [
            'post_type'         => 'page',
            'post_status'       => 'publish',
            'posts_per_page'    => 15,
        ];

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['post__in'] = $ids;
        }
        if(isset($this->request['s'])){
            $query_args['s'] = $this->request['s'];
        }

        $query = new \WP_Query($query_args);
        $options = [];
        if($query->have_posts()):
            while ($query->have_posts()) {
                $query->the_post();
                $options[] = [ 'id' => get_the_ID(), 'text' => get_the_title() ];
            }
        endif;

        return ['results' => $options];
        wp_reset_postdata();
    }

    public function get_post_types_list() {
        // Get all public post types with objects
        $post_types = get_post_types( [ 'public' => true ], 'objects' );

        // Exclude 'post' and 'page'
        $excluded = [ 'attachment', 'e-floating-buttons', 'elementor_library' ];

        $list = [];
        foreach ( $post_types as $type => $obj ) {
            if ( ! in_array( $type, $excluded, true ) ) {
                $list[ $type ] = $obj->labels->singular_name;
            }
        }

        return ['results' => $list];
    }


    public function get_singular_list(){
        // Capability is enforced here (and by check_for_permission()); the REST
        // API has already validated the X-WP-Nonce cookie nonce at this point.
        if ( ! current_user_can('edit_posts') ) {
            return new \WP_Error( 'rest_forbidden', __( 'Insufficient permissions.', 'master-addons' ), [ 'status' => 403 ] );
        }

        $query_args = [
            'post_status'       => 'publish',
            'posts_per_page'    => 15,
            'post_type'         => 'any'
        ];

        // Filter by specific post type if provided
        if(isset($this->request['post_type']) && !empty($this->request['post_type'])){
            $post_type = sanitize_text_field($this->request['post_type']);
            // Validate that the post type exists
            if (post_type_exists($post_type)) {
                $query_args['post_type'] = $post_type;
            }
        }

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['post__in'] = array_map('intval', $ids); // Sanitize IDs
        }
        if(isset($this->request['s'])){
            $query_args['s'] = sanitize_text_field($this->request['s']);
        }

        $query = new \WP_Query($query_args);
        $options = [];
        if($query->have_posts()):
            while ($query->have_posts()) {
                $query->the_post();
                $options[] = [ 'id' => get_the_ID(), 'text' => get_the_title() ];
            }
        endif;
        wp_reset_postdata();

        return $options; // Return just the array, not wrapped in 'results'
    }

    public function get_category(){

        $taxonomy	 = 'category';
        $query_args = [
            'taxonomy'      => ['category'], // taxonomy name
            'orderby'       => 'name',
            'order'         => 'DESC',
            'hide_empty'    => true,
            'number'        => 6
        ];

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['include'] = $ids;
        }
        if(isset($this->request['s'])){
            $query_args['name__like'] = $this->request['s'];
        }

        $terms = get_terms( $query_args );


        $options = [];
        $count = count($terms);
        if($count > 0):
            foreach ($terms as $term) {
                $options[] = [ 'id' => $term->term_id, 'text' => $term->name ];
            }
        endif;
        return ['results' => $options];
    }

    public function get_product_list(){
        $query_args = [
            'post_type'         => 'product',
            'post_status'       => 'publish',
            'posts_per_page'    => 15,
        ];

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['post__in'] = $ids;
        }
        if(isset($this->request['s'])){
            $query_args['s'] = $this->request['s'];
        }

        $query = new \WP_Query($query_args);
        $options = [];
        if($query->have_posts()):
            while ($query->have_posts()) {
                $query->the_post();
                $options[] = [ 'id' => get_the_ID(), 'text' => get_the_title() ];
            }
        endif;

        return ['results' => $options];
        wp_reset_postdata();
    }

    public function get_product_cat(){
        $query_args = [
            'taxonomy'      => ['product_cat'], // taxonomy name
            'orderby'       => 'name',
            'order'         => 'DESC',
            'hide_empty'    => false,
            'number'        => 6
        ];

        if(isset($this->request['ids'])){
            $ids = explode(',', $this->request['ids']);
            $query_args['include'] = $ids;
        }
        if(isset($this->request['s'])){
            $query_args['name__like'] = $this->request['s'];
        }

        $terms = get_terms( $query_args );


        $options = [];
        $count = count($terms);
        if($count > 0):
            foreach ($terms as $term) {
                $options[] = [ 'id' => $term->term_id, 'text' => $term->name ];
            }
        endif;
        return ['results' => $options];
    }

}
new Select2_API();