<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title><?php echo $productoDesc;?></title>

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
        <style>
            .kardex-table{
                font-size: 10pt;
            }
            .kardex-table tr td{
                padding: 4px;
            }
        </style>
    </head>
    <body>
        <div class="text-center">
            <button class="btn btn-info" id="export-btn">Exportar</button>
        </div>
        <div class="m-3" id="kardex-wrapper">
            <!--header-->
            <div class="text-center">
                <h2><?php echo $nombreComercial?></h2>
                <h3><?php echo $razonSocial?></h3>
                <span>NIT: <?php echo $nit?> NRC: <?php echo $nrc?></span>
                <h5>KARDEX DE PRODUCTOS <?php echo ( $inicio ? "DEL ".date("d/m/Y", strtotime($inicio)) : "").( $final ? " AL ".date("d/m/Y", strtotime($final)) : "")?></h5>   
            </div>
            <hr>
            <div class="row mb-2">
                <div class="col-sm-2"><label><b>SKU:</b> <?php echo $productoSku;?></div>
		        <div class="col-sm-6"><label><b>Producto:</b> <?php echo $productoDesc;?></div>
		        <div class="col-sm-4"><label><b>Unidad: </b> <?php echo $productoUMed;?></label></div>
            </div>
            <!--Table-->
            <table class="table table-striped kardex-table">
                <thead>
                    <tr class="table-secondary">
                        <th rowspan="2">#</th>
                        <th rowspan="2">Fecha</th>
                        <th rowspan="2">Concepto</th>
                        <th rowspan="2">Proveedor</th>
                        <th rowspan="2">Nacionalidad</th>
                        <th rowspan="2" class="border-end">Referencia</th>
                        <th colspan="3" class="text-center">Entradas</th>
                        <th colspan="3" class="text-center">Salidas</th>
                        <th colspan="3" class="text-center">Existencias</th>
                    </tr>
                    <tr class="table-secondary">
                        <th>Unidad</th>
                        <th>Costo Unit.</th>
                        <th>Costo Total</th>
                        <th>Unidad</th>
                        <th>Costo Unit.</th>
                        <th>Costo Total</th>
                        <th>Unidad</th>
                        <th>Costo Unit.</th>
                        <th>Costo Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $inventarioInicial=0;
                $costoPromedio=0;
                if($transacciones && count($transacciones)):
                    $printRow = true;
                    $counter = 0;
                    $saldo=0;
                    foreach($transacciones as $transaccion):
                        $proveedor = "";
                        $nacionalidadProv = "";
                        $refFolio = "";
                        $refLinea = "";

                        $saldo +=  $transaccion->entrada-$transaccion->salida;
                        /**Entradas */
                        if( $transaccion->trans == "entrada")
                        {
                            $concepto = isset($conceptos_entrada[$transaccion->concepto]) ? $conceptos_entrada[$transaccion->concepto] : " Desconocido (".$transaccion->concepto.")";
                            switch($transaccion->concepto){
                                case 0: /**Inventario inicial */
                                    if($inventarioInicial==0){
                                        $inventarioInicial=1;
                                        $costoPromedio=round($transaccion->costo, 4);
                                    }
                                break;
                                case 1: /**Compra */
                                    $concepto .= isset($doc_compra[$transaccion->documentoc]) ? " ".$doc_compra[$transaccion->documentoc] : " Desconocido (".$transaccion->documentoc.")";
								    $concepto .= $transaccion->numdocc !="" ? " No. ".$transaccion->numdocc : "";
                                    $proveedor = $transaccion->proveedor;
                                    $nacionalidadProv = "Salvadore&ntilde;a";
                                    $refFolio = $transaccion->folio;
                                    $refLinea = $transaccion->linea;
                                    /**Calculo de costo*/
                                    if($saldo - $transaccion->entrada>0){
                                        $costoPromedio=round(((($saldo - $transaccion->entrada)*$costoPromedio)+($transaccion->entrada*$transaccion->costo))/$saldo, 4);
                                        if($costoPromedio<0)
                                            $costoPromedio=round($transaccion->costo, 4);
                                    }else{
                                        $costoPromedio=round($transaccion->costo, 4);
                                    }
                                break;
                                case 2:/**Devolucion */
                                    $concepto .= isset($doc_venta[$transaccion->documentod]) ? " ".$doc_venta[$transaccion->documentod] : " Desconocido (".$transaccion->documentod.")";
                                    $concepto .= $transaccion->numdocd !="" ? " No. ".$transaccion->seried." ".$transaccion->numdocd : "";	
                                break;
                            }
                            
                        }
                        else/**Salidas */
                        {
                            $concepto = isset($conceptos_salida[$transaccion->concepto]) ? $conceptos_salida[$transaccion->concepto] : " Desconocido (".$transaccion->concepto.")";
                            if($transaccion->concepto == 0){ /**Ventas */
                                $concepto .= isset($doc_venta[$transaccion->documentov]) ? " ".$doc_venta[$transaccion->documentov] :  "Desconocido (".$transaccion->documentov.")";
                                $concepto .= $transaccion->numdocv !="" ? " No. ".$transaccion->seriev." ".$transaccion->numdocv : "";
                            }
                        }
                        
                        $fecha = date("d/m/Y",strtotime($transaccion->fecha));
                        $entradaCant = ($transaccion->entrada>0?number_format($transaccion->entrada,4):"");
                        $entradaCosto = ($transaccion->entrada>0?number_format($transaccion->costo,4):"");
                        $entradaCTotal = ($transaccion->entrada>0?number_format(($transaccion->entrada*$transaccion->costo),4):"");
                        $salidaCant = ($transaccion->salida>0?number_format($transaccion->salida,4):"");
                        $salidaCosto = ($transaccion->salida>0?number_format($costoPromedio,4):"");
                        $salidaCTotal = ($transaccion->salida>0?number_format(($transaccion->salida*$costoPromedio),4):"");
                        $existenciaCant = number_format($saldo,4);
                        $existenciaCosto = number_format($costoPromedio,4);
                        $existenciaCTotal = number_format(($saldo*$costoPromedio),4);
                        if($printRow):
                            $counter ++;  
                            
                ?>
                    <tr>
                        <td class=""><?php echo ($counter > 0 ? $counter : ""); ?></td>
                        <td class=""><?php echo $fecha;?></td>
                        <td class="border-end"><?php echo $concepto;?></td>
                        <td class=""><?php echo $proveedor;?></td>
                        <td class=""><?php echo $nacionalidadProv;?></td>
                        <td class="border-end"><?php echo ($refFolio !="" ? "Libro compras folio: ".$refFolio: "").($refLinea != "" ? " linea: ".$refLinea : "");?></td>
                        <td class=""><?php echo $entradaCant;?></td>
                        <td class=""><?php echo $entradaCosto;?></td>
                        <td class="border-end"><?php echo $entradaCTotal;?></td>
                        <td class=""><?php echo $salidaCant;?></td>
                        <td class=""><?php echo $salidaCosto;?></td>
                        <td class="border-end"><?php echo $salidaCTotal;?></td>
                        <td class=""><?php echo $existenciaCant;?></td>
                        <td class=""><?php echo $existenciaCosto;?></td>
                        <td class="border-end"><?php echo $existenciaCTotal;?></td>
                    </tr>

                <?php 
                    endif;endforeach; else:?>
                    <span>No se hay transacciones para el producto en el periodo</span>
                <?php endif;?>
                </tbody>
            </table>
            <!--footer-->
            <div class="row mt-5">
                <div class="col text-center">
                    <span>F:__________________________________</span><br>
                    <span>__________________________________</span><br>
                    <span>Propietario/a, representante legal o apoderado/a.</span>
                </div>
                <div class="col text-center">
                    <span>F:__________________________________</span><br>
                    <span>__________________________________</span><br>
                    <span>Contador/a.</span>
                </div>
            </div>
        </div>
    </body>
    <script>
        $(document).ready(function(){
            window.jsPDF = window.jspdf.jsPDF;
       
            var doc = new jsPDF({
                orientation: 'landscape'
            });
            var elementHTML = document.querySelector("#kardex-wrapper");
            $("#export-btn").click(function(){
                doc.html(elementHTML, {
                    callback: function(doc) {
                        doc.save('example.pdf');
                    },
                    x: 15,
                    y: 15,
                    width: 170, //target width in the PDF document
                    windowWidth: 650 //window width in CSS pixels

                });

               /* html2canvas(document.querySelector("#kardex-wrapper")).then(canvas => {
                    var imgData = canvas.toDataURL('image/png', 1);
                    doc.addImage(imgData, 'PNG', 10, 10, 190, 293);
                    doc.save('example.pdf');
                });*/
            });
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js" integrity="sha512-qZvrmS2ekKPF2mSznTQsxqPgnpkI4DNTlrdUmTzrDgektczlKNRRhy5X5AAOnx5S09ydFYWWNSfcEqDTTHgtNA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.0/purify.min.js" integrity="sha512-Ijc86Y/rPOFCr+CJLd0QQlEaCC9ztVJFvPzK0DMrHCJ8biDkyQoo6Ll/OmqMEOaDJ2nCgsV89402SzXnocKzZg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</html>