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

namespace Shara\Reportes;

use Exception;
use Knp\Snappy\Pdf;
use Shara\App\Log;

class FacturaPdf
{

    private $documento = null;
    private $docPdf = null;
    private $claveAcceso = null;
    private $infoTri;
    private $estado;
    private $fechaAutorizacion;
    private $numeroAutorizacion;
    private $ambiente;
    private $pathLogo;


    /**
     * FacturaPdf constructor.
     */
    public function __construct($docPdf, $clave, $documento, $infoTri, $estado, $fechaAutorizacion, $pathLogo, $numAutorizacion, $ambiente)
    {

        $log = new Log();

        try {
            if (PHP_OS == 'Linux') {
                define('WKHTMLTOPDF_PATH', '../src/wkhtmltopdf-amd64');
                $this->snappy = new Pdf('../src/wkhtmltopdf-amd64');
                //define('WKHTMLTOIMAGE_PATH', APP_ROOT . '[site-path]/wkhtmltoimage-amd64');
            } elseif (PHP_OS == "Darwin") {
                //define('WKHTMLTOPDF_PATH', APP_ROOT . '[site-path]/wkhtmltopdf-osx');
                //define('WKHTMLTOIMAGE_PATH', APP_ROOT . '[site-path]/wkhtmltoimage-osx');
                $this->snappy = new Pdf('../src/wkhtmltopdf');
            } else {
                $this->snappy = new Pdf('C:\xampp74\htdocs\api_sharafac\src\wkhtmltopdf64.exe');
            }
        }catch (Exception $ex){
            $log->setError($ex->getMessage());
        }

        $this->documento = $documento;
        $this->docPdf = $docPdf;
        $this->claveAcceso = $clave;
        $this->infoTri = $infoTri;
        $this->estado = $estado;
        $this->fechaAutorizacion = $fechaAutorizacion;
        $this->numeroAutorizacion = $numAutorizacion;
        $this->pathLogo = $pathLogo;
        $this->ambiente = $ambiente;
    }

    public function generarPdf(\Twig\Environment $twig, $isHtml = false, $plantilla, $agente_ret)
    {
        $resp = null;

        $log = new Log();
        try {

            $template = $twig->load($plantilla);

            $infoFac = DatosReporte::getInfoComprobante($this->documento, 'infoFactura');
            if ($infoFac['error'] === true)
                return $infoFac;

            $impuestos = DatosReporte::getImpuestosFactura($this->documento);
            if ($impuestos['error'] === true)
                return $impuestos;

            $pagos = DatosReporte::getPagos($this->documento);
            if ($pagos['error'] === true)
                return $pagos;

            $detalle = DatosReporte::getDetalleFactura($this->documento);
            if ($detalle['error'] === true)
                return $detalle;

            $infoAdici = DatosReporte::getInfoAdicional($this->documento);
            if ($infoAdici['error'] === true)
                return $infoAdici;

            $email = "";
            $direccion = "";
            $telefono ="";
            $notas = "";
            $puntoEmision="";
            $rucSocio="";
            $contribuyente ="";
            $razonSocialSocio="";
            $placa ="";
            $infoAdiciTransdanant = array();
            $infoAdicional = array();



            foreach ($infoAdici['infoadici'] as $key => $value) {
                if (strtolower($key) === 'email')
                    $email = $value;
                else if (strtolower($key) === 'direccion' || strtolower($key) === 'dirección')
                    $direccion = $value;
                else if (strtolower($key) === 'telefono' || strtolower($key) === 'teléfono')
                    $telefono = $value;
                else if ($key === 'Notas')
                    $notas = $value;

                else {
                    $infoAdiciTransdanant[$key] = $value;
                    $infoAdicional[$key] = $value;
                }

            }

            $barcode = ReporteUtil::getCodBarras($this->claveAcceso);

            $repUtil = new ReporteUtil();

            $totales = $repUtil->getTotales($impuestos['impuestos']);
            if ($totales['error'] === true)
                return $totales;

            if (file_exists($this->pathLogo) == false)
                $this->pathLogo = '../public' . DIRECTORY_SEPARATOR . 'logo.jpeg';

            $imagen = file_get_contents($this->pathLogo);

            $html = $template->render(
                array(
                    'infotri' => $this->infoTri['infotri'],
                    'info' => $infoFac['infodoc'],
                    'fechaAutorizacion' => $this->fechaAutorizacion,
                    'ambiente' => $this->ambiente,
                    'claveacceso' => $this->claveAcceso,
                    'barcode' => $barcode == null ? '' : $barcode,
                    'detalle' => $detalle['detalle'],
                    'infoadici' => $infoAdici['infoadici'],
                    'fpago' => $pagos['pagos'],
                    'totales' => $totales['totimp'],
                    'logo' => base64_encode($imagen),
                    'print' => $isHtml,
                    'email' => $email,
                    'telefono' => $telefono,
                    'direccion' => $direccion,
                    'notas' => $notas,
                    'agente_ret' =>$agente_ret,
                    'infoadicional' => $infoAdicional,

                    'infoadicitransdanant' => $infoAdiciTransdanant,
                    'puntoemision_socio' =>$puntoEmision,
                    'ruc_socio' =>$rucSocio,
                    'contribuyente_socio' =>$contribuyente,
                    'nombre_socio' =>$razonSocialSocio,
                    'placa_socio' =>$placa,

                ));



            if($isHtml == false) {
                $footer = $twig->render('footer.html', array());

                if (file_exists($this->docPdf . DIRECTORY_SEPARATOR . $this->claveAcceso . '.pdf'))
                    unlink($this->docPdf . DIRECTORY_SEPARATOR . $this->claveAcceso . '.pdf');
                try{

                    $this->snappy->setOption('footer-html', $footer);
                    $this->snappy->generateFromHtml($html, $this->docPdf . DIRECTORY_SEPARATOR . $this->claveAcceso . '.pdf');

                } catch (Exception $ex1) {
                    $log->setError($ex1->getMessage());
                }

                $resp = array('error' => false, 'html' => '');
            }
            else
                $resp = array('error' => false, 'html' => $html);

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

}
