<?php

namespace Blazemedia\Affiliation\API;

abstract class ApiGET {

    const NAMESPACE = 'api/v1';

    protected string $signature = '';   
    protected string $action = '';   
    protected array $parameters = [];   
    protected $params;

    function __construct() {

        add_action( 'rest_api_init', [ $this, 'setRouting' ], 1 );
        add_action( 'init', array( $this, 'initCacheSettings' ) , 999999);

        $this->buildSignature();
    }

    public function setRouting() {

        register_rest_route( ApiGET::NAMESPACE, "/{$this->signature}", [
            
            'methods'  => 'GET',
            'callback' => array( $this, 'getCachedData' ),
            'permission_callback' => '__return_true'
        ]);
    }

    protected function buildSignature( ) {

        $this->signature = $this->action . '/' . array_reduce( $this->parameters, fn( $url, $parameter ) =>  "{$url}(?P<{$parameter}>.*)/", '');        
    }
    
    public function getCachedData( $request ) {

        $this->params   = (object) $request->get_params();
        
        if( BLAZE_AFFILIATION_CACHE ) {

            $data = get_transient( $this->transientKey() );

            if( $data === false ) {
                
                $data = $this->getData();
                
                set_transient( $this->transientKey(), $data, 3600);
            }

            echo $data;

        } else {

            echo $this->getData();
        } 
        
        die();
    }

    protected function transientKey() {

        return "{$this->signature}_transient";
    }

    public function initCacheSettings(){

		// SETTINGS CACHE
        $seconds_to_cache = 600;
        $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
        header("Expires: $ts");
        header("Pragma: no-cache");
        header("Cache-Control: max-age=".$seconds_to_cache.", public");
        
	}

    abstract protected function getData();
    
}