<?php

// A light version of the iamCommons WebRequest
// This code is property of IAM
// Licensed under Creative Commons Attribution

namespace OctopusSignatureClient\Commons;


class WebRequest
{

    public function __construct()
    {

    }


    // Static Methods

    /**
     * Curls any given URL. Returns the Response Code, The Response as an array.
     *
     * @param $targetURL. The URL to curl
     * @param $fields. An array with pairs key=>value to build the request
     * @param string $method. Get, Post, Put, Delete
     * @return array. An array with two keys. Code and Response.
     */
    public static function curlThis($targetURL, $fields, $method = 'post')
    {
//        TODO: ADD PUT AND DELETE

        $queryString =  http_build_query( $fields );

        if( $method == 'get' ){
            $targetURL .= "?{$queryString}";
        }

        $ch = curl_init( $targetURL );

        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_REFERER, get_home_url());

        if ( $method == "post" ){
            curl_setopt( $ch, CURLOPT_POST, count( $fields ) );
            curl_setopt( $ch, CURLOPT_POSTFIELDS, $queryString );
        }

        $response = curl_exec( $ch );
        $code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
        curl_close( $ch );

        return array( "code" => $code, "response" => $response );
    }

    /**
     * This function is uses curl to get the file contents of any given URL
     *
     * @param $fields. Fields for the request
     * @param string $method. Get, Post, Put or Delete
     * @return mixed File Contents
     */
    public static function getFileContentFromURL($targetURL)
    {
        set_time_limit(0);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 50);
        curl_setopt($curl, CURLOPT_URL, str_replace(" ","%20",$targetURL));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);

        $file = curl_exec($curl);

        curl_close($curl);

        return $file;
    }

}