{% extends "base.html.twig" %}

{% trans_default_domain 'core' %}

{% block actionheader %}

{% endblock %}

{% block searchform %}{% endblock %}

{% block body %}

    {{ form_start(form) }}

    <article class="invoice-like">

        <header id="invoice-like-title">
            {% block invoice_actions %}{% endblock %}
            {% block invoice_label %}{% endblock %}
        </header>
        <div class="box pad box-warning">

            <div class="box-header with-border">

                <div class="btn-group">

                    <a href="{{ path('invoice_index') }}" class="btn btn-app">
                        <i class="glyphicon glyphicon-list-alt"></i>
                        Listado
                    </a>
                    <a href="{{ path('invoice_add') }}" class="btn btn-app">
                        <i class="glyphicon glyphicon-file"></i>
                        Nuevo
                    </a>

                    <button type="button" class="btn btn-app" data-toggle="modal" data-target="#myModal"
                            onclick='verPdf("{{ path('invoice_show_pdf_preview',{ 'id': entity.id , 'slug': entity.slug }) }}")'>
                        <i class="fa fa-file-pdf-o"></i>Pdf
                    </button>

                    <button type="button" class="btn btn-app" onclick="imprimir('hola')">
                        <i class="fa fa-print"></i>Imprimir Tiket
                    </button>

                    {% if entity.autorizado == true %}
                        <a href="{{ path('invoice_download_xml', {'id': entity.id, 'slug': entity.slug}) }}"
                           class="btn btn-app" name="Form-xml"><span
                                    class="fa fa-file-text"></span> XML
                        </a>
                    {% endif %}







                    {% if entity.anulado == false %}
                        {% include "Core/comprob.show.html.twig" with {'entity': entity} %}
                        
                    {% endif %}
                    
                    
                    
                    
           {% if entity.anulado %}
  <button id="reactivate-btn" class="btn btn-app">
    <i class="fa fa-check-circle"></i> Reactivar
  </button>

  <script>
    document.getElementById('reactivate-btn').addEventListener('click', function() {
      if (!confirm('¿Seguro quieres reactivar esta factura?')) return;

      fetch('/reactivate_invoice.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({id: {{ entity.id }}})
      })
      .then(response => response.json())
      .then(data => {
        if(data.success) {
          alert('Factura reactivada');
          location.reload();
        } else {
          alert('Error: ' + data.message);
        }
      })
      .catch(err => alert('Error: ' + err.message));
    });
  </script>
{% endif %}


                    {#
                    REVISAR IMPORTANTE SHARA
                    <form action="{{ path('invoice_email', {'id': entity.id}) }}" method="post">
                        <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
                        <button type="submit" class="btn btn-default btn-warning"><span
                                    class="glyphicon glyphicon-envelope"></span> {% trans %}show.email{% endtrans %}</button>
                    </form>
                    #}


                </div>

            </div>
            <div class="box-body">
                {% if entity.anulado %}
                    <div class="container-fluid">
                        <div class="row text-center">
                            <div class="col-md-12">
                                <h2 style="color: red">ANULADO SOLO EN EL SISTEMA WEB, NO EN EL SRI</h2>
                                
  
                            </div>
                        </div>
                    </div>
                {% endif %}

                {% include "Core/emisor.show.html.twig" with {'entity': entity} %}

                <div class="row">
                    <div id="invoice-like-customer-data" class="col-md-12">

                        <h3>Factura</h3>

                        <div class="row">
                            <div class="col-md-3 clearfix">
                                <label>Serie:</label>
                                {{ entity.serie }}
                            </div>
                            <div class="col-md-3 clearfix">
                                <label>Número:</label>
                                {{ entity.label }}
                            </div>
                            <div class="col-md-3 clearfix">
                                <label>Fecha:</label>
                                {{ entity.issueDate |date("d/m/Y") }}
                            </div>

                        </div>
                        <div class="row">
                            <div class="col-md-6 clearfix">
                                <label>{% trans %}abstract_invoice.show.customer_name{% endtrans %}:</label>
                                {{ entity.customer_name }}
                            </div>
                            <div class="col-md-6 clearfix">
                                <label>{% trans %}abstract_invoice.show.customer_identification{% endtrans %}:</label>
                                {{ entity.customer_identification }}
                            </div>
                            <div class="col-md-6 clearfix">
                                <label>{% trans %}abstract_invoice.show.invoicing_address{% endtrans %}:</label>
                                {{ entity.invoicing_address|nl2br }}
                            </div>
                            <div class="col-md-6 clearfix">
                                <label>{% trans %}abstract_invoice.show.customer_email{% endtrans %}:</label>
                                {{ entity.customer_email }}
                            </div>

                        </div>
                    </div>

                    {# <div id="invoice-like-properties" class="col-md-5">
                        <div class="panel panel-default">
                            <h3 class="panel-heading">{% trans %}abstract_invoice.show.properties{% endtrans %}</h3>

                            <div class="panel-body">
                                <div class="col-md-12">
                                    <label>Clave acceso:</label>
                                    {{ entity.claveAcceso }}
                                </div>
                                <div class="col-md-12">
                                    <label>{% trans %}show.issue_date{% endtrans %}:</label>
                                    {{ entity.issueDate|localizeddate('none', 'none', app.request.locale, null, 'dd/MM/yyyy') }}
                                </div>
                                <div class="col-md-12">
                                    <label>Fecha de autorización:</label>
                                    {{ entity.fechaAutorizacion }}
                                </div>
                            </div>
                        </div>
                    </div> #}
                </div>

                <div class="row">
                    <div class="col-md-12">

                        <h3>{% trans %}abstract_invoice.show.items{% endtrans %}</h3>

                        <table id="invoice-like-items" class="table table-condensed table-striped align-middle">
                            <thead>
                            <tr>
                                <th class="">{% trans %}item.show.description{% endtrans %}</th>
                                <th class="col-md-1 cell-align-center">{% trans %}item.show.quantity{% endtrans %}</th>
                                <th class="col-md-2 cell-align-right">{% trans %}item.show.unitary_cost{% endtrans %}</th>
                                <th class="col-md-2 cell-align-right">{% trans %}item.show.discount{% endtrans %}</th>
                                {# <th class="col-md-1 cell-align-center">{% trans %}item.show.taxes{% endtrans %}</th> #}
                                <th colspan="2" class="cell-align-right">{% trans %}item.show.total{% endtrans %}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for item in entity.items %}
                                {{ include('Item/show.html.twig', { 'item': item, 'currency': currency }) }}
                            {% endfor %}
                            </tbody>
                        </table>

                    </div>
                </div>

                <div class="row totals">
                    <div class="col-md-4 col-md-offset-8">
                        <table id="invoice-like-totals" class="table table-condensed table-striped">
                            <tbody>
                            <tr>
                                <th class="cell-size-large">{% trans %}abstract_invoice.show.subtotal{% endtrans %}</th>
                                <td class="cell-align-right">{{ entity.baseAmount|localizedcurrency(currency, app.request.locale) }}</td>
                            </tr>
                            <tr>
                                <th>{% trans %}abstract_invoice.show.total_taxes{% endtrans %}</th>
                                <td class="cell-align-right">{{ entity.taxAmount|localizedcurrency(currency, app.request.locale) }}</td>
                            </tr>
                            <tr>
                                <th>{% trans with {'%currency%': currency} %}abstract_invoice.show.total{% endtrans %}</th>
                                <td class="cell-align-right">{{ entity.grossAmount|localizedcurrency(currency, app.request.locale) }}</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-8">

                        <table id="invoice-like-items" class="table table-condensed table-striped align-middle">
                            <thead>
                            <tr>
                                <th class="col-md-2">Forma Pago</th>
                                <th class="col-md-1 cell-align-right">Valor</th>
                                <th class="col-md-1 cell-align-right">Plazo</th>
                                <th class="col-md-1 cell-align-center">Tiempo</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for item in entity.pagos %}
                                <tr>
                                    <td>
                                        {{ item.formapago.name }}
                                    </td>
                                    <td class="cell-align-right">
                                        {{ item.valor|localizedcurrency(currency, app.request.locale) }}
                                    </td>
                                    <td class="cell-align-right">
                                        {{ item.plazo }}
                                    </td>
                                    <td class="cell-align-center">
                                        {{ item.tiempo }}
                                    </td>
                                </tr>

                            {% endfor %}
                            </tbody>
                        </table>

                    </div>
                </div>


                <div id="invoice-like-notes" class="row">

                    <div class="col-md-12" style="word-wrap: break-word;">
                        <label>{% trans %}abstract_invoice.show.notes{% endtrans %}:</label>
                        <p>{{ entity.notes|nl2br }}</p>
                    </div>
                </div>

                <div id="invoice-like-notes" class="row">

                    <div class="col-md-12" style="word-wrap: break-word;">
                        <label>Observación:</label>
                        <p>{{ entity.note1|nl2br }}</p>
                    </div>
                </div>

                {% if transportesocio is defined and transportesocio != null  %}
                    <h5><strong>DATOS TRANSPORTISTA</strong></h5>
                    <div class="row">
                        <div class="col-md-3 clearfix">
                            <label>PUNTO EMISION:</label>
                            {{ transportesocio.Ptoemisionsocio }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 clearfix">
                            <label>RAZÓN SOCIAL:</label>
                            {{ transportesocio.Nombresocio }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 clearfix">
                            <label>RUC:</label>
                            {{ transportesocio.Rucsocio }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 clearfix">
                            <label>TIPO CONTRIBUYENTE:</label>
                            {{ transportesocio.Tpcontribuyentesocio }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 clearfix">
                            <label>PLACA:</label>
                            {{ entity.placa }}
                        </div>
                    </div>
                {% endif %}

                <div class="entity-actions clearfix">
                    {% block invoice_edit_actions %}{% endblock %}
                </div>

            </div>
        </div>
    </article>

    {% include "Core/email.show.html.twig" with {'entity': entity} %}

    {{ form_rest(form) }}
    {{ form_end(form) }}
  
 <style>
    /* Estilos para la tabla específica */
    table#invoice-table {
        width: 56mm; /* Ancho de la impresora */
        border-collapse: collapse; /* Fusiona los bordes de las celdas */
        font-size: 0.8em; /* Reducimos el tamaño de la fuente */
        margin: auto; /* Centramos la tabla horizontalmente */
    }

    /* Estilos para las celdas de la tabla específica */
    table#invoice-table td, table#invoice-table th {
        border: 1px solid #000; /* Añade bordes a las celdas */
        padding: 2px; /* Espaciado interno de las celdas */
        text-align: center; /* Centra el texto horizontalmente */
        max-width: 15%; /* Establece un ancho máximo para el contenido */
        overflow: hidden; /* Oculta el contenido que exceda el ancho máximo */
        white-space: nowrap; /* Evita el salto de línea */
    }
</style>

<form method="get" action="#" id="printJS-form">
    <div id="myDiv" style="display: none">
        <table id="invoice-table">
            <!-- Contenido de la factura -->
            <tr>
                <td colspan="4" align="center">
                    <strong>FACTURA ELECTRÓNICA FACTECU</strong><br>
                    {{ entity.empresa.nombrecomercial }}
                </td>
            </tr>
            <tr>
                <td colspan="4" align="center">
                    <strong>Datos Emisor:</strong><br>
                    {{ entity.empresa.razonsocial }}<br>
                    RUC: {{ entity.empresa.ruc }}<br>
                    Correo: {{ entity.empresa.email }}<br>
                    Teléfono: {{ entity.empresa.telefono }}<br>
                    Dirección: {{ entity.empresa.direstablecimiento }}
                </td>
            </tr>
            <tr>
                <td colspan="4" align="center">
                    <strong>Datos Cliente:</strong><br>
                    Factura Número: {{ entity.serie }} - {{ entity.label }}<br>
                    Fecha: {{ entity.issueDate |date("d/m/Y") }}<br>
                    Cliente: {{ entity.customer_name }}<br>
                    RUC / Cédula: {{ entity.customer_identification }}<br>
                    Dirección: {{ entity.invoicing_address|nl2br }}<br>
                    Email: {{ entity.customer_email }}
                </td>
            </tr>
            <tr>
                <th>Qty</th>
                <th>Description</th>
                <th>Unit Cost</th>
                <th>Total</th>
            </tr>
            {% for item in entity.items %}
                <tr>
                    <td>{{ item.quantity }}</td>
                    <td>{{ item.description }}</td>
                    <td>{{ item.unitary_cost|localizedcurrency(currency, app.request.locale) }}</td>
                    <td>{{ (item.quantity * item.unitary_cost)|localizedcurrency(currency, app.request.locale) }}</td>
                
                </tr>
            {% endfor %}
            <tr>
                <td colspan="3" align="right">SUBTOTAL:</td>
                <td align="right">{{ entity.baseAmount|localizedcurrency(currency, app.request.locale) }}</td>
            </tr>
            <tr>
                <td colspan="3" align="right">IVA:</td>
                <td align="right">{{ entity.taxAmount|localizedcurrency(currency, app.request.locale) }}</td>
            </tr>
            <tr>
                <td colspan="3" align="right">TOTAL:</td>
                 <td align="right">{{ entity.grossAmount|localizedcurrency(currency, app.request.locale) }}</td>
           
            </tr>
            <tr>
                
                  <td colspan="4" align="center">
    <strong>Clave acceso:</strong><br>{{ entity.claveAcceso | slice(0,25) }}...<br>
    Consultar factura electrónica: <a href="https://n9.cl/wugq">https://n9.cl/wugq</a><br>
    <strong>Contratar Facturación electrónica:</strong><br>
    <a href="www.factecu.com">www.factecu.com</a><br>
    <strong>Gracias por su compra.</strong>
</td>
            </tr>
        </table>
    </div>
</form>
  
        
</FONT>
    <script>

        function PrintDiv(id) {
            var data = document.getElementById(id).innerHTML;
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload = function () { // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }


        function imprimir(pdf_url) {
            //e.preventDefault(); // if you have a URL in the link
            $("#myDiv").show();// and $("#dv1").hide();
            printJS({printable: 'printJS-form', type: 'html', style: '.rowtotal { left: 200px; position: relative; }' })
            $("#myDiv").hide();
            //window.print();

            /*$("#pdfFrame").contents().find("body").html("");
            */
            /*
                        var settings = {
                            "url": "http://localhost:8087/jsonprint",
                            "method": "POST",
                            "timeout": 0,
                            "headers": {
                                "Content-Type": "application/json",
                                "Accept": "application/json",
                                "Access-Control-Allow-Origin": "*",
                                "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
                                "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
                                "Access-Control-Allow-Credentials": "true"
                            },
                            "data": "{ 'email': 'james@example.com', 'nombre': 'nombre cliente', 'fecha': '01/07/2022', 'ruc': '1234578962', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'items': [ {'descripcion': 'james@example.com','cantidad': '1.00','unitario': '89.788'}, {'descripcion': 'james@example.com','cantidad': '1.00','unitario': '89.788'} ], 'basedoce': '12.58', 'basecero': '2.68', 'iva': '0.12', 'descuento': '1.00', 'total': '25.89', 'subtotal': '25.87' }",
                        };

                        $.ajax(settings).done(function (response) {
                            alert(response);
                        });
            */

            /* let url = "http://localhost:8087/jsonprint";
             $.ajax({
                 type: "POST",
                 url: url,
                 contentType: 'application/json; charset=utf-8',
                 dataType: 'json',
                 data: "{ 'email': 'james@example.com', 'nombre': 'nombre cliente', 'fecha': '01/07/2022', 'ruc': '1234578962', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'items': [ {'descripcion': 'james@example.com','cantidad': '1.00','unitario': '89.788'}, {'descripcion': 'james@example.com','cantidad': '1.00','unitario': '89.788'} ], 'basedoce': '12.58', 'basecero': '2.68', 'iva': '0.12', 'descuento': '1.00', 'total': '25.89', 'subtotal': '25.87' }",
                 success: function (data) {
                     if(data.error === true)
                         alert(data.message);
                     else
                         console.log(data.message);
                 },
                 error: function (ui) {
                     console.log(data.responseText);
                 },
                 async: true,
                 beforeSend: function () {
                     //$body.addClass("loading");
                 },
                 complete: function () {

                 },
             });

 */

        };
    </script>
{% endblock %}