<?php

namespace Velis\User;

use Velis\App;
use Velis\Output;
use Velis\Lang;

/**
 * User signature model
 *
 * @author Michał Nosek <michal.nosek@velis.pl>
 */
class Signature extends \Velis\Signature
{

    /**
     * Returns signature type
     * @return string
     */
    public function getType()
    {
        return 'ENVELOPED';
    }

    /**
     * Returns signature filename
     * @return string
     */
    public function getFilename()
    {
        return 'CertificateAssign' . App::$user->id();
    }


    /**
     * Returns signature filename
     * @return string
     */
    public function getRedirectUrl()
    {
        return '/ustawienia';
    }


     /**
     * Get user from xml and validate
     * @param \SimpleXMLElement $xml
     * @return bool
     */
    public function validateUserFromXml($xml)
    {
        $xml = new \SimpleXMLElement($xml);
        if ($xml->SigningUserId != App::$user->id()) {
            return false;
        } else {
            return true;
        }
    }

    public function getCertificate()
    {
        if (!$this->_signature) {
            throw new \Exception('Brak podpisu');
        }

        $xml         = new \SimpleXMLElement($this->_signature);
        $ns          = $xml->getNamespaces(true);
        $child       = $xml->children($ns['ds']);
        return reset($child->Signature->KeyInfo->X509Data->X509Certificate);
    }



    /**
     * Generates order confirmation xml
     * @return string Xml to sign
     */
    public function generateConfirmXml()
    {
        $confirmArray = array('CertificateAssign' =>
            array(  'DocumentType' => 'Certificate',
                    'DocumentNumber'   => App::$user->id(),
                    'SigningUserId'    => App::$user->id(),
                    'SigningUser'      => App::$user
                            ));
        $xml = new \XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString("\t");
        $xml->startDocument();

        Output::xmlFromArray($xml, $confirmArray);
        $xml->endDocument();

        return $xml->outputMemory();
    }
}
