<?php

namespace Blazemedia\Affiliation\Utils;

class HttpRequest {

    

    static function getContent( $url, $curl = true, $timeout = 1 ) {

        return $curl ? self::getContentCURL( $url, $timeout ) : self::getContentGetFile( $url, $timeout );
    }


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

        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",
        ]);

        $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 ) {

        try {

            $res = file_get_contents( $url, false, stream_context_create( [
                "ssl" => [
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ],
                "http" => [
                    'method' => 'GET',
                    'timeout' => $timeout,  // 1200 Seconds is 20 Minutes
                    'ignore_errors' => '1',
                ]
            ]));

            return $res;

        } catch (\Exception $e) {

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

}
