<?php

namespace Blazemedia\Affiliation\API;

class ArticlesByITM extends ApiGET {

    protected string $action     = 'articlesbyitm';
    protected array  $parameters = ['code','post_type','post_ID'];
    
    protected function transientKey() {
        
        return "articles_by_itm_{$this->params->code}";
    }


    protected function getData(){
        
        $code      = $this->params->code;
        $post_type = $this->params->post_type;
        $post_ID   = $this->params->post_ID;

        $year  = (new \DateTime())->format('Y');
        $month = (new \DateTime())->format('m');
        $day   = (new \DateTime())->format('d');

        $query = [
            'post_type'   => [$post_type],
            's' => $code,
            'posts_per_page' => -1,
            'post_status' => ['publish', 'pending', 'draft', 'auto-draft', 'future'],  
            'post__not_in'   => [$post_ID],
            'date_query' => [
                'year'  => $year,
                'month' => $month,
                'day'   => $day,
            ]
        ];

         $articles = array_map(function($post){

            $pagedata = new PageData($post);

            return $pagedata->getParams([
                'date'        => \get_the_date( 'Y-m-d' , $post->ID ),
                'title'       => \get_the_title( $post->ID),
                'url'         => \get_permalink( $post->ID)
            ]);


         } , get_posts( $query )); 


        return json_encode( $articles );
    }

}