<?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()
            ]);
        }
    }



    static function post( string $url, string $json, bool $ssl_ignore  = false ) {

        $curl = curl_init();

        curl_setopt( $curl, CURLOPT_URL,            $url  ); 
        curl_setopt( $curl, CURLOPT_POST,           true  ); 
        curl_setopt( $curl, CURLOPT_POSTFIELDS,     $json );
        curl_setopt( $curl, CURLOPT_TIMEOUT,        2     );
        
        // Imposta a true per ottenere una risposta come stringa
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true  ); 
         
        curl_setopt( $curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json', 
            'Content-Length: ' . strlen( $json )
        ]);
        
        if( $ssl_ignore ) {

            // Ignora la verifica del certificato SSL
            curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 ); // Non verificare l'host
            curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // Non verificare il peer
        }
        

        // Esegui la richiesta e ottieni la risposta
        $response = curl_exec( $curl );

        // Controlla se ci sono errori
        if(curl_errno( $curl )) {
            echo 'Errore di cURL: ' . curl_error( $curl );
        }

        // Chiudi la sessione cURL
        curl_close( $curl );

        return $response;
    }


}
