<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\RestAuthBundle\Api;

use GuzzleHttp\Exception\RequestException;

/**
 * Class Controller
 * @package LifeStyle\Tools\RestAuthBundle\Api
 */
class Controller
{
    /**
     * @var Manager
     */
    public $apiM;

    /**
     * @var \GuzzleHttp\Client
     */
    public $client;

    /**
     * Constructor
     * @param Manager $apiM
     */
    public function __construct(Manager $apiM)
    {
        $this->apiM = $apiM;
        $this->client = $this->apiM->client();
    }

    /**
     * @param string $username
     * @param string $userIdentifier
     * @return boolean
     */
    public function userIdentifierValidate($username, $userIdentifier)
    {
        $request = $this->apiM->modelFactory()->request();
        $request->credentials()->serviceCountry();
        $request->userIdentifier()
            ->validate()
            ->key()
            ->userType()
            ->setUsername($username)
            ->setUserIdentifier($userIdentifier);

        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'UserIdentifier',
                'API-ACTION' => 'Validate',
                'Content-Type' => 'text/xml; charset=UTF-8',
            ),
            'body' => $this->apiM->serializer()->serialize($request, 'xml'),
        );

        try {
            $clientResponse = $this->client->post($this->apiM->configuration()->getServiceUrl(), $options);
        } catch (RequestException $ex) {
            $this->apiM->logger()->error('Cannot validate userIdentifier!');

            return false;
        } catch (\Exception $exc) {
            $this->apiM->logger()->error('Cannot validate userIdentifier!');

            return false;
        }

        $response = $this->apiM->modelFactory()->response($clientResponse->getBody());
        try {
            return 'Success' == $response->getStatus() && 'Success' == $response->getUserIdentifier()->validate()->getStatus();
        } catch (\Exception $ex) {
            unset($ex);
        }

        return false;
    }
}
