<?php
namespace Helpers\Outil;

use Psr\Container\ContainerInterface;

class HTTP
{
    protected ContainerInterface $contenaire;

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

    // /**
    //  * @param string $url
    //  * @param array<mixed> $post
    //  * @param string $sessionId
    //  * @return bool|string
    //  */
    // public function curl($url, $post, $sessionId)
    // {
    //     $headers = array(
    //         "Content-type: text/xml",
    //         "Content-length: " . strlen($post),
    //         "Connection: close",
    //     );

    //     $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_HTTPHEADER, $headers);
    //     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)));
    //     session_write_close();
    //     $response = curl_exec($ch);
    //     curl_close($ch);
    //     return $response;
    // }

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

        $url = Outils::getRootUrl() . $url;

        $post_string = http_build_query($data);

        $params = [
            "http" => [
                "method" => "POST",
                "content" => $post_string,
                "header" => [
                    "Content-type: application/x-www-form-urlencoded\r\n" .
                    "Content-length: " . strlen($post_string) . "\r\n" .
                    "Accept: */*\r\n"
                ],
            ]
        ];

        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, 'r', false, $ctx);
        if ($fp) {
            return stream_get_contents($fp);
        } else {
            // Error
            throw new \Exception("Error loading '$url'");
        }
    }

    /**
     * @param non-empty-string $delimiter
     * @return array<string,string[]> All keys are lowercase
     */
    public static function parseHeader(string $raw, string $delimiter = "\r\n") :array
    {
        return array_reduce(
            array_filter(explode($delimiter, $raw)),
            function ($carry, $item) {
                list($key, $content) = explode(': ', $item, 2);
                $carry[ strtolower($key) ][] = $content;
                return $carry;
            },
            []
        );
    }

    /**
     * All keys are lowercase
     * @return array<string,string[]>
     */
    public static function parseContentDisposition(string $raw) :array
    {
        return array_reduce(
            explode(';', StringHelper::removePrefix($raw, 'form-data; ')),
            function ($carry, $item) {
                list($key, $content) = explode('=', $item, 2);
                if (str_starts_with($content, '"')) { // Strip double quote
                    $content = substr($content, 1, strlen($content) - 2);
                }
                $carry[ strtolower($key) ] = $content;
                return $carry;
            },
            []
        );
    }
}
