<?php
namespace Helpers\Outil;

class HTTP
{
    protected $contenaire;

    public function __construct($contenaire)
    {
        $this->contenaire = $contenaire;
    }

    public function curl($url, $post, $sessionId)
    {
        $cookieHeader = '';
        $cookiePairs = [];
        foreach ($_COOKIE as $key => $value) {
            $cookiePairs[] = $key . '=' . $value;
        }

        $cookieHeader .= implode('; ', $cookiePairs);
        
        $ch = curl_init();
        

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . $sessionId);
        curl_setopt($ch, CURLOPT_URL, Outils::getRootUrl() . $this->contenaire->get('base').$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/xml',
                'Content-Length: ' . strlen($post),
                'Cookie: '.$cookieHeader,
            ));
        session_write_close();
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    /**
     * Redirect with POST data.
     *
     * @param string $url URL.
     * @param array $data POST data. Example: array('foo' => 'var', 'id' => 123)
     * @param array $headers Optional. Extra headers to send.
     */
    public static function redirectPost($url, array $data, array $headers = null)
    {

        $post_params = [];

        foreach ($data as $key => &$val) {
            if (is_array($val)) {
                $val = implode(',', $val);
            }
              $post_params[] = $key.'='.urlencode($val);
        }

        $post_string = implode('&', $post_params);

        $url = Outils::getRootUrl() . $url;
        $params = array(
            'http' => array(
                'method' => 'POST',
                'content' => $post_string
            )
        );
        if (!is_null($headers)) {
            $params['http']['header'] = '';
            foreach ($headers as $k => $v) {
                $params['http']['header'] .= "$k: $v\n";
            }
        }
        $ctx = stream_context_create($params);
        $fp = @fopen($url, 'rb', false, $ctx);
        if ($fp) {
            return @stream_get_contents($fp);
        } else {
            // Error
            throw new \Exception("Error loading '$url'");
        }
    }
}
