<?php

namespace Blazemedia\Affiliation\API;

use Blazemedia\Affiliation\Rendering\PageData;

class ArticlesByAsin extends ApiGET {

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


    protected function getData(){
        
        $asin = $this->params->asin;
        $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' => $asin,
            '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 );
    }

}