<?php
require('general/plugin/mpdf-master/mpdf.php');
//libreria necesaria para excel
require_once('Classes\PHPExcel.php');
class resumen_cuenta extends main_controller
{
    function excel()
    {
        $usuario = $_POST['usuario'];
        $desde = $_POST['desde'];
        $hasta = $_POST['hasta'];
        $cc = $_POST['cc'];
        $remito = $_POST['remito'];
        $contado = $_POST['contado'];
        $anulada = $_POST['anulada'];
        $orden = $_POST['orden'];
        $tipoana = $_POST['tipoana'];
        $remitoPrecioActual = $_POST['remitoPrecioActual'];
        FLAG_HO == false ? $empresa = $_POST['codEmp'] : $empresa = '';

        list($d, $m, $y) = explode("-", $desde);
        $desde = mktime(0, 0, 0, $m, $d, $y);

        list($d, $m, $y) = explode("-", $hasta);
        $hasta = mktime(0, 0, 0, $m, $d, $y);

        //trae los datos segun si es resumen o analisis de deuda
        if ($tipoana == "resumen") {
            $data['comprobantes'] = $this->mod->get_datos_res($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa, $remitoPrecioActual);
        } else if ($tipoana == "analisis") {
            $data['comprobantes'] = $this->mod->get_datos_ana($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa, $remitoPrecioActual);
        }
        $contador = count($data['comprobantes']['ret']) + 3;

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //modifica el ancho de cada columna
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(7);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(7);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        //cambia las comas por puntos para que el valor de los numeros no sea texto
        $data['comprobantes']['saldos']['rpe'] = str_replace(',', '.', $data['comprobantes']['saldos']['rpe']);
        //encabezados
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Fecha')
            ->setCellValue('B1', 'Comprobante')
            ->setCellValue('C1', 'FPA')
            ->setCellValue('D1', 'TCO')
            ->setCellValue('E1', 'Debito')
            ->setCellValue('F1', 'Credito')
            ->setCellValue('G1', 'Saldo')
            ->setCellValue('H1', 'Rtos.Pend')
            ->setCellValue('I1', 'Observaciones')
            ->setCellValue('J1', 'Vencimientos')
            ->setCellValue('K1', 'Conductor')
            ->setCellValue('L1', 'Vehiculo');
        //si es resumen coloca el segundo encabezado
        if ($tipoana == "resumen") {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A2', 'Saldo al: ' . $data['comprobantes']['saldos']['desde'])
                ->setCellValue('H2', $data['comprobantes']['saldos']['rpe']);
        }
        $j = 0;
        //empieza a rellenar el excel con datos
        for ($i = 3; $i < $contador; $i++) {
            //quita los espacios en blanco
            $comprobar = empty($data['comprobantes']['ret'][$j]);
            while($comprobar == 1){
                $j++;
                $contador--;
                $comprobar = empty($data['comprobantes']['ret'][$j]);
            }
            //cambia las comas por puntos para que el valor de los numeros no sea texto
            $data['comprobantes']['ret'][$j]['DEB'] = str_replace(',', '.', $data['comprobantes']['ret'][$j]['DEB']);
            $data['comprobantes']['ret'][$j]['CRED'] = str_replace(',', '.', $data['comprobantes']['ret'][$j]['CRED']);
            $data['comprobantes']['ret'][$j]['SAL'] = str_replace(',', '.', $data['comprobantes']['ret'][$j]['SAL']);
            //indica la pagina activa
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $i, $data['comprobantes']['ret'][$j]['fep']->date)
                ->setCellValue('B' . $i, $data['comprobantes']['ret'][$j]['ncNCO'])
                ->setCellValue('C' . $i, $data['comprobantes']['ret'][$j]['fpa'])
                ->setCellValue('D' . $i, $data['comprobantes']['ret'][$j]['tco_o'])
                ->setCellValue('E' . $i, $data['comprobantes']['ret'][$j]['DEB'])
                ->setCellValue('F' . $i, $data['comprobantes']['ret'][$j]['CRED'])
                ->setCellValue('G' . $i, $data['comprobantes']['ret'][$j]['SAL'])
                ->setCellValue('I' . $i, $data['comprobantes']['ret'][$j]['obs'])
                ->setCellValue('J' . $i, $data['comprobantes']['ret'][$j]['ven'])
                ->setCellValue('K' . $i, $data['comprobantes']['ret'][$j]['DET1'])
                ->setCellValue('L' . $i, $data['comprobantes']['ret'][$j]['DET3']);
            $j++;
        }
        //cambia las comas por puntos para que el valor de los numeros no sea texto
        $data['comprobantes']['totales']['deb'] = str_replace(',', '.', $data['comprobantes']['totales']['deb']);
        $data['comprobantes']['totales']['cre'] = str_replace(',', '.', $data['comprobantes']['totales']['cre']);
        $data['comprobantes']['totales']['sal'] = str_replace(',', '.', $data['comprobantes']['totales']['sal']);
        $data['comprobantes']['totales']['rtos'] = str_replace(',', '.', $data['comprobantes']['totales']['rtos']);
        //pie del excel
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A' . $contador, 'Totales al: ' . $data['comprobantes']['totales']['hasta'])
            ->setCellValue('E' . $contador, $data['comprobantes']['totales']['deb'])
            ->setCellValue('F' . $contador, $data['comprobantes']['totales']['cre'])
            ->setCellValue('G' . $contador, $data['comprobantes']['totales']['sal'])
            ->setCellValue('H' . $contador, $data['comprobantes']['totales']['rtos'])
            ->setCellValue('I' . $contador, $data['comprobantes']['totales']['obs']);

        //comienza a pintar las casillas
        $objPHPExcel->getActiveSheet()
            ->getStyle('A1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('B1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('C1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('D1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('E1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('F1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('G1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('H1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('I1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('J1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('K1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');
        $objPHPExcel->getActiveSheet()
            ->getStyle('L1')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#86D3FA');

        $objPHPExcel->getActiveSheet()
            ->getStyle('A2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('B2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('C2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('D2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('E2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('F2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('G2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('H2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('I2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('J2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('K2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('L2')
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');

        $objPHPExcel->getActiveSheet()
            ->getStyle('A' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('B' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('C' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('D' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('E' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('F' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('G' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('H' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('I' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('J' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('K' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');
        $objPHPExcel->getActiveSheet()
            ->getStyle('L' . $contador)
            ->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('#3DC7F8');

        //titulo del documento
        if ($tipoana == "resumen") {
            $objPHPExcel->getActiveSheet()->setTitle('Resumen de cuenta');
        } else if ($tipoana == "analisis") {
            $objPHPExcel->getActiveSheet()->setTitle('Analisis de deuda');
        }
        $objPHPExcel->setActiveSheetIndex(0);
        //encabezados necesarios
        header('Content-Type: application/vnd.ms-excel');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        header('Content-Disposition: attachment;filename="resumen.xls"');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace('.php', '.xls', __FILE__));
        $fecha = date("Y-m-d");
        $hora = date("H");
        $minuto = date("i");
        if ($tipoana == "resumen") {
            rename("app_decode/resumen_cuenta/controller/resumen_cuenta.xls", "app_decode/resumen_cuenta/controller/ResumenCuenta" . $usuario . "_" . $fecha . ".xls");
        } else if ($tipoana == "analisis") {
            rename("app_decode/resumen_cuenta/controller/resumen_cuenta.xls", "app_decode/resumen_cuenta/controller/AnalisisDeuda" . $usuario . "_" . $fecha . ".xls");
        }
    }
    function limpiarExcel()
    {
        $fecha = date("Y-m-d");
        $hora = date("H");
        $minuto = date("i");
        $usuario = $_POST['usuario'];
        unlink("app_decode/resumen_cuenta/controller/ResumenCuenta" . $usuario . "_" . $fecha . ".xls");
        unlink("app_decode/resumen_cuenta/controller/AnalisisDeuda" . $usuario . "_" . $fecha . ".xls");
    }

    function __construct()
    {
        $this->mod = $this->model("datos_model");
    }

    function init()
    {
        //$this->_get_loged();
        $this->setCss(array("init.css"));
        $this->setJs(array("init.js"));

        $datax = array();
        $datax['main'] = $this->_obtener_main();
        $datax['titulo'] = "Administracion";
        $this->render($datax);
    }

    function _obtener_main()
    {
        //  $data['fecha'] = $this->mod->get_datos($user, $desde, $hasta);
        $data['codigo'] = $_SESSION['USER']['COD'];
        $data['nombre'] = $_SESSION['USER']['NOM'];
        FLAG_HO == false ? $data['domicilio'] = $_SESSION['USER']['DOM'] . " - " . $_SESSION['USER']['LOC'] . " - " . $_SESSION['USER']['PVC'] : $data['domicilio'] = $_SESSION['USER']['DOM'] . " - " . $_SESSION['USER']['LOC'] . " - " . $_SESSION['USER']['PCI'];
        $data['mcc'] = $_SESSION['USER']['MCC'];
        FLAG_HO == false ? $data['empresa'] = $this->mod->get_empresas() : '';
        return $this->view("main", $data);
    }

    function x_consultar_empresa_BO(){
        //inc608461 Para BO, capturamos el valor de la empresa
        $data = new sqldata();
        $empBO = $data->query("SELECT * FROM aparemp");

        header('Content-Type: application/json');

        if (is_array($empBO) && isset($empBO[0]['ZON'])) {
            echo json_encode($empBO);
        }
    }



    function x_enviar_datos() {
        $usuario = $_POST['usuario'];
        $desde = $_POST['desde'];
        $hasta = $_POST['hasta'];
        $cc = $_POST['cc'];
        $remito = $_POST['remito'];
        $contado = $_POST['contado'];
        $anulada = $_POST['anulada'];
        $orden = $_POST['orden'];
        $tipoana = $_POST['tipoana'];
        $remitoPrecioActual = $_POST['remitoPrecioActual'];
        FLAG_HO == false ? $empresa = $_POST['codEmp'] : $empresa = '';
        FLAG_HO == true ? $empresa = $_POST['codEmp'] : $empresa = '';

        list($d, $m, $y) = explode("-", $desde);
        $desde = mktime(0, 0, 0, $m, $d, $y);

        list($d, $m, $y) = explode("-", $hasta);
        $hasta = mktime(0, 0, 0, $m, $d, $y);

        // log_this('log/PARAMETRO.log', 'usuario ' . $usuario. ' desde '. $desde.' hasta ' . $hasta . ' cc ' . $cc. ' remito '. $remito . ' contado '. $contado . ' anulada '. $anulada. ' orden ' . $orden . ' empresa '. $empresa  .  "\n");

        if ($tipoana == 'resumen'){
            //log_this('log/huellita.log', 'En eel caso de resumen 2'. "\n");
            $data['comprobantes'] = $this->mod->get_datos_res($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa, $remitoPrecioActual);
        }else{
            $data['comprobantes'] = $this->mod->get_datos_ana($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa, $remitoPrecioActual);
        }
        //log_this('log/huellita.log', 'Lista_Datos '. print_r($data,true). "\n");
        echo $this->view("lista_datos", $data);
    }

    function x_get_detalle()
    {
        $cod = $_POST['cod'];
        $tco = $_POST['tco'];
        $tip = $_POST['tip'];
        $suc = $_POST['suc'];
        $nco = $_POST['nco'];
        FLAG_HO == false ? $emp = $_POST['emp'] : $emp = 1;
        $data['detalle'] = $this->mod->get_detalle($cod, $tco, $tip, $suc, $nco, $emp);
        if ($data['detalle'] == "-1") {
            echo "-1";
        } elseif ($data['detalle']['tipo'] == "F") {
            $json = json_encode(array(
                'html' => $this->view("detalle", $data),
                'data' => $data
            ));
            echo $json;
        } else {
            $json = json_encode(array(
                'html' => $this->view("detalle_rec", $data),
                'data' => $data
            ));
            echo $json;
        }
    }

    function x_get_remitos(){
        $suc = $_POST['suc'];
        $nco = $_POST['nco'];
        $tip = $_POST['tip'];
        $remitos = $this->mod->get_remitos($suc, $nco, $tip);
        
        $json = json_encode($remitos);
        echo $json;
    }

    function x_imprimir_datos()
    {

        $comprobante = json_decode($_POST['factura']);
        $comprobante = $comprobante->detalle;
        $css = file_get_contents('app_decode/resumen_cuenta/css/impresion.css');
        $html = file_get_contents('app_decode/resumen_cuenta/view/detalle.html');
        foreach($comprobante->arr_empresa as $datoEmpresa){
            $html = str_replace('{{nom}}', $datoEmpresa->NOM, $html);
            $html = str_replace('{{dom}}', $datoEmpresa->DOM, $html);
            $html = str_replace('{{tel}}', $datoEmpresa->TEL, $html);
            $html = str_replace('{{condIva}}', $datoEmpresa->NOMBRE, $html);
            $html = str_replace('{{cui}}', $datoEmpresa->CUI, $html);
            $html = str_replace('{{iibb}}', $datoEmpresa->NIB, $html);
            $html = str_replace('{{iac}}', $datoEmpresa->IAC, $html);
            $html = str_replace('{{nes}}', $datoEmpresa->NES, $html);
            $html = str_replace('{{sti}}', $datoEmpresa->STI, $html);
        }
        $data = new sqldata();
        $suc = $data->query("SELECT  TCAE, TCAEA, MAR,* FROM APARPVE WHERE PVE = ".$comprobante->suc);
        if ($suc[0]['TCAE'] == 0 && $suc[0]['TCAEA'] == 0) {
           if ($suc[0]['MAR'] != '') {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 81"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
           } else {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 01"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
           }
           
        } else {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 01"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
        }
        

        
        $imp1 = $data->query("SELECT * from SETTINGS where variable = 'imp_1'");
        $imp2 = $data->query("SELECT * from SETTINGS where variable = 'imp_2'");        

        $html = str_replace('{{afip}}', $afip, $html);
        $html = str_replace('{{laiva}}', $comprobante->laiva, $html);
        $html = str_replace('{{lacui}}', $comprobante->lacui, $html);
        
        $html = str_replace('{{ato_o}}', $comprobante->ato_o, $html);
        $html = str_replace('{{tip_o}}', $comprobante->tip_o, $html);
        $html = str_replace('{{tip}}', $comprobante->tip, $html);
        $html = str_replace('{{numf}}', $comprobante->numf, $html);
        $html = str_replace('{{fecha}}', $comprobante->fecha, $html);
        $html = str_replace('{{lanom}}', $comprobante->lanom, $html);
        $html = str_replace('{{ladir}}', $comprobante->ladir, $html);
        $html = str_replace('{{ladom}}', $comprobante->ladom, $html);
        $html = str_replace('{{laloc}}', $comprobante->laloc, $html);
        $html = str_replace('{{laprov}}', $comprobante->laprov, $html);
        $html = str_replace('{{imp1}}', $imp1[0]["valor"], $html);
        $html = str_replace('{{imp2}}', $imp2[0]["valor"], $html);
        $html = str_replace('{{lamas}}', $comprobante->lamas, $html);
        $html = str_replace('{{langr}}', isset($comprobante->arr_pie->langr) ? $comprobante->arr_pie->langr : '&nbsp;', $html);
        $html = str_replace('{{r_gananc}}', isset($comprobante->arr_pie->r_gananc) ? $comprobante->arr_pie->r_gananc : '&nbsp;', $html);
        $html = str_replace('{{lairi}}', isset($comprobante->arr_pie->lairi) ? $comprobante->arr_pie->lairi : '&nbsp;', $html);
        $html = str_replace('{{lairs}}', isset($comprobante->arr_pie->lairs) ? $comprobante->arr_pie->lairs : '&nbsp;', $html);
        $html = str_replace('{{ret_brut}}', isset($comprobante->arr_pie->ret_brut) ? $comprobante->arr_pie->ret_brut : '&nbsp;', $html);
        $html = str_replace('{{lapiv}}', isset($comprobante->arr_pie->lapiv) ? $comprobante->arr_pie->lapiv : '&nbsp;', $html);
        $html = str_replace('{{laiitc}}', isset($comprobante->arr_pie->laiitc) ? $comprobante->arr_pie->laiitc : '&nbsp;', $html);
        $html = str_replace('{{laiidc}}', isset($comprobante->arr_pie->laiidc) ? $comprobante->arr_pie->laiidc : '&nbsp;', $html);
        $html = str_replace('{{laitv}}', isset($comprobante->arr_pie->laitv) ? $comprobante->arr_pie->laitv : '&nbsp;', $html); 
        $html = str_replace('{{lanograb}}', isset($comprobante->arr_pie->lanograb) ? $comprobante->arr_pie->lanograb : '&nbsp;', $html);
        $html = str_replace('{{ladesc}}', isset($comprobante->arr_pie->ladesc) ? $comprobante->arr_pie->ladesc : '&nbsp;', $html);
        $html = str_replace('{{latot}}', isset($comprobante->arr_pie->latot) ? $comprobante->arr_pie->latot : '&nbsp;', $html);
        $html = str_replace('{{lacae}}', isset($comprobante->arr_pie->lacae) ? $comprobante->arr_pie->lacae : '&nbsp;', $html);
        $html = str_replace('{{lafeccae}}', isset($comprobante->arr_pie->lafeccae) ? $comprobante->arr_pie->lafeccae : '&nbsp;', $html);
        $html = str_replace('{{body_detalles}}', $this->generarHtmlDetalle($comprobante->arr_detalle,$comprobante->laanu,$comprobante->arr_pie->lacanc,$comprobante->tip), $html);
        $html = str_replace('{{arr_conductor}}', $this->generarMasDatos($comprobante->arr_conductor), $html);

        $pdf = new mpdf('', 'A4', 9, 'chelvetica');
        $pdf->WriteHTML($css, 1);
        $pdf->WriteHTML($html, 2);
        $pdf->Output($comprobante->numf . '.pdf', 'D');
    }

    function generarHtmlDetalle($detalles,$anulada,$cancelaRemitos,$tip)
    {
        $html = '';
        if($anulada == 'A'){
            foreach ($detalles as $detalle) {
                $tasa = number_format($detalle->tasa,2);
                $iva = number_format($detalle->iva,2);
                $html .=
                    '<tr>
                        <td class="columnDet">' . $detalle->cod . '</td>
                        <td class="columnDet">' . $detalle->can . '</td>
                        <td class="columnDet">' . $detalle->det . '</td>
                        <td class="columnDet">' . $detalle->uni . '</td>
                        <td class="columnDet">' . $tasa . '</td>
                        <td class="columnDet">' . $iva . '</td>
                        <td class="columnDet">' . $detalle->impint . '</td>
                        <td class="columnDet">' . $detalle->pun . '</td>
                        <td class="columnDet">' . $detalle->imp . '</td>
                    </tr>';
            }
    
            $length = 44 - count($detalles);
    
            if ($length > 0) {
                for ($i = 0; $i < $length; $i++) {
                    $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
                }
                
                $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">Es copia del original</h1></td> </tr>';
                if ($tip == 'COMPROBANTE INTERNO' || $tip == 'CREDITO INTERNO' || $tip == 'DEBITO INTERNO') {
                    $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">Comprobante no válido como factura</h1></td> </tr>';
                } 
                $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: red">ANULADA</h1></td> </tr>';
                $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">'.$cancelaRemitos.'</h1></td> </tr>';
                $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
                $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
            }
    
            return $html;
        }else{
            foreach ($detalles as $detalle) {
                $tasa = number_format($detalle->tasa,2);
                $iva = number_format($detalle->iva,2);
                $html .=
                    '<tr>
                        <td class="columnDet">' . $detalle->cod . '</td>
                        <td class="columnDet">' . $detalle->can . '</td>
                        <td class="columnDet">' . $detalle->det . '</td>
                        <td class="columnDet">' . $detalle->uni . '</td>
                        <td class="columnDet">' . $tasa . '</td>
                        <td class="columnDet">' . $iva . '</td>
                        <td class="columnDet">' . $detalle->impint . '</td>
                        <td class="columnDet">' . $detalle->pun . '</td>
                        <td class="columnDet">' . $detalle->imp . '</td>
                    </tr>';
            }
    
            $length = 44 - count($detalles);
    
            if ($length > 0) {
                for ($i = 0; $i < $length; $i++) {
                    $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
                }
                
                $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">Es copia del original</h1></td> </tr>';
                if ($tip == 'COMPROBANTE INTERNO' || $tip == 'CREDITO INTERNO' || $tip == 'DEBITO INTERNO') {
                    $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">Comprobante no válido como factura</h1></td> </tr>';
                } 
                $html .= '<tr><td></td><td></td><td colspan="5"><h1 style="color: #ff99007a">'.$cancelaRemitos.'</h1></td> </tr>';
                $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
                $html .= '<tr> <td colspan="5">&nbsp;</td> </tr>';
            }
    
            return $html;
        }
        
    }

    function generarMasDatos($conductor)
    {
        if ($conductor == "Sin datos adicionales") {
            return '<b>Sin Datos Adicionales</b>';
        }
        $html = '<td><strong>Conductor: </strong>' . $conductor->CONDUCTOR . '</td>
                 <td><strong>Vehículo:</strong></td>
                 <td><strong>Marca: </strong>' . $conductor->V_MARCA . '</td>
                 <td><strong>Patente: </strong>' . $conductor->V_PATENTE . '</td>
                 <td><strong>Kms: </strong>' . $conductor->V_KM . '</td>';
        return $html;
    }

    function x_imprimir_datos_rec()
    {

        $comprobante = json_decode($_POST['factura']);
        $comprobante = $comprobante->detalle;
        $css = file_get_contents('app_decode/resumen_cuenta/css/impresion.css');
        $html = file_get_contents('app_decode/resumen_cuenta/view/detalle_rec.html');
        foreach($comprobante->arr_empresa as $datoEmpresa){
            $html = str_replace('{{nom}}', $datoEmpresa->NOM, $html);
            $html = str_replace('{{dom}}', $datoEmpresa->DOM, $html);
            $html = str_replace('{{tel}}', $datoEmpresa->TEL, $html);
            $html = str_replace('{{condIva}}', $datoEmpresa->NOMBRE, $html);
            $html = str_replace('{{cui}}', $datoEmpresa->CUI, $html);
            $html = str_replace('{{iibb}}', $datoEmpresa->NIB, $html);
            $html = str_replace('{{iac}}', $datoEmpresa->IAC, $html);
            $html = str_replace('{{nes}}', $datoEmpresa->NES, $html);
            $html = str_replace('{{sti}}', $datoEmpresa->STI, $html);
        }

        $data = new sqldata();
        $suc = $data->query("SELECT  TCAE, TCAEA, MAR,* FROM APARPVE WHERE PVE = ".$comprobante->suc);
        if ($suc[0]['TCAE'] == 0 && $suc[0]['TCAEA'] == 0) {
           if ($suc[0]['MAR'] != '') {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 81"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
           } else {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 01"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
           }
           
        } else {
            if($comprobante->tip_o == 'A'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 01"; break;
                    case "ND": $afip = "COD: 02"; break;
                    case "NC": $afip = "COD: 03"; break;
                    case "CE": $afip = "COD: 201"; break;
                    case "NE": $afip = "COD: 203"; break;
                }
            }elseif($comprobante->tip_o == 'B'){
                switch($comprobante->tco_o){
                    case "FT": $afip = "COD: 06"; break;
                    case "ND": $afip = "COD: 07"; break;
                    case "NC": $afip = "COD: 08"; break;
                    case "CE": $afip = "COD: 206"; break;
                    case "NE": $afip = "COD: 208"; break;
                }
            }
        }
        

        
        $imp1 = $data->query("SELECT * from SETTINGS where variable = 'imp_1'");
        $imp2 = $data->query("SELECT * from SETTINGS where variable = 'imp_2'");        

        $html = str_replace('{{afip}}', $afip, $html);
        $html = str_replace('{{laiva}}', $comprobante->laiva, $html);
        $html = str_replace('{{lacui}}', $comprobante->lacui, $html);
        
        $html = str_replace('{{ato_o}}', $comprobante->ato_o, $html);
        $html = str_replace('{{tip_o}}', 'R', $html);
        $html = str_replace('{{tip}}', $comprobante->tip, $html);
        $html = str_replace('{{numf}}', $comprobante->numf, $html);
        $html = str_replace('{{fecha}}', $comprobante->fecha, $html);
        $html = str_replace('{{lanom}}', $comprobante->lanom, $html);
        $html = str_replace('{{ladir}}', $comprobante->ladir, $html);
        $html = str_replace('{{ladom}}', $comprobante->ladom, $html);
        $html = str_replace('{{laloc}}', $comprobante->laloc, $html);
        $html = str_replace('{{laprov}}', $comprobante->laprov, $html);
        $html = str_replace('{{imp1}}', $imp1[0]["valor"], $html);
        $html = str_replace('{{imp2}}', $imp2[0]["valor"], $html);
        $html = str_replace('{{lamas}}', $comprobante->lamas, $html);
        $html = str_replace('{{langr}}', isset($comprobante->arr_pie->langr) ? $comprobante->arr_pie->langr : '&nbsp;', $html);
        $html = str_replace('{{r_gananc}}', isset($comprobante->arr_pie->r_gananc) ? $comprobante->arr_pie->r_gananc : '&nbsp;', $html);
        $html = str_replace('{{lairi}}', isset($comprobante->arr_pie->lairi) ? $comprobante->arr_pie->lairi : '&nbsp;', $html);
        $html = str_replace('{{lairs}}', isset($comprobante->arr_pie->lairs) ? $comprobante->arr_pie->lairs : '&nbsp;', $html);
        $html = str_replace('{{ret_brut}}', isset($comprobante->arr_pie->ret_brut) ? $comprobante->arr_pie->ret_brut : '&nbsp;', $html);
        $html = str_replace('{{lapiv}}', isset($comprobante->arr_pie->lapiv) ? $comprobante->arr_pie->lapiv : '&nbsp;', $html);
        $html = str_replace('{{laiitc}}', isset($comprobante->arr_pie->laiitc) ? $comprobante->arr_pie->laiitc : '&nbsp;', $html);
        $html = str_replace('{{laiidc}}', isset($comprobante->arr_pie->laiidc) ? $comprobante->arr_pie->laiidc : '&nbsp;', $html);
        $html = str_replace('{{laitv}}', isset($comprobante->arr_pie->laitv) ? $comprobante->arr_pie->laitv : '&nbsp;', $html); 
        $html = str_replace('{{lanograb}}', isset($comprobante->arr_pie->lanograb) ? $comprobante->arr_pie->lanograb : '&nbsp;', $html);
        $html = str_replace('{{laliq}}', isset($comprobante->arr_pie->pagtotal) ? $comprobante->arr_pie->pagtotal : '&nbsp;', $html);
        $html = str_replace('{{latot}}', isset($comprobante->arr_pie->liqtotal) ? $comprobante->arr_pie->liqtotal : '&nbsp;', $html);
        $html = str_replace('{{body_detalles}}', $this->generarHtmlDetalle_rec($comprobante->arr_detalle,$comprobante->laanu,$comprobante->arr_pie->lacanc,$comprobante->tip), $html);
        $html = str_replace('{{arr_conductor}}', $this->generarMasDatos_rec($comprobante->arr_conductor), $html);

        $pdf = new mpdf('', 'A4', 9, 'chelvetica');
        $pdf->WriteHTML($css, 1);
        $pdf->WriteHTML($html, 2);
        $pdf->Output($comprobante->numf . '.pdf', 'D');
    }

    function generarHtmlDetalle_rec($detalles,$anulada,$cancelaRemitos,$tip)
    {
        $html = '';
        if($anulada == 'A'){
            foreach ($detalles as $detalle) {
                $html .=
                    '<tr>
                        <td class="columnDet">' . $detalle->can . '</td>
                        <td class="columnDet">' . $detalle->det . '</td>
                        <td class="columnDet">' . $detalle->laimp . '</td>
                        <td class="columnDet">' . $detalle->cod . '</td>
                    </tr>';
            }
    
            $length = 36 - count($detalles);
    
            if ($length > 0) {
                for ($i = 0; $i < $length; $i++) {
                    $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
                }
                
                $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">Es copia del original</h1></td> </tr>';
                if ($tip == 'COMPROBANTE INTERNO' || $tip == 'CREDITO INTERNO' || $tip == 'DEBITO INTERNO') {
                    $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">Comprobante no válido como factura</h1></td> </tr>';
                }    
                $html .= '<tr><td colspan="4"><h1 style="color: red">ANULADA</h1></td> </tr>';
                $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">'.$cancelaRemitos.'</h1></td> </tr>';
                $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
                $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
            }
    
            return $html;
        }else{
            foreach ($detalles as $detalle) {
                $html .=
                    '<tr>
                        <td class="columnDet">' . $detalle->can . '</td>
                        <td class="columnDet">' . $detalle->det . '</td>
                        <td class="columnDet">' . $detalle->laimp . '</td>
                        <td class="columnDet">' . $detalle->cod . '</td>
                    </tr>';
            }
    
            $length = 36 - count($detalles);
    
            if ($length > 0) {
                for ($i = 0; $i < $length; $i++) {
                    $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
                }
                
                $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">Es copia del original</h1></td> </tr>';
                if ($tip == 'COMPROBANTE INTERNO' || $tip == 'CREDITO INTERNO' || $tip == 'DEBITO INTERNO') {
                    $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">Comprobante no válido como factura</h1></td> </tr>';
                } 
                $html .= '<tr><td colspan="4"><h1 style="color: #ff99007a">'.$cancelaRemitos.'</h1></td> </tr>';
                $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
                $html .= '<tr> <td colspan="4">&nbsp;</td> </tr>';
            }
    
            return $html;
        }
        
    }

    function generarMasDatos_rec($conductor)
    {
        if ($conductor == "Sin datos adicionales") {
            return '<b>Sin Datos Adicionales</b>';
        }
        $html = '<td><strong>Conductor: </strong>' . $conductor->CONDUCTOR . '</td>
                 <td><strong>Vehículo:</strong></td>
                 <td><strong>Marca: </strong>' . $conductor->V_MARCA . '</td>
                 <td><strong>Patente: </strong>' . $conductor->V_PATENTE . '</td>
                 <td><strong>Kms: </strong>' . $conductor->V_KM . '</td>';
        return $html;
    }
}
