<?php

 @session_start();

if(!isset($_SESSION['PCOSESS_SesionAbierta'])) {
	echo '<head><title>Error</title><style type="text/css"> body { background-color: #000000; color: #7f7f7f; font-family: sans-serif,helvetica; } </style></head><body><table width="100%" height="100%" border=0><tr><td align=center>&#9827; Acceso no autorizado !</td></tr></table></body>';
	die();
}

/*include_once '../../core/configuracion.php';
include_once '../../core/conexiones.php';
include_once '../../inc/practico/def_basedatos.php';
include_once '../../core/comunes.php';*/

//echo "$builder";
$saldoFavor = $factura["saldo_pendiente"] < 0 ? -$factura["saldo_pendiente"] : 0;
$saldoPendienteValor = $factura["saldo_pendiente"] > 0 ? $factura["saldo_pendiente"] : 0;
$saldoPendiente = number_format($saldoPendienteValor, 0, ',', '.');

$descargar = 0;
if ($PCO_Accion == "FACTURAS_descargarFactura")
    $descargar = 1;
$fechaSinRecargoBr = str_replace("-", "", $factura["fecha_sin_recargo"]);
$totalValor =  number_format($factura["valor_sin_recargo"] + $saldoPendienteValor - $saldoFavor, 0, ',', '.');
$total = $totalValor > 0 ? $totalValor : 0;
$totalBr = str_replace(".", "", $total);
$codigobarra="7709998678439";
$Barcode = $codigobarra.$factura["id_contrato"]."$totalBr96$fechaSinRecargoBr";
$BarcodeParent = "(415)$codigobarra(8020)" . $factura["id"] . "(3900)$totalBr(96)$fechaSinRecargoBr";
//$Barcode = "(415)7709998678439(8020)12345(3900)50000(96)20220524";
//$Barcode = "41577099986784398020123453900500009620220524";
//$Barcode = "12345670";

$rayaDesprendibleBanco = str_repeat("- ", 34);

$estadoMedidor = "Bueno";
if($factura["estado_medidor"] == 2) $estadoMedidor = "Dañado";
if($factura["estado_medidor"] == 3) $estadoMedidor = "N/A";

function getMesEsp($mes) {
    $mesesArray = ["","Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"];
    return $mesesArray[$mes];
}
$i = 1;
$grafBarra = "";
$tableData = "";
$class = "";

$consumos = PCO_EjecutarSQL("SELECT consumo_actual, MONTH(fecha_fin_facturacion) mes, valor_sin_recargo, saldo_pendiente, valor_tarifa_aplicada
    FROM 
        app_facturas
    WHERE 
        id_contrato = ". $factura["id_contrato"]. " ORDER BY id DESC LIMIT 6
")->fetchAll();

foreach ($consumos as $consumo) {
    $mes = getMesEsp($consumo["mes"]);
    $totalMes =  number_format($consumo["valor_sin_recargo"], 0, ',', '.');
    $grafBarra .= '<div class="barra"><div class="sub_barra b' . $i . '"><div class="tag_g">' . $consumo["consumo_actual"] . '</div><div class="tag_leyenda">' . $mes . '</div></div></div>';
    $tableData .= '<tr><td>' . $mes . '</td><td>' . $consumo["consumo_actual"] . '</td><td>' . $consumo["valor_tarifa_aplicada"] . '</td><td>' . $totalMes . '</td></tr>';
    $class .= ".b$i { height: " . (is_numeric($consumo["consumo_actual"]) ? $consumo["consumo_actual"] : 0) . "%} ";
    $i++;
}

$html = '
<html>

<head>
   <meta charset="utf-8">
   <title>Factura</title>
   <style>
      * {
         border: 0;
         box-sizing: content-box;
         color: inherit;
         font-family: Verdana;
         font-size: inherit;
         font-style: inherit;
         font-weight: inherit;
         list-style: none;
         padding: 0;
         text-decoration: none;
      }

    table.info, 
    .info td,
    .info tr {
        border-width: 0px !important;
        border-style: none;
        text-align:left
    }
      /* heading */

      h1 {
         font: bold 100% sans-serif;
         letter-spacing: 0.5em;
         text-align: center;
         text-transform: uppercase;
      }

      /* table */

      table {
         font-size: 75%;
         table-layout: fixed;
         width: 100%;
      }

      table {
         border-collapse: separate;
      }

      th,
      td {
         border-width: 1px;
         padding: 0.56em;
         position: relative;
         text-align: center;
      }

      th,
      td {
         border-radius: 0.25em;
         border-style: solid;
      }

      th {
         background: #1f60a0;
         color: #fff;
         border-color: #BBB;
      }

      td {
         border-color: #DDD;
      }

      /* page */

      html {
         font: 16px/1 "Open Sans", sans-serif;
         overflow: auto;
         padding: 0.4in;
      }

      html {
         background: #999;
         cursor: default;
      }

      body {
         box-sizing: border-box;
         height: 11in;
         margin: 0 auto;
         overflow: hidden;
         padding: 0.5in;
         width: 8.5in;
      }

      body {
         background: #FFF;
         border-radius: 1px;
         box-shadow: 0 0 1in -0.25in rgba(0, 0, 0, 0.5);
      }

      /* header */

      header {
         margin: 0 0 3em;
      }

      header:after {
         clear: both;
         display: table;
      }

      header h1 {
         background: #000;
         border-radius: 0.25em;
         color: #FFF;
         margin: 0 0 1em;
         padding: 0.4em 0;
      }

      header address {
         float: left;
         font-size: 75%;
         font-style: normal;
         line-height: 1.25;
         margin: 0 1em 1em 0;
      }

      header address p {
         margin: 0 0 0.25em;
      }

      header span,
      header img {
         display: block;
         float: right;
      }

      header span {
         margin: 0 0 1em 1em;
         max-height: 25%;
         max-width: 60%;
         position: relative;
      }

      header img {
         max-height: 100%;
         max-width: 100%;
      }

      header input {
         cursor: pointer;
         -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
         height: 100%;
         left: 0;
         opacity: 0;
         position: absolute;
         top: 0;
         width: 100%;
      }

      /* article */

      article,
      article address,
      table.meta,
      table.inventory {
         margin: 0 0 0.3em;
      }

      article:after {
         clear: both;
         content: "";
         display: table;
      }

      article h1 {
         clip: rect(0 0 0 0);
         position: absolute;
      }

      article address {
         float: left;
         font-size: 30%;
      }

      /* table meta & balance */

      table.meta,
      table.balance {
         float: right;
         width: 38%;
      }

      table.meta:after,
      table.balance:after {
         clear: both;
         display: table;
      }

      /* table meta */

      table.meta th {
         width: 40%;
      }

      table.meta td {
         width: 60%;
      }

      /* table items */

      table.inventory {
         clear: both;
         width: 100%;
      }

      table.inventory th {
         font-weight: bold;
         text-align: center;
      }

      table.inventory td:nth-child(1) {
         width: 26%;
      }

      table.inventory td:nth-child(2) {
         width: 38%;
      }

      table.inventory td:nth-child(3) {
         text-align: center;
         width: 12%;
      }

      table.inventory td:nth-child(4) {
         text-align: center;
         width: 12%;
      }

      table.inventory td:nth-child(5) {
         text-align: center;
         width: 12%;
      }

      /* table balance */

      table.balance th {
         width: 40%;
         text-align: center;
      }

      table.balance td {
         width: 60%;
         text-align: center;
      }

      /* aside */

      aside h1 {
         border: none;
         border-width: 0 0 1px;
         margin: 0 0 1em;
      }

      aside h1 {
         border-color: #999;
         border-bottom-style: solid;
      }

      /* javascript */

      @media print {
         * {
            -webkit-print-color-adjust: exact;
         }

         html {
            background: none;
            padding: 0;
         }

         body {
            box-shadow: none;
            margin: 0;
         }

         span:empty {
            display: none;
         }
      }

      @page {
         margin: 0;
      }
      
.board{
    width: 100%;
    height: 160px;
    box-sizing: border-box;
    overflow: hidden;
}
.titulo_grafica{
    width: 100%;
    height: 10%;
}
.titulo_grafica>h3{
    padding: 0;
    margin: 0px;
    text-align: center;
    color: #666666;
}
.sub_board{
    width: 100%;
    height: 100%;
    margin-top: 0px;
    overflow: hidden;
    box-sizing: border-box;
}
.sep_board{
    width: 100%;
    height: 10%;
}
.cont_board{
    width: 100%;
    height: 80%;
}
.graf_board{
    width: 90%;
    height: 100%;
    float: right;
    margin-top: 0px;
    background-color: darkgrey;
    border-left: 2px solid #999999;
    border-bottom: 2px solid #999999;
    box-sizing: border-box;
    display: flex;
    background: -moz-linear-gradient(top, rgba(0,0,0,0) 0%, 
 
    rgba(0,0,0,0) 100%);
    background: -webkit-linear-gradient(top, rgba(0,0,0,0) 0%, 
    rgba(0,0,0,0) 100%);

    background: linear-gradient(to bottom, rgba(0,0,0,0) 0%,
    rgba(0,0,0,0) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr="#00ffffff", endColorstr="#00ffffff",GradientType=0 );
}
.barra{
    width:100%;
    height: 100%;
    margin-right: 9px;
    margin-left: 9px;
    background-color: none;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
}
.sub_barra{
    width: 100%;
    height: 80%;
    background: #00799b;
    background: -moz-linear-gradient(top, #00799b 0%, #64d1be 100%);
    
    -webkit-border-radius: 12px 12px 0 0;
    border-radius: 12px 12px 0 0;
}
.tag_g{
    position: relative;
    width: 100%;
    height: 100%;
    margin-bottom: 23px;
    text-align: center;
    margin-top: -20px;
    z-index: 2;
}
.tag_leyenda{
    text-align: center;
    margin-top: 0px;
}
.tag_board{
    height: 100%;
    width: 15%;
    border-bottom: 2px solid rgba(0,0,0,0);
    box-sizing: border-box;
}
.sub_tag_board{
    height: 85%;
    width: 60%;
    display: flex;
    align-items: flex-end;
    flex-wrap: wrap;
}
.sub_tag_board>div{
    width: 100%;
    height: 3%;
    text-align: right;
    padding-right: 3px;
    box-sizing: border-box;
}
'.$class.'
footer{
    position: absolute;
    bottom: 0px;
    width: 100%;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
}
   </style>

    <script type="text/javascript" src="inc/bwip/bwip-js-min.js"></script>
    
    <link rel="stylesheet" href="inc/pdfLib/all.min.css">
    <script type="text/javascript" src="inc/pdfLib/html2pdf.bundle.min.js"></script>
    
            <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">-->
            <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"
              integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg=="
              crossorigin="anonymous" referrerpolicy="no-referrer"></script>-->
      <!-- BARCODE -->
        <!--<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"></script>-->
        
		
	
		
</head>

<body id="Invoices">
   <article>
      <img
         src="data:image/png;base64,[encoded data, 74668 characters]"
         data-filename="logoASJ_.png">
      <!--<img src="./logoASJ_.png">-->
      <BR>
      <BR>
      <address style="width: 62%;">
         <div style="color:#14406b; font-size: 18px; font-weight: bold;">AGUAS DE SAN JERONIMO E.S.P</div>
         <div style="font-size: 12px;">NIT: 811018300-6</div>
         <div style="font-size: 12px;">CLL 21 # 8-78 San Jerónimo, Ant</div>
         <BR>
         <table class="info">
            <tr>
                <td>
                    <p style="font-size: 14px;">
                        <span style="font-weight: bold;">Contrato N° </span> ' . $factura["id_contrato"] . ' <br>
                        <span style="font-weight: bold;">Nombre: </span>' . $factura["nombres"] . ' ' . $factura["apellidos"] . ' <br>
                        <span style="font-weight: bold;">Vereda: </span>' . $factura["zona"] . ' <br>
                        <span style="font-weight: bold;">Dirección: </span>' . $factura["direccion_predio"] . ' <br>
                        <span style="font-weight: bold;">Estrato: </span>' . $factura["estrato"] . ' <br>
                        <span style="font-weight: bold;">Consumo Periodo: </span>' . $factura["fecha_inicio_facturacion"] . ' - ' . $factura["fecha_fin_facturacion"] . ' <br>
                    </p>
                </td>
                <!--<td>

                </td>-->
            </tr>
         </table>

      </address>

      <table class="meta">
         <tr>
            <th style="width: 120px !important;"><span>Factura</span></th>
            <td><span>' . $factura["id"] . '</span></td>
         </tr>
         <tr>
            <th><span>Fecha sin recargo</span></th>
            <td><span>' . $factura["fecha_sin_recargo"] . '</span></td>
         </tr>
         <tr>
            <th><span>Fecha con recargo</span></th>
            <td><span>' . $factura["fecha_con_recargo"] . '</span></td>
         </tr>
      </table>
      <table class="info" style="border-collapse: collapse; border:none; border-width: 0px;">
        <tr>
            <td colspan="3" style="font-weight: bold;">INFORMACIÓN ACUEDUCTO</tr>
        </tr>
        <tr>
            <td>
                <p>
                    <span style="font-weight: bold;">Medidor </span> ' . $factura["numero_medidor"] . ' <br>
                    <span style="font-weight: bold;">Diametro </span> 1/2" <br>
                </p>
            </td>
            <td>
                <p>
                    <span style="font-weight: bold;">Lectura actual </span> ' . $factura["lectura_actual"] . ' <br>
                    <span style="font-weight: bold;">Lectura anterior </span> ' . $factura["lectura_anterior"] . ' <br>
                </p>
            </td>
            <td>
                <p>
                    <span style="font-weight: bold;">Estado medidor </span> ' . $estadoMedidor. ' <br>
                    <span style="font-weight: bold;">Consumo (m3)</span> ' . $factura["consumo_actual"] . ' <br>
                </p>
            </td>
        </tr>
      </table>
      <table style="border-collapse: collapse; border:none; border-width: 0px;">
          <tr>
            <td width="50%" style="border-collapse: collapse; border:none; border-width: 0px; vertical-align: none !important;">
              <table style="border-collapse: collapse; border:none; border-width: 0px;">
              
                <tr>
                  <th>MES</th>
                  <th>M3</th>
                  <th>CARGO FIJO</th>
                  <th>TOTAL</th>
                </tr>
                ' . $tableData . '
              </table>
            </td>
            <td width="50%" style="border-collapse: collapse; border:none; border-width: 0px;">
               <div class="board">
                <div class="titulo_grafica">
                    <h3 class="t_grafica">Consumos anteriores en metros cúbicos</h3>
                </div>
                <div class="sub_board">
                    <div class="cont_board">
                        <div class="graf_board">
                            ' . $grafBarra . '
                        </div>
                        <div class="tag_board">
                            <div class="sub_tag_board">
                                <div>100</div>
                                <div>90</div>
                                <div>80</div>
                                <div>70</div>
                                <div>60</div>
                                <div>50</div>
                                <div>40</div>
                                <div>30</div>
                                <div>20</div>
                                <div>10</div>
                            </div>
                        </div>
                   </div>
                </div>
               </div>
            </td>
          </tr>
      </table>
      <table class="info" style="border-collapse: collapse; border:none; border-width: 0px;">
        <tr>
            <td colspan="3" style="font-weight: bold;">COSTOS REFERENCIA ACUEDUCTO</tr>
        </tr>
        <tr>
            <td>
                <p>
                    
                    <span>Cargo Fijo. = ' . $factura["valor_tarifa_aplicada"] . '</span>
                </p>
            </td>
            <td>
                <p>
                    
                    <span>CMO=Costo por consumo = ' . $factura["costo_medio_operacion"] . '</span>
                </p>
            </td>
           
        </tr>
      </table>
      <!--<table class="inventory">
         <thead>
            <tr>
               <th><span>Descripción</span></th>
               <th><span>Cantidad</span></th>
               <th style="background-color: #14406b;"><span>Precio</span></th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td><span>Consumo de agua m3</span></td>
               <td><span>' . $factura["consumo_actual"] . '</span></td>
               <td style="text-align: center !important;"><span data-prefix>$</span><span>' . number_format($factura["valor_sin_recargo"], 0, ',', '.') . '</span></td>
            </tr>
         </tbody>
      </table> -->

      <table class="balance" style="font-size: 11px;">
         <tr>
            <td><span>SUBTOTAL</span></td>
            <th><span data-prefix>$</span><span>' . number_format($factura["valor_sin_recargo"] + $factura['valor_subsidio'] + $factura['valor_subsidio_cargo_fijo'], 0, ',', '.') . '</span></th>
         </tr>
         <tr>
            <td><span>CUENTAS VENCIDAS</span></td>
            <th><span data-prefix>$</span><span>' . $saldoPendiente . '</span></th>
         </tr>
         <tr>
            <td><span>SALDO A FAVOR</span></td>
            <th><span data-prefix>$</span><span>' . number_format($saldoFavor, 0, ',', '.') . '</span></th>
         </tr>
         <tr>
            <td><span>SUBSIDIO</span></td>
            <th><span data-prefix>$</span><span>' . number_format($factura['valor_subsidio'] + $factura['valor_subsidio_cargo_fijo']) . '</span></th>
         </tr>
         <tr style="color: #fff; font-size: 16px;">
            <td style="background-color: #1f60a0; font-weight: bold;"><span>TOTAL</span></td>
            <th style="background-color: #14406b;"><span data-prefix>$</span><span>' . $total . '</span></th>
         </tr>
      </table>
     <address style="width: 62%;">
      <table>
            <tr>
               <td style="border-radius: 0 !important; border-style: none !important;">
                  <p style="font-size: 13px; vertical-align: middle; line-height: normal">
                     <span style="font-weight: bold;"> Canales y medios disponibles para hacer el pago de tu
                        factura</span>
                     <br>
                     <br>
                     <span>Transferencia o consignación a la cuenta de:</span>
                     <br>
                     <br>
                     <span style="font-weight: bold;">Ahorros Bancolombia N°</span>
                     <br>
                     <br>
                     <span style="font-weight: bold;">240-000018-93</span>
                  </p>
               </td> 
               <td style="border-radius: 0 !important; border-style: none !important;">
                    <img src="data:image/png;base64,[encoded data, 21620 characters]" data-filename="Firma Ignacio Digital.png"
                    data-filename="Firma Ignacio Digital.png" style="width: 220px; height: 70px;">
                    <p style="font-size: 10.3px; font-weight: bold;">JORGE IGNACIO AREIZA CASTRILLON <BR> GERENTE</p>
               </td>
            </tr>
         </table> 

      <BR>
       </address> 
   </article>
   <BR>
   <p style="font-size:10px;">' . $rayaDesprendibleBanco . ' DESPRENDIBLE PARA EL BANCO ' . $rayaDesprendibleBanco . '</p>
   <table style="border-collapse: collapse; border:none; border-width: 0px; style="vertical-align: middle !important;">
        <tr style="float: middle; !important;">
            <td style="border-radius: 0 !important; border-style: none !important; vertical-align: middle !important; width: 30%">
                <img 
                	<img src="data:image/png;base64,[encoded data, 32188 characters]"
	                style="width: 208px;" data-filename="Logo2.png">
            </td>
            <td style="border-radius: 0 !important; border-style: none !important; vertical-align: middle !important; width:70%">
                <img id="barcodeTarget"/>
                
            </td>
        </tr>
    </table>
</body>
    <script>
        //https://parzibyte.me/blog/2019/08/19/codigos-barras-javascript-jsbarcode/
        addEventListener("DOMContentLoaded", () => {
            try {
               // The return value is the canvas element
                const canvas = document.createElement("canvas");
    
                const options = {
                    bcid:        "code128",       // Barcode type
                    text:        "0123456789",    // Text to encode
                    scale:       3,               // 3x scaling factor
                    height:      10,              // Bar height, in millimeters
                    includetext: true,            // Show human-readable text
                    textxalign:  "center",        // Always good to set this
                };
                bwipjs(canvas, options, (err, cvs) => {
                    if (err) {
                        console.log({err});
                    } else {
                    console.log({cvs});
                        // Dont need the second param since we have the canvas in scope...    
                        document.getElementById("barcodeTarget").src = canvas.toDataURL("image/png");
                    }
                });
            } catch (e) {
                console.log({e});
                // `e` may be a string or Error object
            }     
        });

         /* JsBarcode("#barcodeTarget", "' . $Barcode. '", {
            format: "CODE128C",// El formato
    		width: 2.67, // La anchura de cada barra
    		height: 65, // La altura del código
    		displayValue: true, // ¿Mostrar el valor (como texto) del código de barras?
    		text: "' . $BarcodeParent . '", // Texto (no código) que acompaña al barcode
    		fontSize: 14, // Tamaño de la fuente
    		fontOptions: "bold", // Opciones de la fuente del texto del barcode
    		ean128: true,
    	}); */
		</script>
   <script> 
      document.addEventListener("DOMContentLoaded", function (event) {
        //setTimeout(function(){ hola(); }, 1000);
        var descargar = ' . $descargar . ';
        if(descargar == 1) {
             var element = document.getElementById("Invoices");
             
             var opt = {
                filename: "' . str_replace(' ', '', $factura["nombres"] . ' ' . $factura["apellidos"]) . '.pdf",
                image: { type: "jpeg", quality: 0.98 },
                html2canvas: { scale: 2, useCORS: true, letterRendering: true },
                jsPDF: { unit: "mm", format: "letter", orientation: "portrait" }
             };
    		 html2pdf(element, opt);
    		 setTimeout(function(){ window.close(); }, 1650);
        }
        });
        
        function hola(){
            var element = document.getElementById("Invoices");
             
             var opt = {
                filename: "' . $factura["contrato"] . '.pdf",
                image: { type: "jpeg", quality: 0.98 },
                html2canvas: { scale: 2, useCORS: true, letterRendering: true },
                jsPDF: { unit: "mm", format: "letter", orientation: "portrait" }
             };
    		 html2pdf(element, opt);
        }
   </script>
</html>';

echo $html;
die();