<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 02/21/2017
 */

namespace AppBundle\Export;


use AppBundle\Util;
use Monolog\Logger;

abstract class SternToursCrmExporter
{
    const API_URL = 'http://www.cms.stern-tours.net/api';
    const API_KEY = 'f6077389c9ce710e554763a5de02c8ec';
    const API_USER_ID = 15; // 'apiuser'
    const WEBSITE_ID = 1; // 'sterntours.de'

    protected $logger;

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

    protected final function httpGet($url)
    {   
        $auth = base64_encode("star:4w28baV8xEZa0SR4");
        $resp = Util::httpGet($url, ['X-ApiKey: '. self::API_KEY, 'Authorization: Basic '.$auth]);
        $ret = json_decode($resp['content'], true);
        if ($ret === null)
        {
            $this->logger->warn(get_class($this) .': Invalid server response: '. $resp['content']);
            $this->logger->warn('*** Date: '. (new \DateTime())->format('d.m.Y'));
        }
        return $ret;
    }

    protected final function httpPost($context, $postData = [], $isContextFullUrl = false)
    {
        $url = $isContextFullUrl ? $context : self::API_URL.'/'. $context .'.json';
        $auth = base64_encode("star:4w28baV8xEZa0SR4");
        $resp = Util::httpPost($url, $postData, ['X-ApiKey: '. self::API_KEY, 'Authorization: Basic '.$auth], true);
        return [
            'content' => json_decode($resp['content']),
            'location' => isset($resp['response_headers']['location'])
                ? $resp['response_headers']['location']
                : null,
            'success' => $resp['success'] && ($resp['status_code'] == 201)
        ];
    }


}