<?php

namespace Vendtics\App\Http\Controllers\Admin;

defined( 'ABSPATH' ) || exit;

use Vendtics\App\Http\Controllers\Controller;
use Vendtics\App\Models\Post;
use Vendtics\WpMVC\RequestValidator\Validator;
use Vendtics\WpMVC\Routing\Response;
use WP_REST_Request;

class PageController extends Controller {
    public function index( Validator $validator, WP_REST_Request $wp_rest_request ) {
        $validator->validate(
            [
                'ids'    => 'array',
                'search' => 'string'
            ]
        );

        $page = Post::query()->select( 'ID as id, post_title as title' )->where( 'post_type', 'page' )->where( 'post_status', 'publish' )->order_by_desc( 'id' );
            
        if ( $wp_rest_request->has_param( 'ids' ) ) {
            $ids = map_deep( $wp_rest_request->get_param( 'ids' ), 'intval' );
            $page->where_in( 'ID', $ids );
        }

        $pages = $page->get();

        if ( ! empty( $pages ) ) {
            $pages = array_map( fn( $item ) => [ 'id' => $item->id, 'name' =>  $item->title ], $pages );
        } else {
            $pages = [];
        }
    
        return Response::send(
            [
                'items' => $pages
            ] 
        );
    }
}