<?php
namespace Twilio\Http;

/**
 *
 * @package JCHAT::FRAMEWORK::administrator::components::com_jchat
 * @subpackage framework
 * @subpackage twilio
 * @subpackage sdk
 * @author Joomla! Extensions Store
 * @copyright (C) 2015 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 *
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );

class CurlClient implements Client {
    const DEFAULT_TIMEOUT = 60;
    protected $curlOptions = array();

    public function __construct(array $options = array()) {
        $this->curlOptions = $options;
    }

    public function request($method, $url, $params = array(), $data = array(),
                            $headers = array(), $user = null, $password = null,
                            $timeout = null) {
        $options = $this->options($method, $url, $params, $data, $headers,
                                  $user, $password, $timeout);

        try {
            if (!$curl = curl_init()) {
                throw new \Exception('Unable to initialize cURL');
            }

            if (!curl_setopt_array($curl, $options)) {
                throw new \Exception(curl_error($curl));
            }

            if (!$response = curl_exec($curl)) {
            	if (curl_errno ( $curl ) == 60) { // CURLE_SSL_CACERT
            		curl_setopt ( $curl, CURLOPT_CAINFO, dirname ( __FILE__ ) . '/ca_chain.crt' );
            		$response = curl_exec ( $curl );
            	}
            	if(!$response) {
	                throw new \Exception(curl_error($curl));
            	}
            }

            $parts = explode("\r\n\r\n", $response, 3);
            list($head, $body) = ($parts[0] == 'HTTP/1.1 100 Continue')
                               ? array($parts[1], $parts[2])
                               : array($parts[0], $parts[1]);

            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            $responseHeaders = array();
            $headerLines = explode("\r\n", $head);
            array_shift($headerLines);
            foreach ($headerLines as $line) {
                list($key, $value) = explode(':', $line, 2);
                $responseHeaders[$key] = $value;
            }

            curl_close($curl);

            if (isset($buffer) && is_resource($buffer)) {
                fclose($buffer);
            }

            return new Response($statusCode, $body, $responseHeaders);
        } catch (\Exception $e) {
            if (isset($curl) && is_resource($curl)) {
                curl_close($curl);
            }

            if (isset($buffer) && is_resource($buffer)) {
                fclose($buffer);
            }

            throw $e;
        }
    }

    public function options($method, $url, $params = array(), $data = array(),
                            $headers = array(), $user = null, $password = null,
                            $timeout = null) {

        $timeout = is_null($timeout)
            ? self::DEFAULT_TIMEOUT
            : $timeout;

        $options = $this->curlOptions + array(
            CURLOPT_URL => $url,
            CURLOPT_HEADER => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_INFILESIZE => -1,
            CURLOPT_HTTPHEADER => array(),
            CURLOPT_TIMEOUT => $timeout,
        );

        foreach ($headers as $key => $value) {
            $options[CURLOPT_HTTPHEADER][] = "$key: $value";
        }

        if ($user && $password) {
        	$bas64FunctionNameEncode = 'base'. 64 . '_encode';
            $options[CURLOPT_HTTPHEADER][] = 'Authorization: Basic ' . $bas64FunctionNameEncode("$user:$password");
        }

        $body = $this->buildQuery($params);
        if ($body) {
            $options[CURLOPT_URL] .= '?' . $body;
        }

        switch (strtolower(trim($method))) {
            case 'get':
                $options[CURLOPT_HTTPGET] = true;
                break;
            case 'post':
                $options[CURLOPT_POST] = true;
                $options[CURLOPT_POSTFIELDS] = $this->buildQuery($data);

                break;
            case 'put':
                $options[CURLOPT_PUT] = true;
                if ($data) {
                    if ($buffer = fopen('php://memory', 'w+')) {
                        $dataString = $this->buildQuery($data);
                        fwrite($buffer, $dataString);
                        fseek($buffer, 0);
                        $options[CURLOPT_INFILE] = $buffer;
                        $options[CURLOPT_INFILESIZE] = strlen($dataString);
                    } else {
                        throw new \Exception('Unable to open a temporary file');
                    }
                }
                break;
            case 'head':
                $options[CURLOPT_NOBODY] = true;
                break;
            default:
                $options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
        }

        return $options;
    }

    public function buildQuery($params) {
        $parts = array();

        $params = $params ?: array();

        foreach ($params as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $item) {
                    $parts[] = urlencode((string)$key) . '=' . urlencode((string)$item);
                }
            } else {
                $parts[] = urlencode((string)$key) . '=' . urlencode((string)$value);
            }
        }

        return implode('&', $parts);
    }
}
