<?php

namespace Webkul\WooCommerceBundle\Classes;

/**
 * Basic auth
 *
 */
class BasicAuth
{
    /**
     * Consumer key.
     *
     * @var string
     */
    protected $consumerKey;

    /**
     * Consumer secret.
     *
     * @var string
     */
    protected $consumerSecret;

    /**
     * Initialize Basic Auth
     *
     * @param string $consumerKey    Consumer key.
     * @param string $consumerSecret Consumer Secret.
     */
    public function __construct($consumerKey, $consumerSecret)
    {
        $this->consumerKey    = $consumerKey;
        $this->consumerSecret = $consumerSecret;        
    }

    public function addAuthentication(&$ch, $url, $parameters = [])
    {
        $extraParam = parse_url($url);
        $extraParam = isset($extraParam['query']) ? $extraParam['query'] : null;
        if($extraParam) {
            parse_str($extraParam, $extraparameters);
            $parameters = array_merge($parameters, $extraparameters);
        }

        if($parameters) {
            $url = $url . '?' . http_build_query($parameters);
        }
        
        if('resource' == gettype($ch)) {
            $basicKey =  base64_encode($this->consumerKey . ':' . $this->consumerSecret);
            $headers = [
                'Authorization: Basic ' . $basicKey,
                'Content-Type: application/json'
            ];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_URL, $url);        
        }
    }
}