<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'Gridpress_Admin_Ajax' ) ) {

    class Gridpress_Admin_Ajax {

        public function __construct() {
            add_action(
                'wp_ajax_gridpress_ajax_get_page_results',
                array( $this, 'gridpress_get_pages_list' )
            );
        }

        /**
         * Get pages list for AJAX search.
         *
         * @return void
         */
        public function gridpress_get_pages_list() {

            check_ajax_referer( 'gridpress_admin_nonce', 'gridpress_nonce' );

           if ( ! current_user_can( 'edit_pages' ) ) {
                wp_send_json_error(
                    array(
                        'message' => esc_html__( 'Permission denied.', 'gridpress-grid-layout-design' ),
                    )
                );
                wp_die();
            }
            $gridpress_pages = [];

            if ( ! gridpress_user_normal_permission() ) {
                wp_send_json(
                    array(
                        'results' => $gridpress_pages,
                    )
                );
            }
            $gridpress_query_args = array(
                'post_type'      => 'page',
                'post_status'    => 'publish',
                'posts_per_page' => 50,
                'fields'         => 'ids',
                'orderby'        => 'title',
                'order'          => 'ASC',
            );

            if ( isset( $_POST['q'] ) ) {
                $gridpress_query_args['s'] = sanitize_text_field(
                    wp_unslash( $_POST['q'] )
                );
            }

            $gridpress_page_ids = get_posts( $gridpress_query_args );

            if ( ! empty( $gridpress_page_ids ) && is_array( $gridpress_page_ids ) ) {
                foreach ( $gridpress_page_ids as $gridpress_id ) {
                    $gridpress_id    = absint( $gridpress_id );
                    $gridpress_title = get_the_title( $gridpress_id );
                    $gridpress_pages[] = array(
                        'id'   => $gridpress_id,
                        'text' => sprintf(
                            /* translators: 1: Page title, 2: Page ID. */
                            esc_html__( '%1$s (ID: %2$d)', 'gridpress-grid-layout-design' ),
                            esc_html( $gridpress_title ),
                            $gridpress_id
                        ),
                    );
                }
            }
            wp_send_json(
                array(
                    'results' => $gridpress_pages,
                )
            );
        }
    }
    new Gridpress_Admin_Ajax();
}