<?php

class BlogApi extends Api
{
    public $apiName = 'blog';

    public function __construct($requestUri, $encryption=true) {
      $this->cacheWhitelist = [
        "viewAction" => ['ttl' => 900], // 900 sec. = 15 min.
        "indexAction" => ['ttl' => 900]
      ];
      parent::__construct($requestUri, $encryption);
    }

    public function indexAction()
    {
        global $savvyext;
        $message = "Data not found";
        $limit = trim($this->requestParams["limit"] ?? "");
        $page = trim($this->requestParams["page"] ?? "");
        $params =[
            'limit' => $limit,
            'page' => $page
        ];
        
        $url = $savvyext->cfgReadChar('system.blog_api_url') . "/latest-articles?".http_build_query($params);

        try {
            $body = file_get_contents($url, false);
            $result = json_decode($body, true);

            return $this->response(
                array(
                    'data' => $result,
                    'error' => ""), 
                200);
        } catch (Exception $e) {
            error_log(json_encode($e));
            $message = $e->getMessage();
        }

        return $this->response(
            array(
                "error" => $message,
            ), 500);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/blog/679
     * @return string
     */
    public function viewAction()
    {
        global $savvyext;
        $message = "Data not found";
        $id = array_shift($this->requestUri);
        if(!empty($id)){
            $url = $savvyext->cfgReadChar('system.blog_api_url') . "/articles/" . intval($id);
            try {
                $body = file_get_contents($url, false);
                $result = json_decode($body, true);
    
                return $this->response(
                    array(
                        'data' => $result,
                        'error' => ""), 200);
            } catch (Exception $e) {
                error_log(json_encode($e));
                $message = $e->getMessage();
            }
            
        }

        return $this->response(
            array(
                "error" => $message,
            ), 500);
    }

    public function createAction()
    {
        return $this->response(
            array(
                "error" => "Data not found",
            ), 400);

    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error",
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error",
            ), 500);
    }

}
