<?php

namespace OAuth\Common\Http\Client;

use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\UriInterface;

/**
 * Client implementation for streams/file_get_contents
 */
class StreamClient extends AbstractClient
{
    /**
     * Extract last HTTP status line and code from $http_response_header.
     *
     * @param array $headers
     * @return array{0:string,1:int} [statusLine, statusCode]
     */
    private function getHttpStatusFromResponseHeaders($headers)
    {
        $statusLine = '';
        $statusCode = 0;

        if (!is_array($headers)) {
            return array($statusLine, $statusCode);
        }

        // In case of redirects, PHP may include multiple status lines. Keep the last one.
        foreach ($headers as $h) {
            if (is_string($h) && strpos($h, 'HTTP/') === 0) {
                $statusLine = trim($h);
            }
        }

        if ($statusLine !== '' && preg_match('/^HTTP\\/\\S+\\s+(\\d{3})\\b/', $statusLine, $m)) {
            $statusCode = (int) $m[1];
        }

        return array($statusLine, $statusCode);
    }

    /**
     * Any implementing HTTP providers should send a request to the provided endpoint with the parameters.
     * They should return, in string form, the response body and throw an exception on error.
     *
     * @param UriInterface $endpoint
     * @param mixed        $requestBody
     * @param array        $extraHeaders
     * @param string       $method
     *
     * @return string
     *
     * @throws TokenResponseException
     * @throws \InvalidArgumentException
     */
    public function retrieveResponse(
        UriInterface $endpoint,
        $requestBody,
        array $extraHeaders = array(),
        $method = 'POST'
    ) {
        // Normalize method name
        $method = strtoupper($method);

        $extraHeaders = $this->normalizeHeaders($extraHeaders);

        if ($method === 'GET' && !empty($requestBody)) {
            throw new \InvalidArgumentException('No body expected for "GET" request.');
        }

        if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) {
            $extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
        }

        $host = 'Host: '.$endpoint->getHost();
        // Append port to Host if it has been specified
        if ($endpoint->hasExplicitPortSpecified()) {
            $host .= ':'.$endpoint->getPort();
        }

        $extraHeaders['Host']       = $host;
        $extraHeaders['Connection'] = 'Connection: close';

        if (is_array($requestBody)) {
            $requestBody = http_build_query($requestBody, '', '&');
        }
        $extraHeaders['Content-length'] = 'Content-length: '.strlen($requestBody);

        //var_dump($requestBody); var_dump($extraHeaders);var_dump($method);exit;
        $context = $this->generateStreamContext($requestBody, $extraHeaders, $method);

		// @CHANGE DOL_LDR Add log
        if (function_exists('getDolGlobalString') && getDolGlobalString('OAUTH_DEBUG')) {
        	file_put_contents(DOL_DATA_ROOT . "/dolibarr_oauth.log", $endpoint->getAbsoluteUri()."\n", FILE_APPEND);
        	file_put_contents(DOL_DATA_ROOT . "/dolibarr_oauth.log", $requestBody."\n", FILE_APPEND);
        	file_put_contents(DOL_DATA_ROOT . "/dolibarr_oauth.log", $method."\n", FILE_APPEND);
        	file_put_contents(DOL_DATA_ROOT . "/dolibarr_oauth.log", var_export($extraHeaders, true)."\n", FILE_APPEND);
        	@chmod(DOL_DATA_ROOT . "/dolibarr_oauth.log", octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
        }

        $level = error_reporting(0);
        $response = file_get_contents($endpoint->getAbsoluteUri(), false, $context);
        error_reporting($level);
        if (false === $response) {
            $lastError = error_get_last();
            if (is_null($lastError)) {
                throw new TokenResponseException(
                    'Failed to request resource. HTTP Code: ' .
                    ((isset($http_response_header[0]))?$http_response_header[0]:'No response')
                );
            }
            throw new TokenResponseException($lastError['message']);
        }

        // When ignore_errors is enabled, file_get_contents returns the body even on HTTP 4xx/5xx.
        // Keep the previous behavior (throw on HTTP errors) but include a short response snippet to help debugging.
        list($statusLine, $statusCode) = $this->getHttpStatusFromResponseHeaders(isset($http_response_header) ? $http_response_header : null);
        if ($statusCode >= 400) {
            $snippet = trim((string) $response);
            if (strlen($snippet) > 2000) {
                $snippet = substr($snippet, 0, 2000).'...';
            }

            $msg = 'Failed to request resource. HTTP Code: '.($statusLine !== '' ? $statusLine : (string) $statusCode);

            $canShowDetails = (!empty($GLOBALS['user']) && is_object($GLOBALS['user']) && !empty($GLOBALS['user']->admin));
            if ($snippet !== '' && $canShowDetails) {
                $msg .= ' Response: '.$snippet;
            }

            throw new TokenResponseException($msg);
        }

        return $response;
    }

    private function generateStreamContext($body, $headers, $method)
    {
        return stream_context_create(
            array(
                'http' => array(
                    'method'           => $method,
                    'header'           => implode("\r\n", array_values($headers)),
                    'content'          => $body,
                    'protocol_version' => '1.1',
                    'user_agent'       => $this->userAgent,
                    'max_redirects'    => $this->maxRedirects,
                    'timeout'          => $this->timeout,
                    // Return the response body even on HTTP error status codes so we can include it in exceptions.
                    'ignore_errors'    => true
                ),
            )
        );
    }
}
