<?php

namespace Blazemedia\Affiliation\Utils;

class HttpRequest {

    static function getContent( $url, $curl = true, $timeout = 1, $headers = [] ) {
        return $curl
            ? self::getContentCURL( $url, $timeout, $headers )
            : self::getContentGetFile( $url, $timeout, $headers );
    }

    /**
     * Undocumented function
     *
     * @param string $url
     * @param int $timeout
     * @param array $headers
     * @return object|string
     */
    static function getContentCURL( $url, $timeout, $headers = [] ){
        $curl = curl_init();

        $curlHeaders = [];
        foreach ($headers as $key => $value) {
            $curlHeaders[] = "$key: $value";
        }

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYHOST => 0,            
            CURLOPT_SSL_VERIFYPEER => false,    # required for https urls
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => $curlHeaders,
        ]);

        $response = curl_exec($curl);

        if ( curl_errno( $curl )) {
            $error_msg = curl_error( $curl );
        }

        // Then, after your curl_exec call:
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr( $response, 0, $header_size );        
        $body   = substr( $response, $header_size );

        // self::logHeaderMiss( $header, $url );
        
        curl_close($curl);

        return isset( $error_msg ) ? json_encode([
            'status' => 'error',
            'message' => $error_msg
        ]) : $body;
    }

    static function logHeaderMiss( $header, $url ) {
        if( str_contains( $header, 'X-GG-Cache-Status: MISS' ) ) {
            error_log("###HEADER_MISS###: ".$url, 0);
        };        
    }

    static function getContentGetFile( $url, $timeout, $headers = [] ) {
        try {
            $headerLines = [];
            foreach ($headers as $key => $value) {
                $headerLines[] = "$key: $value";
            }
            $contextOptions = [
                "ssl" => [
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ],
                "http" => [
                    'method' => 'GET',
                    'timeout' => $timeout,
                    'ignore_errors' => '1',
                    'header' => implode("\r\n", $headerLines),
                ]
            ];

            $res = file_get_contents( $url, false, stream_context_create( $contextOptions ));

            return $res;

        } catch (\Exception $e) {
            return json_encode ([
                'status' => 'error',
                'message' => $e->getMessage()
            ]);
        }
    }

}
