<?php
/**
 * Created by PhpStorm.
 * User: svycar
 * Date: 23/4/18
 * Time: 14:41
 */

namespace Shara;

use DOMDocument;
use Shara\App\Log;
use Shara\Comprobantes\Comprobante;
use Shara\Reportes\DatosReporte;
use Shara\Reportes\FacturaPdf;
use Shara\Reportes\GuiaRemisionPdf;
use Shara\Reportes\LiquidacionPdf;
use Shara\Reportes\NcreditoPdf;
use Shara\Reportes\RetencionPdf;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;


class ComprobantesController
{
    private $config;
    private $tipoComprobante;
    private $clave;
    private $xmlFirmado = null;
    protected $log;


    public function __construct(array $config, $clave, $tipoComprobante)
    {
        $this->log = new Log();

        // zona horaria
        date_default_timezone_set('America/Bogota');
        $this->config = $config;
        $this->clave = $clave;
        $this->tipoComprobante = $tipoComprobante;
    }

    public function getConsultarAutorizacion($clave)
    {

        //CREAR COMPROBANTE
        $firma = array(
            'file' => $this->config["pathfirma"],
            'pass' => $this->config["passfirma"]);

        $comprobante = new Comprobante($this->config);
        $comprobante->setClaveAcesso($clave);

        $resp = $comprobante->autorizacionIndividualSri('01');


        /*if ($resp['error'] === false && $resp['autorizado'] === true) {
            $resp = $comprobante->generarPdf($this->twig, '01');
        }*/

        return $resp;
    }

    /**
     * Consultar Autorizacion XML method
     *
     * @return array
     */
    public function autorizacionXml()
    {
        try {
            //AUTORIZAR SRI
            if (strlen($this->clave) != 49)
                return array('error' => true, 'mensaje' => 'longitud clave de acceso mal estructura');

            //sleep(2);
            $comprobante = new Comprobante($this->config);
            $comprobante->setClaveAcesso($this->clave);
            $resp = $comprobante->autorizacionIndividualSri($this->tipoComprobante);

            /*if ($resp['error'] === false && $resp['autorizado'] === true) {
                //generar pdf y envio mail cliente
                return $resp;

            } else
                return array('error' => true, 'estado' => $resp["estado"], 'mensaje' => $resp["mensaje"]);
            */

            return $resp;

        } catch (\Exception $ex) {
            return array('error' => true, 'estado' => 'excepcion: ' . $ex->getLine(), 'mensaje' => $ex->getMessage());
        }

    }

    /**
     * Enviar XML method
     *
     * @return array
     */
    public function enviarXml()
    {
        $resp = null;
        try {

            if ($this->xmlFirmado == null)
                return array('error' => true, 'mensaje' => 'xml firmado is null');

            if (strlen($this->clave) != 49)
                return array('error' => true, 'mensaje' => 'longitud clave de acceso mal estructura');

            //ENVIAR SRI
            $comprobante = new Comprobante($this->config);
            $comprobante->setClaveAcesso($this->clave);
            $resp = $comprobante->envioIndividualSri($this->tipoComprobante, $this->xmlFirmado);

        } catch (\Exception $ex) {
            return array('error' => true, 'mensaje' => $ex->getMessage());
        }
        return $resp;

    }

    /**
     * Crear validar firmar XML method
     * @param string $xmlString string xml del comprobante
     *
     * @return array
     */
    public function validarFirmarXml($xmlString)
    {
        try {

            $xmlString = trim($xmlString);

            if (strlen($this->clave) != 49)
                return array('error' => true, 'mensaje' => 'longitud clave de acceso mal estructura');

            $pathXsdName = "";
            //VALIDAR XML
            switch ($this->tipoComprobante) {
                case '01':
                    $pathXsdName = $this->config['xsd'] . DIRECTORY_SEPARATOR . 'factura.xsd';
                    break;
                case '03':
                    $pathXsdName = $this->config['xsd'] . DIRECTORY_SEPARATOR . 'liquidacioncompra.xsd';
                    break;
                case '04':
                    $pathXsdName = $this->config['xsd'] . DIRECTORY_SEPARATOR . 'notaCredito.xsd';
                    break;
                case '06':
                    $pathXsdName = $this->config['xsd'] . DIRECTORY_SEPARATOR . 'guiaRemision.xsd';
                    break;
                case '07':
                    $pathXsdName = $this->config['xsd'] . DIRECTORY_SEPARATOR . 'comprobanteRetencion.xsd';
                    break;
            }

            $resp = Comprobante::validarXml($xmlString, $pathXsdName);

            if ($resp != null) 
                return $resp;

            //if (file_put_contents($this->App['generados'] . DIRECTORY_SEPARATOR . $clave . ".xml", $xmlString) === false)
            //    return array('error' => true, 'mensaje' => 'no se puede crear el archivo xml en: ' . $this->App['generados']);

            $proxy = [
                'pruebas' => $this->config['url_pruebas'],
                'produccion' => $this->config['url_produccion'],
            ];

            $comprobante = new Comprobante($proxy);

            $firma = array(
                'file' => $this->config['pathFirma'],
                'pass' => $this->config['passFirma'],
                'firmados' => $this->config['firmados']
            );


            $resp = $comprobante->firmarComprobante($firma, $this->clave, $xmlString);

            if ($resp != null)
                return $resp;

            $this->xmlFirmado = $comprobante->getXmlFirmado();

        } catch (\Exception $ex) {
            return array('error' => true, 'mensaje' => $ex->getMessage());
        }

        return array('error' => false, 'mensaje' => 'firma OK');
    }

    /**
     * Generar RIDE method
     *
     */
    public function getGenerarPdf($clave, $html = false, $xml_autorizado, $plantilla = 'invoice.html.twig')
    {
        $log = new Log();

        $loader = new FilesystemLoader('../public/templates');

        $twig = new Environment($loader, array(
            'cache' => '../public/templates/cache',
        ));

        $documento = new DOMDocument();
        $documento->loadXml($xml_autorizado);

        $items = $documento->documentElement;

        $offline = true;
        foreach ($items->childNodes as $item) {

            if ($item->nodeName === 'estado')
                $estado = $item->nodeValue;

            if ($item->nodeName === 'numeroAutorizacion')
                $numeroAutorizacion = $item->nodeValue;

            if ($item->nodeName === 'fechaAutorizacion') {
                $offline = false;
                $fechaAutorizacion = $item->nodeValue;
            }

            if ($item->nodeName === 'comprobante') {
                $comprobante = $item->nodeValue;
                break;
            }

        }

        if($offline){
            $log->setInfo($clave.", offline");
            $numeroAutorizacion = $clave;
            $fechaAutorizacion = "";
            $comprobante = $xml_autorizado;
        }
        else {
            $log->setInfo($numeroAutorizacion);

            if (strlen($numeroAutorizacion) != 49)
                return array('error' => true, 'mensaje' => 'la longitud del número de autorización debe ser 49');

        }
        $ambiente = substr($numeroAutorizacion, 23, 1);

        if ($ambiente === "1")
            $ambiente = "PRUEBAS";
        else if ($ambiente === "2")
            $ambiente = "PRODUCCION";

        $documento->loadXML($comprobante);

        $infoTri = DatosReporte::getInfoTributaria($documento);

        if ($infoTri['error'] === true)
            return $infoTri;

        switch ($infoTri["infotri"]["codDoc"]) {
            case '01':
                $facturaPdf = new FacturaPdf($this->config['pdf'], $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $this->config['logo'], $numeroAutorizacion, $ambiente);
                $aux = $facturaPdf->generarPdf($twig, $html, $plantilla, $this->config["agente_ret"]);
                if ($aux['error'] === true)
                    return array('error' => true, 'mensaje' => $aux['mensaje']);
                else {
                    if ($html === true)
                        return array('error' => false, 'html' => $aux['html']);
                    return array('error' => false, 'mensaje' => '');
                }

                break;
            case '03':
                $liquidacionPdf = new LiquidacionPdf($this->config['pdf'], $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $this->config['logo'], $numeroAutorizacion, $ambiente);
                $aux = $liquidacionPdf->generarPdf($twig, $html, $plantilla, $this->config["agente_ret"]);
                if ($aux['error'] === true)
                    return array('error' => true, 'mensaje' => $aux['mensaje']);
                else {
                    if ($html == true)
                        return array('error' => false, 'html' => $aux['html']);
                    return array('error' => false, 'mensaje' => '');
                }
                break;
            case '04':
                $ncreditoPdf = new NcreditoPdf($this->config['pdf'], $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $this->config['logo'], $numeroAutorizacion, $ambiente);
                $aux = $ncreditoPdf->generarPdf($twig, $html, $this->config["agente_ret"]);
                if ($aux['error'] === true)
                    return array('error' => true, 'mensaje' => $aux['mensaje']);
                else {
                    if ($html == true)
                        return array('error' => false, 'html' => $aux['html']);
                    return array('error' => false, 'mensaje' => '');
                }
                break;
            case '06':
                $guiaPdf = new GuiaRemisionPdf($this->config['pdf'], $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $this->config['logo'], $numeroAutorizacion, $ambiente);
                $aux = $guiaPdf->generarPdf($twig, $html, $plantilla, $this->config["agente_ret"]);
                if ($aux['error'] === true)
                    return array('error' => true, 'mensaje' => $aux['mensaje']);
                else {
                    if ($html == true)
                        return array('error' => false, 'html' => $aux['html']);
                    return array('error' => false, 'mensaje' => '');
                }
                break;
            case '07':
                $retencionPdf = new RetencionPdf($this->config['pdf'], $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $this->config['logo'], $numeroAutorizacion, $ambiente);
                $aux = $retencionPdf->generarPdf($twig, $html, $this->config["agente_ret"]);
                if ($aux['error'] === true)
                    return array('error' => true, 'mensaje' => $aux['mensaje']);
                else {
                    if ($html == true)
                        return array('error' => false, 'html' => $aux['html']);
                    return array('error' => false, 'mensaje' => '');
                }

                break;
        }

    }

}
