<?php

namespace App\Controladores;

use App\Modelos\Cliente;
use App\Modelos\ClienteContactos;
use App\Modelos\Clientedireccionenvios;
use App\Modelos\EmpleadoInfo;
use App\Modelos\Facturacion;
use App\Modelos\Generico;
use App\Modelos\ProductosCompuestos;
use App\Modelos\Ingresosegresos;
use App\Modelos\Notadecredito;
use App\Modelos\Notasdeentrega;
use App\Modelos\Ordendeentrega;
use App\Modelos\Pedidos;
use App\Modelos\Pos;
use Core\Controller;
use Core\Helpers\Moneda;
use Core\Librerias\CarritoVentasEditar;
use Core\Librerias\Http;
use Core\Librerias\Module;
use Core\Vista;
use DateTime;
use DateTimeZone;

final class FacturacionControlador extends Controller
{
    private $facturacionModel;
    private $array_errors = [];
    private $module;
    private $divisa_master;

    public function __construct()
    {
        parent::__construct();
        $this->module   = new Module('facturacion');
        $this->facturacionModel = new Facturacion();
        $this->divisa_master  = $this->facturacionModel->obtenerDivisaMaster();
    }

    public function obtenerDivisaPredeterminada()
    {
        Http::json_response(Moneda::Predeterminada());
    }

    public function obtenerDivisaParaFactura()
    {
        Http::json_response(Moneda::facturarPredeterminada());
    }

    public function index()
    {
        $obtener_agente = new EmpleadoInfo();

        return Vista::view('facturacion/index', [
            'series' => $this->facturacionModel->consultar("SELECT ser_id, ser_descripcion FROM app_series")->all(),
            'divisas' => $this->facturacionModel->consultar("SELECT * FROM app_divisas WHERE div_status = 1")->all(),
            'sucursales' => $this->facturacionModel->consultar("SELECT * FROM app_empleados_sucursales s JOIN app_sucursales su ON s.sucursal_id = su.su_id WHERE empleado_id={$_SESSION['user_data']['emp_id']}")->all(),
            'impresoras' => $this->facturacionModel->impresoras(),
            'agentes'               => $obtener_agente->agentesventa(),
            'doc_generico' => $this->facturacionModel->obtenerDocumento(12),
            'tipos_de_documentos' => $this->facturacionModel->obtenerTiposdeDocumentos(),
            'opfacturas' => $this->module->has_module_action_permission('facturacion', 'opfacturas', $_SESSION['user_data']['emp_id']),
            'todosucursales' => $this->module->has_module_action_permission('facturacion', 'todosucursales', $_SESSION['user_data']['emp_id']),
            'opnotasentrgas' => $this->module->has_module_action_permission('facturacion', 'opnotasentrgas', $_SESSION['user_data']['emp_id']),
            'oppresupuestos' => $this->module->has_module_action_permission('facturacion', 'oppresupuestos', $_SESSION['user_data']['emp_id']),
            'oppedidos' => $this->module->has_module_action_permission('facturacion', 'oppedidos', $_SESSION['user_data']['emp_id']),
            'opnotascreditos' => $this->module->has_module_action_permission('facturacion', 'opnotascreditos', $_SESSION['user_data']['emp_id']),
            'opordendeentrega' => $this->module->has_module_action_permission('facturacion', 'opordendeentrega', $_SESSION['user_data']['emp_id']),
            'opfactor' => $this->module->has_module_action_permission('configuracion', 'factor', $_SESSION['user_data']['emp_id']),
            'opbuscarenfacturas' => $this->module->has_module_action_permission('facturacion', 'opbuscarenfacturas', $_SESSION['user_data']['emp_id']),
            'opfabricantes' => $this->module->getModuleUser('fabricantes', $_SESSION['user_data']['emp_id']),
            'opproveedores' => $this->module->getModuleUser('proveedores', $_SESSION['user_data']['emp_id']),
            'opcategorias' => $this->module->getModuleUser('categorias', $_SESSION['user_data']['emp_id']),
            'optarifas' => $this->module->getModuleUser('tarifas', $_SESSION['user_data']['emp_id']),
            'opalmacenes' => $this->module->getModuleUser('almacenes', $_SESSION['user_data']['emp_id']),
            'reporte_proveedor' => $this->module->has_module_action_permission('ingresosegresos', 'reporte_proveedor', $_SESSION['user_data']['emp_id']),
            'cierre_dia' => $this->module->has_module_action_permission('ingresosegresos', 'cierre_dia', $_SESSION['user_data']['emp_id']),
            'productos_vendidos' => $this->module->has_module_action_permission('ingresosegresos', 'productos_vendidos', $_SESSION['user_data']['emp_id']),
            'productos_vendidos_documentos' => $this->module->has_module_action_permission('ingresosegresos', 'productos_vendidos_documentos', $_SESSION['user_data']['emp_id']),
            'productos_vendidos_simples' => $this->module->has_module_action_permission('ingresosegresos', 'productos_vendidos_simples', $_SESSION['user_data']['emp_id']),
            'venta_dia' => $this->module->has_module_action_permission('ingresosegresos', 'venta_dia', $_SESSION['user_data']['emp_id']),
            'ventas_meses' => $this->module->has_module_action_permission('ingresosegresos', 'ventas_meses', $_SESSION['user_data']['emp_id']),
            'venta_dias' => $this->module->has_module_action_permission('ingresosegresos', 'venta_dias', $_SESSION['user_data']['emp_id']),
            'precio_productos_vendidos' => $this->module->has_module_action_permission('ingresosegresos', 'precio_productos_vendidos', $_SESSION['user_data']['emp_id']),
            'cliente_cobrar' => $this->module->has_module_action_permission('ingresosegresos', 'cliente_cobrar', $_SESSION['user_data']['emp_id']),
            'hora_productos_vendidos' => $this->module->has_module_action_permission('ingresosegresos', 'hora_productos_vendidos', $_SESSION['user_data']['emp_id']),
            
        ]);
    }

    public function obtenerSucursalesEmpleado()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $suc = $this->facturacionModel->obtenerSucursales($_SESSION['user_data']['emp_id']);

            $todo = $this->module->has_module_action_permission('facturacion', 'todosucursales', $_SESSION['user_data']['emp_id']);

            $ID = '';

            if ($_SESSION['sucursal']['id'] == 0 && $todo) {
                $ID = $_SESSION['sucursal']['id'];
            } else {

                foreach ($suc as $row) {
                    if ($row['sucursal_predeterminado'] == 1) {
                        $ID = $row['sucursal_id'];
                    }
                }

                if ($ID == "" && count($suc) > 0) {
                    $ID = $suc[0]['empalm_almid'];
                }
            }


            Http::json_response([
                'sucursales' => $suc,
                'id' => ($_SESSION['sucursal']['id'] != 0) ? $_SESSION['sucursal']['id'] : $ID,
                'desactivar' => ($_SESSION['sucursal']['id'] != 0) ? true : false
            ]);
        }
    }

    public function obtenerFacturas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $n_finalizadas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=1 AND YEAR(fm.fm_fecha)=$anio")->count();
                    $n_pendientes = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND YEAR(fm.fm_fecha)=$anio")->count();
                    $n_anuladas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=3 AND YEAR(fm.fm_fecha)=$anio")->count();
                } else {
                    $n_finalizadas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=1 AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio")->count();
                    $n_pendientes = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                          WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio")->count();
                    $n_anuladas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                          WHERE fm.fm_estatus=3 AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio")->count();
                }
            } else {
                if ($mes == 0) {
                    $n_finalizadas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=1 AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                    $n_pendientes = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                    $n_anuladas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=3 AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                } else {
                    $n_finalizadas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                        WHERE fm.fm_estatus=1 AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                    $n_pendientes = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                          WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                    $n_anuladas = $this->facturacionModel->consultar("SELECT *  
                        FROM app_factura_master fm 
                        JOIN app_divisas d ON d.div_id = fm.fm_divid
                        JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                          WHERE fm.fm_estatus=3 AND MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal")->count();
                }
            }

            Http::json_response([
                "pendientes" => $n_pendientes,
                "pagadas" => $n_finalizadas,
                "anuladas" => $n_anuladas,
            ]);
        }
    }

    public function obtenerFacturasPendientes()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $array_finalizadas  = [];
            $array_anuladas     = [];
            $array_pendientes   = [];

            $documento = $this->facturacionModel->obtenerDocumento(2);

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (fm.fm_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR fm.fm_total LIKE '%" . $searchValue . "%' OR fm.fm_neto LIKE '%" . $searchValue . "%' OR fm.fm_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND $peticion ORDER BY fm.fm_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND $peticion $searchQuery ORDER BY fm.fm_id DESC")->count();

            ## Fetch records
            $f_pendientes = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total,fm.fm_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=0 OR fm.fm_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($f_pendientes) && count($f_pendientes)) {
                foreach ($f_pendientes as $row) {
                    
                         $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['fm_id'], 2);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pendientes[] = [
                        'fm_id'            => $row['fm_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'poseditar/verFactura/' . $row['fm_id'],
                        'fm_correlativo' => $documento['doc_prefijo'] . $row['fm_correlativo'],
                        'correlativo'   => $row['fm_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['fm_total'], $row['div_locale'], $row['div_simbolo']),
                        'fm_fecha'         => $row['fm_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['fm_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           =>  $msj_activo,
                        'correo'        => $correo_activo,
                         'observacion'   =>($row['fm_observaciones']==null)?"":$row['fm_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }

    public function obtenerFacturasPagas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $array_finalizadas  = [];
            $array_anuladas     = [];
            $array_pendientes   = [];

            $documento = $this->facturacionModel->obtenerDocumento(2);

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (fm.fm_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR fm.fm_total LIKE '%" . $searchValue . "%' OR fm.fm_neto LIKE '%" . $searchValue . "%' OR fm.fm_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=1) AND $peticion ORDER BY fm.fm_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=1) AND $peticion $searchQuery ORDER BY fm.fm_id DESC")->count();

            ## Fetch records
            $f_finalizadas = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total,fm.fm_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($f_finalizadas) && count($f_finalizadas)) {
                foreach ($f_finalizadas as $row) {
                    
                            $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['fm_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_finalizadas[] = [
                        'fm_id'            => $row['fm_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'poseditar/verFactura/' . $row['fm_id'],
                        'fm_correlativo' => $documento['doc_prefijo'] . $row['fm_correlativo'],
                        'correlativo'   => $row['fm_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['fm_total'], $row['div_locale'], $row['div_simbolo']),
                        'fm_fecha'         => $row['fm_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['fm_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           => $msj_activo,
                        'correo'        => $correo_activo,
                         'observacion'   =>($row['fm_observaciones']==null)?"":$row['fm_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_finalizadas
            ]);
        }
    }

    public function obtenerFacturasAnuladas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $array_finalizadas  = [];
            $array_anuladas     = [];
            $array_pendientes   = [];

            $documento = $this->facturacionModel->obtenerDocumento(2);

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(fm.fm_fecha)=$mes AND YEAR(fm.fm_fecha)=$anio AND fm.fm_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (fm.fm_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR fm.fm_total LIKE '%" . $searchValue . "%' OR fm.fm_neto LIKE '%" . $searchValue . "%' OR fm.fm_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=3) AND $peticion ORDER BY fm.fm_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=3) AND $peticion $searchQuery ORDER BY fm.fm_id DESC")->count();

            ## Fetch records
            $f_anuladas = $this->facturacionModel->consultar("SELECT fm.fm_id, fm.fm_correlativo, fm.fm_fecha, fm.fm_total,fm.fm_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_factura_master fm 
            JOIN app_divisas d ON d.div_id = fm.fm_divid
            JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
            WHERE (fm.fm_estatus=3) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($f_anuladas) && count($f_anuladas)) {
                foreach ($f_anuladas as $row) {
                    
                       $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['fm_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_anuladas[] = [
                        'fm_id'            => $row['fm_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'poseditar/verFactura/' . $row['fm_id'],
                        'fm_correlativo' => $documento['doc_prefijo'] . $row['fm_correlativo'],
                        'correlativo'   => $row['fm_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['fm_total'], $row['div_locale'], $row['div_simbolo']),
                        'fm_fecha'         => $row['fm_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['fm_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           => $msj_activo,
                        'correo'        => $correo_activo,
                         'observacion'   =>($row['fm_observaciones']==null)?"":$row['fm_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_anuladas
            ]);
        }
    }
    //notas de entrega
    public function obtenerNotasdeEntregaAnualesPendientes()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(1);

            $array_pendientes   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (ne.ne_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR ne.ne_total LIKE '%" . $searchValue . "%' OR ne.ne_neto LIKE '%" . $searchValue . "%' OR ne.ne_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND $peticion ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND $peticion $searchQuery ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            ## Fetch records
            $n_pendientes = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total,ne.ne_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pendientes) && count($n_pendientes)) {
                foreach ($n_pendientes as $row) {
                    
                    
                    $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['ne_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pendientes[] = [
                        'ne_id'            => $row['ne_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'notasdeentregaeditar/verFactura/' . $row['ne_id'],
                        'ne_correlativo' => $documento['doc_prefijo'] . $row['ne_correlativo'],
                        'correlativo'   => $row['ne_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['ne_total'], $row['div_locale'], $row['div_simbolo']),
                        'ne_fecha'      => $row['ne_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['ne_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           =>$msj_activo,
                        'correo'        =>$correo_activo,
                        'observacion'   =>($row['ne_observaciones']==null)?"":$row['ne_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }
    public function obtenerNotasdeEntregaAnualesPagadas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(1);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (ne.ne_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR ne.ne_total LIKE '%" . $searchValue . "%' OR ne.ne_neto LIKE '%" . $searchValue . "%' OR ne.ne_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=1) AND $peticion ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=1) AND $peticion $searchQuery ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total,ne.ne_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    
                          $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['ne_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pagas[] = [
                        'ne_id'            => $row['ne_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'notasdeentregaeditar/verFactura/' . $row['ne_id'],
                        'ne_correlativo' => $documento['doc_prefijo'] . $row['ne_correlativo'],
                        'correlativo'   => $row['ne_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['ne_total'], $row['div_locale'], $row['div_simbolo']),
                        'ne_fecha'         => $row['ne_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['ne_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           => $msj_activo,
                        'correo'        => $correo_activo,
                         'observacion'   =>($row['ne_observaciones']==null)?"":$row['ne_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }
    public function obtenerNotasdeEntregaAnualesAnuladas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(1);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (ne.ne_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR ne.ne_total LIKE '%" . $searchValue . "%' OR ne.ne_neto LIKE '%" . $searchValue . "%' OR ne.ne_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=3) AND $peticion ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=3) AND $peticion $searchQuery ORDER BY ne.ne_fecha,ne.ne_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT ne.ne_id, ne.ne_correlativo, ne.ne_fecha, ne.ne_total,ne.ne_observaciones, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_notas_de_entrega ne 
            JOIN app_divisas d ON d.div_id = ne.ne_divid
            JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
            WHERE (ne.ne_estatus=3) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    
                        $msj=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 1 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                      $correo=$this->facturacionModel->consultar("SELECT cs.sc_id id, c.cli_id idcliente,c.cli_razon_social cliente, cc.ccon_nombre cto_nombre, cc.ccon_cargo cto_cargo, cc.ccon_telefono cto_tlf, cc.ccon_email cto_email,cc.ccon_cliid, s.sms_titulo msj_titulo, s.sms_id msj_id,s.sms_cuerpo msj_cuerpo,s.sms_modulo msj_modulo, cs.sc_fecha_desde fecha_desde, cs.sc_fecha_hasta fecha_hasta, cs.sc_intervalo intervalo, cs.sc_ultimo_envio ultimo_envio 
                    FROM app_sms_cliente cs 
                    JOIN app_clientes_contactos cc ON cs.cs_cconid = cc.ccon_id
                    JOIN app_sms s ON s.sms_id = cs.cs_smsid 
                    JOIN app_clientes c ON c.cli_id = cc.ccon_cliid 
                    WHERE s.sms_tipo = 2 AND s.sms_modulo = 3 AND s.sms_estatus=1 AND cc.ccon_cliid={$row['cli_id']} AND (((DATE(cs.sc_fecha_desde) <= DATE(CURRENT_DATE)) AND (DATE(cs.sc_fecha_hasta) >= DATE(CURRENT_DATE))) OR cs.sc_fecha_hasta IS NULL)")->all();
                    
                    $msj_activo=(count($msj)>0) ? true: false;
                    $correo_activo=(count($correo)>0) ? true: false;
                    
                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['ne_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pagas[] = [
                        'ne_id'            => $row['ne_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'notasdeentregaeditar/verFactura/' . $row['ne_id'],
                        'ne_correlativo' => $documento['doc_prefijo'] . $row['ne_correlativo'],
                        'correlativo'   => $row['ne_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['ne_total'], $row['div_locale'], $row['div_simbolo']),
                        'ne_fecha'         => $row['ne_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['ne_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'msj'           =>$msj_activo,
                        'correo'        => $correo_activo,
                        'observacion'   =>($row['ne_observaciones']==null)?"":$row['ne_observaciones']
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }
    public function obtenerNotasdeEntrega()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {
                if ($sucursal == 0) {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=1 AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=3 AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=1 AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                          JOIN app_divisas d ON d.div_id = ne.ne_divid
                          JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                          WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                          JOIN app_divisas d ON d.div_id = ne.ne_divid
                          JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                          WHERE ne.ne_estatus=3 AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio  ORDER BY ne.ne_fecha DESC")->count();
                    }
                } else {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=1 AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=3 AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                        JOIN app_divisas d ON d.div_id = ne.ne_divid
                        JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                        WHERE ne.ne_estatus=1 AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                          JOIN app_divisas d ON d.div_id = ne.ne_divid
                          JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                          WHERE (ne.ne_estatus=0 OR ne.ne_estatus=2) AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT * FROM app_notas_de_entrega ne 
                          JOIN app_divisas d ON d.div_id = ne.ne_divid
                          JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                          WHERE ne.ne_estatus=3 AND MONTH(ne.ne_fecha)=$mes AND YEAR(ne.ne_fecha)=$anio AND ne.ne_surcid=$sucursal  ORDER BY ne.ne_fecha DESC")->count();
                    }
                }

                Http::json_response([
                    "pendientes" => $n_pendientes,
                    "pagadas" => $n_finalizadas,
                    "anuladas" => $n_anuladas,
                ]);
            }
            Http::json_response(['errors' => $this->array_errors]);
        }
    }
    //presupuesto
    public function obtenerPresupuestos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {
                if ($sucursal == 0) {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE pre.pre_estatus=1 AND YEAR(pre.pre_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND YEAR(pre.pre_fecha)=$anio")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE pre.pre_estatus=1 AND MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                          WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio")->count();
                    }
                } else {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE pre.pre_estatus=1 AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                        WHERE pre.pre_estatus=1 AND MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_presupuesto pre 
                        JOIN app_divisas d ON d.div_id = pre.pre_divid
                        JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
                          WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal")->count();
                    }
                }

                Http::json_response([
                    "pendientes" => $n_pendientes,
                    "pagadas" => $n_finalizadas
                ]);
            }
            Http::json_response(['errors' => $this->array_errors]);
        }
    }
    public function obtenerPresupuestosPendientes()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(3);

            $array_pendientes   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(pre.pre_fecha)=$anio";
                } else {
                    $peticion = "MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (pre.pre_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR pre.pre_total LIKE '%" . $searchValue . "%' OR pre.pre_neto LIKE '%" . $searchValue . "%' OR pre.pre_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND $peticion ORDER BY pre.pre_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND $peticion $searchQuery ORDER BY pre.pre_id DESC")->count();

            ## Fetch records
            $n_pendientes = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=0 OR pre.pre_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pendientes) && count($n_pendientes)) {
                foreach ($n_pendientes as $row) {
                    $array_pendientes[] = [
                        'pre_id'            => $row['pre_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'presupuestoeditar/verFactura/' . $row['pre_id'],
                        'pre_correlativo' => $documento['doc_prefijo'] . $row['pre_correlativo'],
                        'correlativo'   => $row['pre_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['pre_total'], $row['div_locale'], $row['div_simbolo']),
                        'pre_fecha'         => $row['pre_fecha'],
                        'acumulado'     =>  0,
                        'pendiente'     =>  0
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }
    public function obtenerPresupuestosPagadas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(3);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(pre.pre_fecha)=$anio";
                } else {
                    $peticion = "MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(pre.pre_fecha)=$mes AND YEAR(pre.pre_fecha)=$anio AND pre.pre_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (pre.pre_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR pre.pre_total LIKE '%" . $searchValue . "%' OR pre.pre_neto LIKE '%" . $searchValue . "%' OR pre.pre_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=1) AND $peticion ORDER BY pre.pre_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=1) AND $peticion $searchQuery ORDER BY pre.pre_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT pre.pre_id, pre.pre_correlativo, pre.pre_fecha, pre.pre_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_presupuesto pre 
            JOIN app_divisas d ON d.div_id = pre.pre_divid
            JOIN app_clientes c ON c.cli_id = pre.pre_cliid 
            WHERE (pre.pre_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    $array_pagas[] = [
                        'pre_id'            => $row['pre_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'presupuestoeditar/verFactura/' . $row['pre_id'],
                        'pre_correlativo' => $documento['doc_prefijo'] . $row['pre_correlativo'],
                        'correlativo'   => $row['pre_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['pre_total'], $row['div_locale'], $row['div_simbolo']),
                        'pre_fecha'         => $row['pre_fecha'],
                        'acumulado'     =>  0,
                        'pendiente'     =>  0
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }

    //pedidos
    public function obtenerPedidos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {
                if ($sucursal == 0) {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE pe.pe_estatus=1 AND YEAR(pe.pe_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND YEAR(pe.pe_fecha)=$anio")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE pe.pe_estatus=1 AND MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                          WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio")->count();
                    }
                } else {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE pe.pe_estatus=1 AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                        WHERE pe.pe_estatus=1 AND MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_pedidos pe 
                        JOIN app_divisas d ON d.div_id = pe.pe_divid
                        JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
                          WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal")->count();
                    }
                }

                Http::json_response([
                    "pendientes" => $n_pendientes,
                    "pagadas" => $n_finalizadas
                ]);
            }
            Http::json_response(['errors' => $this->array_errors]);
        }
    }
    public function obtenerPedidosPendientes()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(4);

            $array_pendientes   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(pe.pe_fecha)=$anio";
                } else {
                    $peticion = "MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (pe.pe_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR pe.pe_total LIKE '%" . $searchValue . "%' OR pe.pe_neto LIKE '%" . $searchValue . "%' OR pe.pe_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND $peticion ORDER BY pe.pe_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND $peticion $searchQuery ORDER BY pe.pe_id DESC")->count();

            ## Fetch records
            $n_pendientes = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=0 OR pe.pe_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pendientes) && count($n_pendientes)) {
                foreach ($n_pendientes as $row) {
                    $array_pendientes[] = [
                        'pe_id'            => $row['pe_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'pedidoseditar/verFactura/' . $row['pe_id'],
                        'pe_correlativo' => $documento['doc_prefijo'] . $row['pe_correlativo'],
                        'correlativo'   => $row['pe_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['pe_total'], $row['div_locale'], $row['div_simbolo']),
                        'pe_fecha'         => $row['pe_fecha'],
                        'acumulado'     =>  0,
                        'pendiente'     =>  0
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }
    public function obtenerPedidosPagadas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(4);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(pe.pe_fecha)=$anio";
                } else {
                    $peticion = "MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(pe.pe_fecha)=$mes AND YEAR(pe.pe_fecha)=$anio AND pe.pe_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (pe.pe_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR pe.pe_total LIKE '%" . $searchValue . "%' OR pe.pe_neto LIKE '%" . $searchValue . "%' OR pe.pe_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=1) AND $peticion ORDER BY pe.pe_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=1) AND $peticion $searchQuery ORDER BY pe.pe_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT pe.pe_id, pe.pe_correlativo, pe.pe_fecha, pe.pe_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_pedidos pe 
            JOIN app_divisas d ON d.div_id = pe.pe_divid
            JOIN app_clientes c ON c.cli_id = pe.pe_cliid 
            WHERE (pe.pe_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    $array_pagas[] = [
                        'pe_id'            => $row['pe_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'pedidoseditar/verFactura/' . $row['pe_id'],
                        'pe_correlativo' => $documento['doc_prefijo'] . $row['pe_correlativo'],
                        'correlativo'   => $row['pe_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['pe_total'], $row['div_locale'], $row['div_simbolo']),
                        'pe_fecha'         => $row['pe_fecha'],
                        'acumulado'     =>  0,
                        'pendiente'     =>  0
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }

    //nota de credito
    public function obtenerCreditos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {
                if ($sucursal == 0) {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE nc.cre_estatus=1 AND YEAR(nc.cre_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND YEAR(nc.cre_fecha)=$anio")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE nc.cre_estatus=1 AND MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                          WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio")->count();
                    }
                } else {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE nc.cre_estatus=1 AND YEARnc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                        WHERE nc.cre_estatus=1 AND MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_nota_de_credito nc
                        JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
                          WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal")->count();
                    }
                }

                Http::json_response([
                    "pendientes" => $n_pendientes,
                    "pagadas" => $n_finalizadas
                ]);
            }
            Http::json_response(['errors' => $this->array_errors]);
        }
    }
    public function obtenerCreditosActivos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(3);

            $array_pendientes   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(nc.cre_fecha)=$anio";
                } else {
                    $peticion = "MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (nc.cre_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR nc.cre_total LIKE '%" . $searchValue . "%' OR nc.cre_neto LIKE '%" . $searchValue . "%' OR nc.cre_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND $peticion ORDER BY nc.cre_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND $peticion $searchQuery ORDER BY nc.cre_id DESC")->count();

            ## Fetch records
            $n_pendientes = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=0 OR nc.cre_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pendientes) && count($n_pendientes)) {
                foreach ($n_pendientes as $row) {

                    $uri = '';

                    if ($row['cre_docid']) {
                        $tipo_documento = $this->facturacionModel->obtenerDocumento($row['cre_docid']);
                        if ($row['cre_docid'] == 1) {
                            $uri = 'notasdeentregaeditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 2) {
                            $uri = 'poseditar/verFactura/' .  $row['cre_facid'];
                        } else if ($row['cre_docid'] == 3) {
                            $uri = 'presupuestoeditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 4) {
                            $uri = 'pedidoseditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 12) {
                            $uri = 'ordendeentregaeditar/verFactura/' . $row['cre_facid'];
                        }
                        $documento =  $tipo_documento['doc_prefijo'] . $row['cre_facid'];
                    } else {
                        $documento =  'CREDITO';
                    }
                    $restante = 0;
                    $pago_total = $this->facturacionModel->obtenerNotadeCreditoDetalleTotal($row['cre_id']);

                    if ($pago_total['total']) {
                        $restante = $row['cre_monto'] - $pago_total['total'];
                    }

                    $array_pendientes[] = [
                        'cre_id'            => $row['cre_id'],
                        'uri'           => $uri,
                        'documento'     => $documento,
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'cre_fecha'         => $row['cre_fecha'],
                        'monto'         => $row['cre_monto'],
                        'descripcion'   => $row['cre_descripcion'],
                        'restante'      => round($restante, 2)

                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }
    public function obtenerCreditosInactivos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(3);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(nc.cre_fecha)=$anio";
                } else {
                    $peticion = "MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(nc.cre_fecha)=$mes AND YEAR(nc.cre_fecha)=$anio AND nc.cre_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (nc.cre_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR nc.cre_total LIKE '%" . $searchValue . "%' OR nc.cre_neto LIKE '%" . $searchValue . "%' OR nc.cre_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=1) AND $peticion ORDER BY nc.cre_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=1) AND $peticion $searchQuery ORDER BY nc.cre_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT nc.cre_id, nc.cre_docid, cre_facid, nc.cre_modulo, nc.cre_monto, nc.cre_fecha, nc.cre_descripcion, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_nota_de_credito nc
            JOIN app_clientes c ON c.cli_id = nc.cre_cliid 
            WHERE (nc.cre_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {

                    $uri = '';

                    if ($row['cre_docid']) {
                        $tipo_documento = $this->facturacionModel->obtenerDocumento($row['cre_docid']);
                        if ($row['cre_docid'] == 1) {
                            $uri = 'notasdeentregaeditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 2) {
                            $uri = 'poseditar/verFactura/' .  $row['cre_facid'];
                        } else if ($row['cre_docid'] == 3) {
                            $uri = 'presupuestoeditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 4) {
                            $uri = 'pedidoseditar/verFactura/' . $row['cre_facid'];
                        } else if ($row['cre_docid'] == 12) {
                            $uri = 'ordendeentregaeditar/verFactura/' . $row['cre_facid'];
                        }
                        $documento =  $tipo_documento['doc_prefijo'] . $row['cre_facid'];
                    } else {
                        $documento =  'CREDITO';
                    }

                    $pago_total = $this->facturacionModel->obtenerNotadeCreditoDetalleTotal($row['cre_id']);

                    if ($pago_total['total']) {
                        $restante = $row['cre_monto'] - $pago_total['total'];
                    }

                    $array_pagas[] = [
                        'cre_id'            => $row['cre_id'],
                        'uri'           => $uri,
                        'documento'     => $documento,
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'cre_fecha'         => $row['cre_fecha'],
                        'monto'         => $row['cre_monto'],
                        'descripcion'   => $row['cre_descripcion'],
                        'restante'      => round($restante, 2)

                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }

    //orden de entrega
    public function obtenerOrdendeEntregaAnualesPendientes()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(12);

            $array_pendientes   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (n.n_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR n.n_total LIKE '%" . $searchValue . "%' OR n.n_neto LIKE '%" . $searchValue . "%' OR n.n_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=0 OR n.n_estatus=2) AND $peticion ORDER BY n.n_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=0 OR n.n_estatus=2) AND $peticion $searchQuery ORDER BY n.n_id DESC")->count();

            ## Fetch records
            $n_pendientes = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=0 OR n.n_estatus=2) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pendientes) && count($n_pendientes)) {
                foreach ($n_pendientes as $row) {

                    $existe_planilla =  $this->facturacionModel->consultar("SELECT * FROM app_planilla_orden_de_entrega WHERE po_nid = {$row['n_id']}")->row();

                    $planilla = '';

                    if ($existe_planilla) {
                        $planill =  $this->facturacionModel->consultar("SELECT * FROM app_preorden_master WHERE pre_id = {$existe_planilla['po_preid']}")->row();

                        $planilla = $planill['pre_correlativo'];
                    }

                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['n_id'], 12);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pendientes[] = [
                        'n_id'            => $row['n_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'n_correlativo' => $documento['doc_prefijo'] . $row['n_correlativo'],
                        'correlativo'   => $row['n_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['n_total'], $row['div_locale'], $row['div_simbolo']),
                        'n_fecha'         => $row['n_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['n_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'planilla'      => $planilla
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pendientes
            ]);
        }
    }
    public function obtenerOrdendeEntregaAnualesPagadas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(12);

            $array_pagas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (n.n_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR n.n_total LIKE '%" . $searchValue . "%' OR n.n_neto LIKE '%" . $searchValue . "%' OR n.n_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=1) AND $peticion ORDER BY n.n_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=1) AND $peticion $searchQuery ORDER BY n.n_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=1) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    $existe_planilla =  $this->facturacionModel->consultar("SELECT * FROM app_planilla_orden_de_entrega WHERE po_nid = {$row['n_id']}")->row();

                    $planilla = '';

                    if ($existe_planilla) {
                        $planill =  $this->facturacionModel->consultar("SELECT * FROM app_preorden_master WHERE pre_id = {$existe_planilla['po_preid']}")->row();

                        $planilla = $planill['pre_correlativo'];
                    }

                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['n_id'], 12);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_pagas[] = [
                        'n_id'            => $row['n_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'n_correlativo' => $documento['doc_prefijo'] . $row['n_correlativo'],
                        'correlativo'   => $row['n_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['n_total'], $row['div_locale'], $row['div_simbolo']),
                        'n_fecha'         => $row['n_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['n_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'planilla'      => $planilla
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_pagas
            ]);
        }
    }
    public function obtenerOrdendeEntregaAnualesAnuladas()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(12);

            $array_anuladas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (n.n_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR n.n_total LIKE '%" . $searchValue . "%' OR n.n_neto LIKE '%" . $searchValue . "%' OR n.n_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=3) AND $peticion ORDER BY n.n_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=3) AND $peticion $searchQuery ORDER BY n.n_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=3) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    $existe_planilla =  $this->facturacionModel->consultar("SELECT * FROM app_planilla_orden_de_entrega WHERE po_nid = {$row['n_id']}")->row();

                    $planilla = '';

                    if ($existe_planilla) {
                        $planill =  $this->facturacionModel->consultar("SELECT * FROM app_preorden_master WHERE pre_id = {$existe_planilla['po_preid']}")->row();

                        $planilla = $planill['pre_correlativo'];
                    }

                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['n_id'], 12);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_anuladas[] = [
                        'n_id'            => $row['n_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'n_correlativo' => $documento['doc_prefijo'] . $row['n_correlativo'],
                        'correlativo'   => $row['n_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['n_total'], $row['div_locale'], $row['div_simbolo']),
                        'n_fecha'         => $row['n_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['n_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'planilla'      => $planilla
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_anuladas
            ]);
        }
    }
    public function obtenerOrdendeEntregaAnualesCreditos()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {


            $draw = $_POST['draw'];
            $row = $_POST['start'];
            $rowperpage = $_POST['length']; // Rows display per page
            $columnIndex = $_POST['order'][0]['column']; // Column index
            $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value'];

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            $documento = $this->facturacionModel->obtenerDocumento(12);

            $array_anuladas   = [];

            if ($sucursal == 0) {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio";
                }
            } else {
                if ($mes == 0) {
                    $peticion = "YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                } else {
                    $peticion = "MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal";
                }
            }

            $totalRecordwithFilter = "";
            ## Search 
            $searchQuery = " ";
            if ($searchValue != '') {
                $searchQuery = " AND (n.n_id LIKE '%" . $searchValue . "%' OR 
            c.cli_dni LIKE '%" . $searchValue . "%' OR c.cli_razon_social LIKE '%" . $searchValue . "%' OR n.n_total LIKE '%" . $searchValue . "%' OR n.n_neto LIKE '%" . $searchValue . "%' OR n.n_subtotal LIKE '%" . $searchValue . "%') ";
            }

            ## Total number of records without filtering
            $totalRecords = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=4) AND $peticion ORDER BY n.n_id DESC")->count();

            $totalRecordwithFilter = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=4) AND $peticion $searchQuery ORDER BY n.n_id DESC")->count();

            ## Fetch records
            $n_pagas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
            FROM app_orden_de_entrega n
            JOIN app_divisas d ON d.div_id = n.n_divid
            JOIN app_clientes c ON c.cli_id = n.n_cliid 
            WHERE (n.n_estatus=4) AND $peticion " . $searchQuery . " ORDER BY " . $columnName . " " . $columnSortOrder . " LIMIT " . $row . "," . $rowperpage)->all();

            if (is_countable($n_pagas) && count($n_pagas)) {
                foreach ($n_pagas as $row) {
                    $existe_planilla =  $this->facturacionModel->consultar("SELECT * FROM app_planilla_orden_de_entrega WHERE po_nid = {$row['n_id']}")->row();

                    $planilla = '';

                    if ($existe_planilla) {
                        $planill =  $this->facturacionModel->consultar("SELECT * FROM app_preorden_master WHERE pre_id = {$existe_planilla['po_preid']}")->row();

                        $planilla = $planill['pre_correlativo'];
                    }

                    $acumulado = $this->facturacionModel->obtenerAcumulado($row['n_id'], 12);
                    $acumulado_total = ($acumulado['total']) ?? 0;
                    $array_anuladas[] = [
                        'n_id'            => $row['n_id'],
                        'cli_razon_social'       => $row['cli_razon_social'],
                        'uri'           => 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'n_correlativo' => $documento['doc_prefijo'] . $row['n_correlativo'],
                        'correlativo'   => $row['n_correlativo'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         =>  Moneda::moneda($row['n_total'], $row['div_locale'], $row['div_simbolo']),
                        'n_fecha'         => $row['n_fecha'],
                        'acumulado'     =>  Moneda::moneda($acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'pendiente'     =>  Moneda::moneda($row['n_total'] - $acumulado_total, $row['div_locale'], $row['div_simbolo']),
                        'planilla'      => $planilla
                    ];
                }
            }

            echo json_encode([
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $array_anuladas
            ]);
        }
    }
    public function obtenerOrdendeEntrega()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio = $this->solicitud->sanitize($_POST['anio'], FILTER_SANITIZE_NUMBER_INT);
            $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {
                if ($sucursal == 0) {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=1 AND YEAR(n.n_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=0 OR n.n_estatus=2) AND YEAR(n.n_fecha)=$anio")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n 
                        JOIN app_divisas d ON d.div_id = n.n_divid 
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=3 AND YEAR(n.n_fecha)=$anio")->count();
                        $n_creditos = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=4) AND YEAR(n.n_fecha)=$anio")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=1 AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=0 OR n.n_estatus=2) AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                          WHERE n.n_estatus=3 AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio")->count();
                        $n_creditos = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=4) AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio")->count();
                    }
                } else {
                    if ($mes == 0) {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=1 AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=0 OR n.n_estatus=2) AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=3 AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_creditos = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=4) AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                    } else {
                        $n_finalizadas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=1 AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_pendientes = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=0 OR n.n_estatus=2) AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_anuladas = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE n.n_estatus=3 AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                        $n_creditos = $this->facturacionModel->consultar("SELECT n.n_id, n.n_correlativo, n.n_fecha, n.n_total, d.*, c.cli_id, c.cli_dni, c.cli_razon_social 
                        FROM app_orden_de_entrega n
                        JOIN app_divisas d ON d.div_id = n.n_divid
                        JOIN app_clientes c ON c.cli_id = n.n_cliid 
                        WHERE (n.n_estatus=4) AND MONTH(n.n_fecha)=$mes AND YEAR(n.n_fecha)=$anio AND n.n_surcid=$sucursal")->count();
                    }
                }

                Http::json_response([
                    "pendientes" => $n_pendientes,
                    "pagadas" => $n_finalizadas,
                    "anuladas" => $n_anuladas,
                    "creditos" => $n_creditos
                ]);
            }
            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    public function obtenerNotadeCreditoDetalle(int $id)
    {
        if ('GET' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $total = 0;
            $array_pagos = [];

            if (!empty($id)) {

                $id = $this->solicitud->sanitize($id, FILTER_SANITIZE_NUMBER_INT);

                $pagos = $this->facturacionModel->obtenerNotadeCreditoDetalle($id);

                if (is_countable($pagos) && count($pagos)) {
                    foreach ($pagos as $row) {
                        $documento = $this->facturacionModel->obtenerDocumento($row['credet_docid']);
                        if ($documento['doc_id'] == 1) {
                            $ruta = 'notasdeentregaeditar/verFactura/' . $row['credet_idfac'];
                        } else {
                            $ruta = 'poseditar/verFactura/' . $row['credet_idfac'];
                        }
                        $array_pagos[] = [
                            'ruta' => ruta_base() . $ruta,
                            'documento' => $documento['doc_prefijo'] . ' ID: ' . $row['credet_idfac'],
                            'monto' => Moneda::moneda($row['credet_monto'], $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                            'fecha' => $row['credet_fecha']
                        ];
                        $total += $row['credet_monto'];
                    }
                    $total = Moneda::moneda($total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']);
                }
            }

            Http::json_response([
                'pagos' => $array_pagos,
                'total' => $total
            ]);
        }
    }

    public function buscarLineas()
    {
        if ('GET' == $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $buscar = $this->solicitud->sanitize($_GET['buscar'], FILTER_SANITIZE_STRING);
            $filtro = $this->solicitud->sanitize($_GET['filtro'], FILTER_SANITIZE_NUMBER_INT);
            $sucursal = $this->solicitud->sanitize($_GET['sucursal'], FILTER_SANITIZE_NUMBER_INT);
            $buscar = strtolower($buscar);

            $timeZone = new DateTimeZone('America/Caracas');
            $fecha_desde = (new DateTime(null, $timeZone))->modify('first day of last month')->format('Y-m-d');
            $fecha_hasta = date('Y-m-d');

            $array_lineas = [];
            $notas = $this->facturacionModel->buscarLineasNEV($buscar, $filtro, $fecha_desde, $fecha_hasta, $sucursal);
            $ordenes = $this->facturacionModel->buscarLineasORDENES($buscar, $filtro, $fecha_desde, $fecha_hasta, $sucursal);
            $facuras = $this->facturacionModel->buscarLineasFACV($buscar, $filtro, $fecha_desde, $fecha_hasta, $sucursal);
            $pedidos = $this->facturacionModel->buscarLineasPEDV($buscar, $filtro, $fecha_desde, $fecha_hasta, $sucursal);
            $presupuesto = $this->facturacionModel->buscarLineasPRESV($buscar, $filtro, $fecha_desde, $fecha_hasta, $sucursal);

            if (is_countable($notas) && count($notas)) {
                foreach ($notas as $row) {
                    $divisa = $this->facturacionModel->obtenerDivisa($row['ne_divid']);
                    $array_lineas[] = [
                        'ruta_documento'    => ruta_base() . 'notasdeentregaeditar/verFactura/' . $row['ne_id'],
                        'correlativo'       => 'NEV' . $row['ne_correlativo'],
                        'cliente'           => $row['cli_razon_social'],
                        'ruta_producto'     => ruta_base() . 'productos/editar/' . $row['neart_proid'],
                        'id_pro'            => $row['neart_proid'],
                        'cantidad'          => $row['neart_procantidad'],
                        'art_codigo'        => $row['neart_procodigo'],
                        'art_nombre'        => $row['neart_propnombre'],
                        'total'             => Moneda::moneda($row['neart_prototal'], $divisa['div_locale'], $divisa['div_simbolo']),
                        'fecha'             => $row['fecha']
                    ];
                }
            }

            if (is_countable($ordenes) && count($ordenes)) {
                foreach ($ordenes as $row) {
                    $divisa = $this->facturacionModel->obtenerDivisa($row['n_divid']);
                    $array_lineas[] = [
                        'ruta_documento'    => ruta_base() . 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'correlativo'       => 'ORNDENV' . $row['n_correlativo'],
                        'cliente'           => $row['cli_razon_social'],
                        'ruta_producto'     => ruta_base() . 'productos/editar/' . $row['nart_proid'],
                        'id_pro'            => $row['nart_proid'],
                        'cantidad'          => $row['nart_procantidad'],
                        'art_codigo'        => $row['nart_procodigo'],
                        'art_nombre'        => $row['nart_propnombre'],
                        'total'             => Moneda::moneda($row['nart_prototal'], $divisa['div_locale'], $divisa['div_simbolo']),
                        'fecha'             => $row['fecha']
                    ];
                }
            }

            if (is_countable($facuras) && count($facuras)) {
                foreach ($facuras as $row) {
                    $divisa = $this->facturacionModel->obtenerDivisa($row['fm_divid']);
                    $array_lineas[] = [
                        'ruta_documento'    => ruta_base() . 'poseditar/verFactura/' . $row['fm_id'],
                        'correlativo'       => 'FACV' . $row['fm_correlativo'],
                        'cliente'           => $row['cli_razon_social'],
                        'ruta_producto'     => ruta_base() . 'productos/editar/' . $row['fa_proid'],
                        'id_pro'            => $row['fa_proid'],
                        'cantidad'          => $row['fa_procantidad'],
                        'art_codigo'        => $row['fa_procodigo'],
                        'art_nombre'        => $row['fa_propnombre'],
                        'total'             => Moneda::moneda($row['fa_prototal'], $divisa['div_locale'], $divisa['div_simbolo']),
                        'fecha'             => $row['fecha']
                    ];
                }
            }

            if (is_countable($pedidos) && count($pedidos)) {
                foreach ($pedidos as $row) {
                    $divisa = $this->facturacionModel->obtenerDivisa($row['pe_divid']);
                    $array_lineas[] = [
                        'ruta_documento'    => ruta_base() . 'pedidoseditar/verFactura/' . $row['pe_id'],
                        'correlativo'       => 'PEDV' . $row['pe_correlativo'],
                        'cliente'           => $row['cli_razon_social'],
                        'ruta_producto'     => ruta_base() . 'productos/editar/' . $row['peart_proid'],
                        'id_pro'            => $row['peart_proid'],
                        'cantidad'          => $row['peart_procantidad'],
                        'art_codigo'        => $row['peart_procodigo'],
                        'art_nombre'        => $row['peart_propnombre'],
                        'total'             => Moneda::moneda($row['peart_prototal'], $divisa['div_locale'], $divisa['div_simbolo']),
                        'fecha'             => $row['fecha']
                    ];
                }
            }

            if (is_countable($presupuesto) && count($presupuesto)) {
                foreach ($presupuesto as $row) {
                    $divisa = $this->facturacionModel->obtenerDivisa($row['pre_divid']);
                    $array_lineas[] = [
                        'ruta_documento'    => ruta_base() . 'presupuestoeditar/verFactura/' . $row['pre_id'],
                        'correlativo'       => 'PRESV' . $row['pre_correlativo'],
                        'cliente'           => $row['cli_razon_social'],
                        'ruta_producto'     => ruta_base() . 'productos/editar/' . $row['preart_proid'],
                        'id_pro'            => $row['preart_proid'],
                        'cantidad'          => $row['preart_procantidad'],
                        'art_codigo'        => $row['preart_procodigo'],
                        'art_nombre'        => $row['preart_propnombre'],
                        'total'             => Moneda::moneda($row['preart_prototal'], $divisa['div_locale'], $divisa['div_simbolo']),
                        'fecha'             => $row['fecha']
                    ];
                }
            }

            Http::json_response($array_lineas);
        }
    }

    public function guardarCliente()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $newCliContacto = new ClienteContactos();
            $cliente_direccion_envio_model = new Clientedireccionenvios();
            $cliente_model = new Cliente();

            $ruta           = filter_input(INPUT_POST, 'ruta', FILTER_SANITIZE_STRING);
            $cli_tipodoc    = filter_input(INPUT_POST, 'cli_tipodoc', FILTER_SANITIZE_NUMBER_INT);
            $cli_dni        = filter_input(INPUT_POST, 'cli_dni', FILTER_SANITIZE_STRING);
            $razon_social   = filter_input(INPUT_POST, 'cli_razon_social', FILTER_SANITIZE_STRING);
            $cli_telefono   = filter_input(INPUT_POST, 'cli_telefono', FILTER_SANITIZE_STRING);
            $cli_direccion  = filter_input(INPUT_POST, 'cli_direccion', FILTER_SANITIZE_STRING);
            $cli_natural    = ('true' == filter_input(INPUT_POST, 'cli_natural')) ? 1 : 0;

            if (empty($cli_tipodoc))
                $this->array_errors[] = "El campo cedula de identidad es obligatorio.";
            if (empty($cli_dni))
                $this->array_errors[] = "El campo Tipo de documento es obligatorio.";
            if (empty($razon_social))
                $this->array_errors[] = "El campo Razón social es obligatorio.";
            if (empty($cli_telefono))
                $this->array_errors[] = "El campo Telefono es obligatorio.";
            if (empty($cli_direccion))
                $this->array_errors[] = "El campo Direccion es obligatorio.";

            if (empty($this->array_errors)) {

                if (empty($_POST['cli_email'])) {
                    $cli_email = NULL;
                } else {
                    $cli_email = filter_input(INPUT_POST, 'cli_email', FILTER_VALIDATE_EMAIL);
                    if (!$cli_email)
                        $this->array_errors[] = 'Correo invalido';
                    if ($cliente_model->existe('cli_email', $cli_email))
                        $this->array_errors[] = "El correo electronico $cli_email ya se encuentra en uso";
                }

                if (empty($cli_telefono)) {
                    $cli_telefono = NULL;
                } else {
                    if (strlen($cli_telefono) < 15 || strlen($cli_telefono) > 50)
                        $this->array_errors[] = 'El número de telefono es incorrecto';
                }

                if ($cliente_model->existe('cli_dni', $cli_dni))
                    $this->array_errors[] = "La cedula de identidad $cli_dni ya se encuentra en uso";

                //if (valida_email($cli_email) == false)
                //array_push($this->array_errors, "La correo $cli_email no es correcto");
                if (empty($this->array_errors) && empty($this->array_errors)) {
                    $data_id = $cliente_model->guardar([
                        'cli_tipodocid'     => $cli_tipodoc,
                        'cli_dni'           => $cli_dni,
                        'cli_razon_social'  => $razon_social,
                        'cli_email'         => $cli_email,
                        'cli_telefono'      => $cli_telefono,
                        'cli_direccion'     => $cli_direccion,
                        'cli_contribuyente' => 1,
                        'cli_fecha_reg'     => date('Y-m-d H:i:s'),
                        'cli_natural'       => $cli_natural
                    ]);
                    if ($data_id) {

                        $newCliContacto->guardar([
                            'ccon_cliid'    => $data_id,
                            'ccon_nombre'   => $razon_social,
                            'ccon_cargo'    => 'Personal',
                            'ccon_telefono' => $cli_telefono,
                            'ccon_email'    => $cli_email,
                        ], true);

                        $cliente_direccion_envio_model->guardar([
                            'cde_cliid'     => $data_id,
                            'cde_direccion' => $cli_direccion
                        ]);

                        Http::json_response(ruta_base() . $ruta . "/nuevaFactura/$data_id");
                    } else {
                        Http::json_response(false);
                    }
                }
            }

            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    public function finalizarNota()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if ($this->module->has_module_action_permission('facturacion', 'status', $_SESSION['user_data']['emp_id'])) {

                $id = $this->solicitud->sanitize($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
                $estatus = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_NUMBER_INT);

                $newNotaDeEntrega = new Notasdeentrega();

                if ($newNotaDeEntrega->editar($id, [
                    'ne_estatus' => $estatus
                ])) {
                    Http::json_response(true);
                } else {
                    Http::json_response(false);
                }
            } else {
                Http::json_response('Usted no posee permisos para cambiar el estatus de los documentos');
            }
        }
    }

    public function finalizarOrden()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if ($this->module->has_module_action_permission('facturacion', 'status', $_SESSION['user_data']['emp_id'])) {

                $id = $this->solicitud->sanitize($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
                $estatus = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_NUMBER_INT);

                $newNotaDeEntrega = new Ordendeentrega();

                if ($newNotaDeEntrega->editar($id, [
                    'n_estatus' => $estatus
                ])) {
                    Http::json_response(true);
                } else {
                    Http::json_response(false);
                }
            } else {
                Http::json_response('Usted no posee permisos para cambiar el estatus de los documentos');
            }
        }
    }

    public function finalizarFactura()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if ($this->module->has_module_action_permission('facturacion', 'status', $_SESSION['user_data']['emp_id'])) {

                $id = $this->solicitud->sanitize($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
                $estatus = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_NUMBER_INT);

                $newFactura = new Pos();

                if ($newFactura->editar($id, [
                    'fm_estatus' => $estatus
                ])) {
                    Http::json_response(true);
                } else {
                    Http::json_response(false);
                }
            } else {
                Http::json_response('Usted no posee permisos para cambiar el estatus de los documentos');
            }
        }
    }

    public function finalizarPedido()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if ($this->module->has_module_action_permission('facturacion', 'status', $_SESSION['user_data']['emp_id'])) {

                $id = $this->solicitud->sanitize($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
                $estatus = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_NUMBER_INT);

                $newPedidos = new Pedidos();

                if ($newPedidos->editar($id, [
                    'pe_estatus' => $estatus
                ])) {
                    Http::json_response(true);
                } else {
                    Http::json_response(false);
                }
            } else {
                Http::json_response('Usted no posee permisos para cambiar el estatus de los documentos');
            }
        }
    }

    public function finalizarCredito()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if ($this->module->has_module_action_permission('facturacion', 'status', $_SESSION['user_data']['emp_id'])) {

                $id = $this->solicitud->sanitize($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
                $estatus = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_NUMBER_INT);

                $estatus = $estatus == 1 ? 0 : 1;

                $newCredito = new Notadecredito();

                if ($newCredito->editar($id, [
                    'cre_estatus' => $estatus
                ])) {
                    Http::json_response(true);
                } else {
                    Http::json_response(false);
                }
            } else {
                Http::json_response('Usted no posee permisos para cambiar el estatus de los documentos');
            }
        }
    }

    public function imprimir()
    {
        $id_factura     = filter_input(INPUT_GET, 'id_factura', FILTER_SANITIZE_NUMBER_INT);
        $id_impresora   = filter_input(INPUT_GET, 'id_impresora', FILTER_SANITIZE_NUMBER_INT);
        $factura        = $this->facturacionModel->obtenerCredito($id_factura);
        $impresora      = $this->facturacionModel->impresora($id_impresora);

        if ($factura && $impresora) {

            $divisa     = Moneda::Predeterminada();

            Http::json_response([
                'ip_puerto' =>  protocolo() . $impresora['ip_puerto'],
                'data' => [
                    'command' => 'generate_ticket_credito',
                    'args' => [[
                        'fecha_impresion'   => date('d-m-Y H:i:s'),
                        'fecha_creacion'    => date('d-m-Y H:i:s', strtotime($factura['cre_fecha'])),
                        'observacion'       => empty($factura['cre_descripcion']) ? '' : $factura['cre_descripcion'],
                        'num_ticket'        => $factura['cre_id'],
                        'rif'               => $factura['cli_dni'],
                        'clients'           => $factura['cli_razon_social'],
                        'direccion'         => $factura['cli_direccion'],
                        'telefono'          => $factura['cli_telefono'],
                        'cajero'            => $factura['einfo_nombres'] . ' ' . $factura['einfo_apellidos'],
                        'monto_total'       => Moneda::moneda($factura['cre_monto'], $divisa['locale'], $divisa['symbol']),
                    ]]
                ]
            ]);
        } else {
            $this->array_errors[] = 'Acción prohibida';
        }

        Http::json_response(['errors' => $this->array_errors]);
    }

    public function cne()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if (empty($_POST['cli_dni']))
                Http::json_response('El numero del documento es obligatorio');
            if (empty($_POST['tipo']))
                Http::json_response('El campo Tipo de documento es obligatorio');

            if (empty($this->array_errors)) {

                $cli_tipo             =  $this->solicitud->sanitize($_POST['tipo'], FILTER_SANITIZE_NUMBER_INT);
                $cli_dni            = $this->solicitud->sanitize($_POST['cli_dni'], FILTER_SANITIZE_STRING);

                $tipo = $dni = '';
                if ($cli_tipo == 2) {
                    $dni = str_replace('V', '', $cli_dni);

                    if (strlen($dni) < 7) {
                        Http::json_response('Verifique los numeros del documento.');
                    }
                    $tipo = 'V';
                } else {
                    $dni = str_replace('J', '', $cli_dni);
                    $tipo = 'J';
                    if (strlen($dni) < 8) {
                        Http::json_response('Verifique los numeros del documento.');
                    }
                }

                $url = "http://www.cne.gob.ve/web/registro_electoral/ce.php?nacionalidad=" . $tipo . "&cedula=" . $dni;
                $resource = self::geUrl($url);
                if ($resource == false) {
                    Http::json_response('No hay repuesta del servidor CNE.');
                } else {
                    $text = strip_tags($resource);
                    $findme = 'REGISTRO ELECTORAL'; // Identifica que si es población Votante
                    $pos = strpos($text, $findme);

                    $findme2 = 'ADVERTENCIA'; // Identifica que si es población Votante
                    $pos2 = strpos($text, $findme2);
                    $datoJson = [];
                    if ($pos == TRUE and $pos2 == FALSE) {
                        // Codigo buscar votante
                        $rempl = array('Cédula:', 'Nombre:', 'Estado:', 'Municipio:', 'Parroquia:', 'Centro:', 'Dirección:', 'SERVICIO ELECTORAL', 'Mesa:');
                        $r = trim(str_replace($rempl, '|', self::limpiarCampo($text)));
                        $resource = explode("|", $r);
                        $datos = explode(" ", self::limpiarCampo($resource[2]));

                        $cvestado = self::limpiarCampo($resource[3]);
                        $cvparroquia = self::limpiarCampo($resource[5]);
                        $cvmunicipio = self::limpiarCampo($resource[4]);
                        $direccion = self::limpiarCampo($resource[7]);
                        Http::json_response(['error' => 0, 'nacionalidad' => $tipo, 'cedula' => $dni, 'nombres' => $datos[0] . ' ' . $datos[1], 'apellidos' => $datos[2] . ' ' . $datos[3], 'inscrito' => 'SI', 'cvestado' => $cvestado, 'cvmunicipio' => $cvmunicipio, 'cvparroquia' => $cvparroquia, 'direccion' => $direccion]);
                    } elseif ($pos == FALSE and $pos2 == FALSE) {
                        Http::json_response('No inscrito CNE.');
                    } elseif ($pos == FALSE and $pos2 == TRUE) {
                        Http::json_response('No inscrito CNE.');
                    } else {
                        Http::json_response('No inscrito CNE.');
                    }
                }
            }
        }
    }

    public static function geUrl($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // almacene en una variable
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3000);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3000); //timeout in seconds
        if (curl_exec($curl) === false) {
            //echo 'Curl error: ' . curl_error($curl);
            //curl_close($curl);
            $return = false;
        } else {
            $return = curl_exec($curl);
        }
        curl_close($curl);
        return $return;
    }

    public static function limpiarCampo($valor)
    { //Con esto limpiamos los errores de la pagina
        if ($valor) {
            $rempl = array('\n', '\t');
            $r = trim(str_replace($rempl, ' ', $valor));
            $vl = str_replace("\r", "", str_replace("\n", "", str_replace("\t", "", $r)));
        } else {
            $vl = " ";
        }

        return $vl;
    }

    public function obtenerIngresosDiarios()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if (empty($this->array_errors)) {

                $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);

                $array_notas        = [];
                $array_notas_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;

                if ($sucursal == 0 || $sucursal == '') {
                    $movimiento = $this->facturacionModel->consultar("SELECT fa.fab_empid,fa.fab_monto as monto, fab_metodo, fa.fab_fecha,WEEKDAY(fa.fab_fecha) as n_dia_semana, b.ban_codigo, b.ban_descripcion, bc.bc_cuenta, bc.bc_alias, bc.bc_tipo, m.mp_nombre, d.*, su.* 
                    FROM app_movimientos fa 
                    JOIN app_sucursales su ON su.su_id=fa.fab_sucursal  
                    JOIN app_cuentas_metodopago cm ON cm.cmp_id = fa.fab_cmpid
                    JOIN app_bancos_cuentas bc ON bc.bc_id = cm.cmp_cueid
                    JOIN app_bancos b ON b.ban_id = bc.bc_banid
                    JOIN app_metodopago_divisa md ON  md.md_id = cm.cmp_mdid
                    JOIN app_metodopago m ON m.mp_id = md.md_mpid
                    JOIN app_divisas d ON d.div_id = md.md_divid 
                    WHERE fa.fab_retiro = 0 AND fa.fab_fecha>=(CURDATE()-INTERVAL WEEKDAY(CURDATE()) DAY) AND fa.fab_fecha<(CURDATE()-INTERVAL WEEKDAY(CURDATE())-7 DAY)  
                    ORDER BY DAY(fa.fab_fecha)")->all();
                } else {
                    $movimiento = $this->facturacionModel->consultar("SELECT fa.fab_empid,fa.fab_monto as monto, fab_metodo, fa.fab_fecha,WEEKDAY(fa.fab_fecha) as n_dia_semana, b.ban_codigo, b.ban_descripcion, bc.bc_cuenta, bc.bc_alias, bc.bc_tipo, m.mp_nombre, d.*, su.* 
                    FROM app_movimientos fa 
                    JOIN app_sucursales su ON su.su_id=fa.fab_sucursal  
                    JOIN app_cuentas_metodopago cm ON cm.cmp_id = fa.fab_cmpid
                    JOIN app_bancos_cuentas bc ON bc.bc_id = cm.cmp_cueid
                    JOIN app_bancos b ON b.ban_id = bc.bc_banid
                    JOIN app_metodopago_divisa md ON  md.md_id = cm.cmp_mdid
                    JOIN app_metodopago m ON m.mp_id = md.md_mpid
                    JOIN app_divisas d ON d.div_id = md.md_divid   
                    WHERE fa.fab_sucursal = $sucursal AND fa.fab_retiro = 0 AND fa.fab_fecha>=(CURDATE()-INTERVAL WEEKDAY(CURDATE()) DAY) AND fa.fab_fecha<(CURDATE()-INTERVAL WEEKDAY(CURDATE())-7 DAY)  
                    ORDER BY DAY(fa.fab_fecha)")->all();
                }

                $ingresosegresos_model = new Ingresosegresos();

                $facturas = $this->facturacionModel->consultar("SELECT fm.fm_id id, WEEKDAY(fm.fm_fecha) as n_dia_semana,fm.fm_correlativo correlativo, fm.fm_fecha fecha, fm_articulos_total art_total, fm.fm_total total, d.*, c.cli_razon_social cliente,su.* 
                    FROM app_factura_master fm 
                    JOIN app_sucursales su ON su.su_id=fm.fm_surcid 
                    JOIN app_divisas d ON d.div_id = fm.fm_divid
                    JOIN app_clientes c ON c.cli_id = fm.fm_cliid 
                    WHERE fm.fm_fecha>=(CURDATE()-INTERVAL WEEKDAY(CURDATE()) DAY) AND fm.fm_fecha<(CURDATE()-INTERVAL WEEKDAY(CURDATE())-7 DAY)")->all();

                $notas = $this->facturacionModel->consultar("SELECT ne.ne_id id,WEEKDAY(ne.ne_fecha) as n_dia_semana, ne.ne_correlativo correlativo, ne.ne_fecha fecha, ne_articulos_total art_total, ne.ne_total total, d.*, c.cli_razon_social cliente, su.* 
                    FROM app_notas_de_entrega ne 
                    JOIN app_sucursales su ON su.su_id=ne.ne_surcid 
                    JOIN app_divisas d ON d.div_id = ne.ne_divid
                    JOIN app_clientes c ON c.cli_id = ne.ne_cliid 
                    WHERE ne.ne_fecha>=(CURDATE()-INTERVAL WEEKDAY(CURDATE()) DAY) AND ne.ne_fecha<(CURDATE()-INTERVAL WEEKDAY(CURDATE())-7 DAY)")->all();

                $ordenes = $this->facturacionModel->consultar("SELECT n.n_id id, WEEKDAY(n.n_fecha) as n_dia_semana,n.n_correlativo correlativo, n.n_fecha fecha, n_articulos_total art_total, n.n_total total, d.*, c.cli_razon_social cliente,su.* 
                    FROM app_orden_de_entrega n
                    JOIN app_sucursales su ON su.su_id=n.n_surcid 
                    JOIN app_divisas d ON d.div_id = n.n_divid
                    JOIN app_clientes c ON c.cli_id = n.n_cliid 
                    WHERE n.n_fecha>=(CURDATE()-INTERVAL WEEKDAY(CURDATE()) DAY) AND n.n_fecha<(CURDATE()-INTERVAL WEEKDAY(CURDATE())-7 DAY)")->all();

                $acumulado_t = 0;
                $pendiente = 0;
                if (is_countable($facturas) && count($facturas)) {
                    foreach ($facturas as $row) {

                        $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 2);

                        if ($row['div_id'] != $this->divisa_master['div_id']) {
                            $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                            $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                        }

                        $acumulado_total = ($acumulado['total']) ?? 0;
                        $acumulado_t = $acumulado_total;
                        $pendiente = $row['total'] - $acumulado_total;

                        if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row['n_dia_semana']] = [
                                'n_dia_semana'  => $row['n_dia_semana'],
                                'venta_USD'         => 0,
                                'venta_BS'         => 0,
                                'acumulado' => round($acumulado_t, 2),
                                'pendiente' => round($pendiente, 2),
                            ];
                            $array_notas_id[] = $row['n_dia_semana'];
                        } else {
                            $array_notas[$row['n_dia_semana']]['acumulado']      += round($acumulado_t, 2);
                            $array_notas[$row['n_dia_semana']]['pendiente']      += round($pendiente, 2);
                        }
                    }
                }

                if (is_countable($notas) && count($notas)) {
                    foreach ($notas as $row) {

                        $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 1);

                        if ($row['div_id'] != $this->divisa_master['div_id']) {
                            $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                            $row['total'] = $factor['df_factor'];
                            $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                        }

                        $acumulado_total = ($acumulado['total']) ?? 0;
                        $acumulado_t = $acumulado_total;
                        $pendiente = $row['total'] - $acumulado_total;
                        if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row['n_dia_semana']] = [
                                'n_dia_semana'  => $row['n_dia_semana'],
                                'venta_USD'         => 0,
                                'venta_BS'         => 0,
                                'acumulado' => round($acumulado_t, 2),
                                'pendiente' => round($pendiente, 2),
                            ];
                            $array_notas_id[] = $row['n_dia_semana'];
                        } else {
                            $array_notas[$row['n_dia_semana']]['acumulado']      += round($acumulado_t, 2);
                            $array_notas[$row['n_dia_semana']]['pendiente']      += round($pendiente, 2);
                        }
                    }
                }

                if (is_countable($ordenes) && count($ordenes)) {
                    foreach ($ordenes as $row) {

                        $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 12);

                        if ($row['div_id'] != $this->divisa_master['div_id']) {
                            $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                            $row['total'] = $factor['df_factor'];
                            $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                        }

                        $acumulado_total = ($acumulado['total']) ?? 0;
                        $acumulado_t = $acumulado_total;
                        $pendiente = $row['total'] - $acumulado_total;

                        if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row['n_dia_semana']] = [
                                'n_dia_semana'  => $row['n_dia_semana'],
                                'venta_USD'         => 0,
                                'venta_BS'         => 0,
                                'acumulado' => round($acumulado_t, 2),
                                'pendiente' => round($pendiente, 2),
                            ];
                            $array_notas_id[] = $row['n_dia_semana'];
                        } else {
                            $array_notas[$row['n_dia_semana']]['acumulado']      += round($acumulado_t, 2);
                            $array_notas[$row['n_dia_semana']]['pendiente']      += round($pendiente, 2);
                        }
                    }
                }

                if (is_countable($movimiento) && count($movimiento)) {
                    foreach ($movimiento as $row) {
                        if ($row['div_id'] == 1) {
                            if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                                $array_notas[$row['n_dia_semana']] = [
                                    'n_dia_semana'  => $row['n_dia_semana'],
                                    'venta_USD'         => 0,
                                    'venta_BS'         => round($row['monto'], 2),
                                    'acumulado' => 0,
                                    'pendiente' => 0,
                                ];
                                $array_notas_id[] = $row['n_dia_semana'];
                            } else {
                                $array_notas[$row['n_dia_semana']]['venta_BS']      += round($row['monto'], 2);
                            }
                        }
                        if ($row['div_id'] == 2) {
                            if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                                $array_notas[$row['n_dia_semana']] = [
                                    'n_dia_semana'  => $row['n_dia_semana'],
                                    'venta_USD'         => round($row['monto'], 2),
                                    'venta_BS'         => 0,
                                    'acumulado' => 0,
                                    'pendiente' => 0,
                                ];
                                $array_notas_id[] = $row['n_dia_semana'];
                            } else {
                                $array_notas[$row['n_dia_semana']]['venta_USD']      += round($row['monto'], 2);
                            }
                        }
                    }
                }

                Http::json_response([
                    'dias_semana'   => $array_notas,
                    'TOTAL' => 2,
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function proveedoresReportes()
    {

        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $sucursal = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);
            $proveedor = filter_input(INPUT_GET, 'proveedor', FILTER_SANITIZE_NUMBER_INT);

            if (empty($fecha_desde))
                $fecha_desde = (new DateTime(null, $this->timeZone))->modify('first day of this month')->format('Y-m-d');

            if (empty($fecha_hasta))
                $fecha_hasta = date('Y-m-d');

            if (empty($this->array_errors)) {

                if (!validateDate($fecha_desde, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha desde es incorrecta.';
                if (!validateDate($fecha_hasta, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha hasta es incorrecta.';

                if (empty($this->array_errors)) {

                    $artic_total        = 0;
                    $costo_total        = 0;
                    $venta_total        = 0;
                    $totales_notas  = [];
                    $total_notas_id = [];
                    $ganancia = 0;

                    $notas =  $this->facturacionModel->obtenerProveedoresNEV($sucursal, $fecha_desde, $fecha_hasta);
                    $factura =  $this->facturacionModel->obtenerProveedoresFact($sucursal, $fecha_desde, $fecha_hasta);
                    $orden =  $this->facturacionModel->obtenerProveedoresOrden($sucursal, $fecha_desde, $fecha_hasta);


                    if (is_countable($notas) && count($notas)) {

                        foreach ($notas as $row) {
                            $factor2 = 1;

                            if ($row['ne_divid'] != $this->divisa_master['div_id']) {
                                $factor = $this->facturacionModel->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                $row['neart_procosto'] = round(($row['neart_procosto'] * $factor['df_factor']), 2);
                                $row['neart_prototal'] = round(($row['neart_prototal'] * $factor['df_factor']), 2);
                                $factor2 = $factor['df_factor'];
                            }

                            if ($row['neart_prototal'] > 1) {
                                $ganancia = $row['neart_prototal'] - ($row['neart_procosto'] * $row['neart_procantidad']);
                                $ga = ($ganancia * 100);
                                $ganc = ($row['neart_procosto'] * $row['neart_procantidad']);
                                if ($ga > 0 && $ganc > 0) {
                                    $ganancia_porct =  $ga / $ganc;
                                } else {
                                    $ganancia_porct = 0;
                                }
                            }

                            if ($row['pro_tipo'] == 2) {
                                $newpro = new ProductosCompuestos();
                                $prod_compuesto = $newpro->obtenerProductosCompuesto($row['pro_id']);

                                foreach ($prod_compuesto as $row2) {
                                    $proveed = $this->facturacionModel->obtenerProveedores($row2['pro_id']);

                                    foreach ($proveed as $row1) {

                                        if ($row2['pro_ccprecio'] > 1) {
                                            $ganancia = (($row2['pro_ccprecio'] * $row2['pro_cccant']) - ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad']);
                                            $ga = ($ganancia * 100);
                                            $ganc = ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                            if ($ga > 0 && $ganc > 0) {
                                                $ganancia_porct =  $ga / $ganc;
                                            } else {
                                                $ganancia_porct = 0;
                                            }
                                        }

                                        if ($proveedor == 0) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row2['pro_descripcion'],
                                                    'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                                    'cantidad'          => $row['neart_procantidad'],
                                                    'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['neart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                            }

                                            $artic_total +=  $ganancia;
                                            $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                            $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                        } else {
                                            if ($row1['prov_id'] == $proveedor) {
                                                if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                    $totales_notas[$row1['prov_id']] = [
                                                        'div_locale'        => $this->divisa_master['div_locale'],
                                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                                        'proveedor_id'      => $row1['prov_id'],
                                                        'productos'         => $row2['pro_descripcion'],
                                                        'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                                        'cantidad'          => $row['neart_procantidad'],
                                                        'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                                        'ganancia'          => $ganancia,
                                                        'sucursal'          => $row['su_nombre'],
                                                        'proveedor'         => $row1['prov_razonsocial'],
                                                    ];
                                                    $total_notas_id[] = $row1['prov_id'];
                                                } else {
                                                    $totales_notas[$row1['prov_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['cantidad']          += $row['neart_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                    $totales_notas[$row1['prov_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                                }

                                                $artic_total +=  $ganancia;
                                                $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                                $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                            }
                                        }
                                    }
                                }
                            } else {
                                $proveed = $this->facturacionModel->obtenerProveedores($row['pro_id']);

                                foreach ($proveed as $row1) {
                                    if ($proveedor == 0) {
                                        if (!in_array($row1['prov_id'], $total_notas_id)) {
                                            $totales_notas[$row1['prov_id']] = [
                                                'div_locale'        => $this->divisa_master['div_locale'],
                                                'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                'div_nombre'        => $this->divisa_master['div_nombre'],
                                                'proveedor_id'      => $row1['prov_id'],
                                                'productos'         => $row['pro_descripcion'],
                                                'costo'             => $row['neart_procosto'] * $row['neart_procantidad'],
                                                'cantidad'          => $row['neart_procantidad'],
                                                'venta'             => $row['neart_prototal'],
                                                'ganancia'          => $ganancia,
                                                'sucursal'          => $row['su_nombre'],
                                                'proveedor'         => $row1['prov_razonsocial'],
                                            ];
                                            $total_notas_id[] = $row1['prov_id'];
                                        } else {
                                            $totales_notas[$row1['prov_id']]['costo']       +=  $row['neart_procosto'] * $row['neart_procantidad'];
                                            $totales_notas[$row1['prov_id']]['cantidad']          += $row['neart_procantidad'];
                                            $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                            $totales_notas[$row1['prov_id']]['venta']          +=  $row['neart_prototal'];
                                        }

                                        $artic_total +=  $ganancia;
                                        $costo_total +=  $row['neart_procosto'] * $row['neart_procantidad'];
                                        $venta_total += $row['neart_prototal'];
                                    } else {
                                        if ($row1['prov_id'] == $proveedor) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row['pro_descripcion'],
                                                    'costo'             => $row['neart_procosto'] * $row['neart_procantidad'],
                                                    'cantidad'          => $row['neart_procantidad'],
                                                    'venta'             => $row['neart_prototal'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       +=  $row['neart_procosto'] * $row['neart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['neart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          +=  $row['neart_prototal'];
                                            }

                                            $artic_total += $ganancia;
                                            $costo_total +=  $row['neart_procosto'] * $row['neart_procantidad'];
                                            $venta_total += $row['neart_prototal'];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (is_countable($factura) && count($factura)) {

                        foreach ($factura as $row) {
                            $factor2 = 1;

                            if ($row['fm_divid'] != $this->divisa_master['div_id']) {
                                $factor = $this->facturacionModel->divisaFactor($row['fm_divid'], $this->divisa_master['div_id']);
                                $row['fa_procosto'] = round(($row['fa_procosto'] * $factor['df_factor']), 2);
                                $row['fa_prototal'] = round(($row['fa_prototal'] * $factor['df_factor']), 2);
                                $factor2 = $factor['df_factor'];
                            }

                            if ($row['fa_prototal'] > 1) {
                                $ganancia = $row['fa_prototal'] - ($row['fa_procosto'] * $row['fa_procantidad']);
                                $ga = ($ganancia * 100);
                                $ganc = ($row['fa_procosto'] * $row['fa_procantidad']);
                                if ($ga > 0 && $ganc > 0) {
                                    $ganancia_porct =  $ga / $ganc;
                                } else {
                                    $ganancia_porct = 0;
                                }
                            }

                            if ($row['pro_tipo'] == 2) {
                                $newpro = new ProductosCompuestos();
                                $prod_compuesto = $newpro->obtenerProductosCompuesto($row['pro_id']);

                                foreach ($prod_compuesto as $row2) {
                                    $proveed = $this->facturacionModel->obtenerProveedores($row['pro_id']);

                                    if ($row['fa_prototal'] > 1) {
                                        $ganancia = (($row2['pro_ccprecio'] * $row2['pro_cccant']) - ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }

                                    foreach ($proveed as $row1) {

                                        if ($proveedor == 0) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row['pro_descripcion'],
                                                    'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                                    'cantidad'          => $row['fa_procantidad'],
                                                    'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['fa_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          +=  ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                            }

                                            $artic_total +=  $ganancia;
                                            $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                            $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                        } else {
                                            if ($row1['prov_id'] == $proveedor) {
                                                if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                    $totales_notas[$row1['prov_id']] = [
                                                        'div_locale'        => $this->divisa_master['div_locale'],
                                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                                        'proveedor_id'      => $row1['prov_id'],
                                                        'productos'         => $row['pro_descripcion'],
                                                        'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                                        'cantidad'          => $row['fa_procantidad'],
                                                        'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                                        'ganancia'          => $ganancia,
                                                        'sucursal'          => $row['su_nombre'],
                                                        'proveedor'         => $row1['prov_razonsocial'],
                                                    ];
                                                    $total_notas_id[] = $row1['prov_id'];
                                                } else {
                                                    $totales_notas[$row1['prov_id']]['costo']       +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['cantidad']          += $row['fa_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                    $totales_notas[$row1['prov_id']]['venta']          +=  ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                                }

                                                $artic_total += $ganancia;
                                                $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                                $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                            }
                                        }
                                    }
                                }
                            } else {
                                $proveed = $this->facturacionModel->obtenerProveedores($row['pro_id']);

                                foreach ($proveed as $row1) {
                                    if ($proveedor == 0) {
                                        if (!in_array($row1['prov_id'], $total_notas_id)) {
                                            $totales_notas[$row1['prov_id']] = [
                                                'div_locale'        => $this->divisa_master['div_locale'],
                                                'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                'div_nombre'        => $this->divisa_master['div_nombre'],
                                                'proveedor_id'      => $row1['prov_id'],
                                                'productos'         => $row['pro_descripcion'],
                                                'costo'             => $row['fa_procosto'] * $row['fa_procantidad'],
                                                'cantidad'          => $row['fa_procantidad'],
                                                'venta'             => $row['fa_prototal'],
                                                'ganancia'          => $ganancia,
                                                'sucursal'          => $row['su_nombre'],
                                                'proveedor'         => $row1['prov_razonsocial'],
                                            ];
                                            $total_notas_id[] = $row1['prov_id'];
                                        } else {
                                            $totales_notas[$row1['prov_id']]['costo']       +=  $row['fa_procosto'] * $row['fa_procantidad'];
                                            $totales_notas[$row1['prov_id']]['cantidad']          += $row['fa_procantidad'];
                                            $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                            $totales_notas[$row1['prov_id']]['venta']          +=  $row['fa_prototal'];
                                        }

                                        $artic_total +=  $ganancia;
                                        $costo_total +=  $row['fa_procosto'] * $row['fa_procantidad'];
                                        $venta_total += $row['fa_prototal'];
                                    } else {
                                        if ($row1['prov_id'] == $proveedor) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row['pro_descripcion'],
                                                    'costo'             => $row['fa_procosto'] * $row['fa_procantidad'],
                                                    'cantidad'          => $row['fa_procantidad'],
                                                    'venta'             => $row['fa_prototal'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       +=  $row['fa_procosto'] * $row['fa_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['fa_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          +=  $row['fa_prototal'];
                                            }

                                            $artic_total += $ganancia;
                                            $costo_total +=  $row['fa_procosto'] * $row['fa_procantidad'];
                                            $venta_total += $row['fa_prototal'];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (is_countable($orden) && count($orden)) {

                        foreach ($orden as $row) {
                            $factor2 = 1;

                            if ($row['n_divid'] != $this->divisa_master['div_id']) {
                                $factor = $this->facturacionModel->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                $row['nart_procosto'] = round(($row['nart_procosto'] * $factor['df_factor']), 2);
                                $row['nart_prototal'] = round(($row['nart_prototal'] * $factor['df_factor']), 2);
                                $factor2 = $factor['df_factor'];
                            }

                            if ($row['nart_prototal'] > 1) {
                                $ganancia = $row['nart_prototal'] - ($row['nart_procosto'] * $row['nart_procantidad']);
                                $ga = ($ganancia * 100);
                                $ganc = ($row['nart_procosto'] * $row['nart_procantidad']);
                                if ($ga > 0 && $ganc > 0) {
                                    $ganancia_porct =  $ga / $ganc;
                                } else {
                                    $ganancia_porct = 0;
                                }
                            }

                            if ($row['pro_tipo'] == 2) {
                                $newpro = new ProductosCompuestos();
                                $prod_compuesto = $newpro->obtenerProductosCompuesto($row['pro_id']);

                                foreach ($prod_compuesto as $row2) {
                                    $proveed = $this->facturacionModel->obtenerProveedores($row2['pro_id']);

                                    foreach ($proveed as $row1) {

                                        if ($row2['pro_ccprecio'] > 1) {
                                            $ganancia = (($row2['pro_ccprecio'] * $row2['pro_cccant']) - ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad']);
                                            $ga = ($ganancia * 100);
                                            $ganc = ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                            if ($ga > 0 && $ganc > 0) {
                                                $ganancia_porct =  $ga / $ganc;
                                            } else {
                                                $ganancia_porct = 0;
                                            }
                                        }

                                        if ($proveedor == 0) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row2['pro_descripcion'],
                                                    'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'],
                                                    'cantidad'          => $row['nart_procantidad'],
                                                    'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['nart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                            }

                                            $artic_total +=  $ganancia;
                                            $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                            $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                        } else {
                                            if ($row1['prov_id'] == $proveedor) {
                                                if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                    $totales_notas[$row1['prov_id']] = [
                                                        'div_locale'        => $this->divisa_master['div_locale'],
                                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                                        'proveedor_id'      => $row1['prov_id'],
                                                        'productos'         => $row2['pro_descripcion'],
                                                        'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'],
                                                        'cantidad'          => $row['nart_procantidad'],
                                                        'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'],
                                                        'ganancia'          => $ganancia,
                                                        'sucursal'          => $row['su_nombre'],
                                                        'proveedor'         => $row1['prov_razonsocial'],
                                                    ];
                                                    $total_notas_id[] = $row1['prov_id'];
                                                } else {
                                                    $totales_notas[$row1['prov_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['cantidad']          += $row['nart_procantidad'];
                                                    $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                    $totales_notas[$row1['prov_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                                }

                                                $artic_total +=  $ganancia;
                                                $costo_total +=  ($row2['pro_costo'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                                $venta_total += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['nart_procantidad'];
                                            }
                                        }
                                    }
                                }
                            } else {
                                $proveed = $this->facturacionModel->obtenerProveedores($row['pro_id']);

                                foreach ($proveed as $row1) {
                                    if ($proveedor == 0) {
                                        if (!in_array($row1['prov_id'], $total_notas_id)) {
                                            $totales_notas[$row1['prov_id']] = [
                                                'div_locale'        => $this->divisa_master['div_locale'],
                                                'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                'div_nombre'        => $this->divisa_master['div_nombre'],
                                                'proveedor_id'      => $row1['prov_id'],
                                                'productos'         => $row['pro_descripcion'],
                                                'costo'             => $row['nart_procosto'] * $row['nart_procantidad'],
                                                'cantidad'          => $row['nart_procantidad'],
                                                'venta'             => $row['nart_prototal'],
                                                'ganancia'          => $ganancia,
                                                'sucursal'          => $row['su_nombre'],
                                                'proveedor'         => $row1['prov_razonsocial'],
                                            ];
                                            $total_notas_id[] = $row1['prov_id'];
                                        } else {
                                            $totales_notas[$row1['prov_id']]['costo']       +=  $row['neart_procosto'] * $row['nart_procantidad'];
                                            $totales_notas[$row1['prov_id']]['cantidad']          += $row['nart_procantidad'];
                                            $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                            $totales_notas[$row1['prov_id']]['venta']          +=  $row['nart_prototal'];
                                        }

                                        $artic_total +=  $ganancia;
                                        $costo_total +=  $row['nart_procosto'] * $row['nart_procantidad'];
                                        $venta_total += $row['nart_prototal'];
                                    } else {
                                        if ($row1['prov_id'] == $proveedor) {
                                            if (!in_array($row1['prov_id'], $total_notas_id)) {
                                                $totales_notas[$row1['prov_id']] = [
                                                    'div_locale'        => $this->divisa_master['div_locale'],
                                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                                    'proveedor_id'      => $row1['prov_id'],
                                                    'productos'         => $row['pro_descripcion'],
                                                    'costo'             => $row['nart_procosto'] * $row['nart_procantidad'],
                                                    'cantidad'          => $row['nart_procantidad'],
                                                    'venta'             => $row['nart_prototal'],
                                                    'ganancia'          => $ganancia,
                                                    'sucursal'          => $row['su_nombre'],
                                                    'proveedor'         => $row1['prov_razonsocial'],
                                                ];
                                                $total_notas_id[] = $row1['prov_id'];
                                            } else {
                                                $totales_notas[$row1['prov_id']]['costo']       +=  $row['nart_procosto'] * $row['nart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['cantidad']          += $row['nart_procantidad'];
                                                $totales_notas[$row1['prov_id']]['ganancia']          += $ganancia;
                                                $totales_notas[$row1['prov_id']]['venta']          +=  $row['nart_prototal'];
                                            }

                                            $artic_total += $ganancia;
                                            $costo_total +=  $row['nart_procosto'] * $row['nart_procantidad'];
                                            $venta_total += $row['nart_prototal'];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Http::json_response([
                        'proveedores'     => $totales_notas,
                        'ganancia' => $artic_total,
                        'costo' => $costo_total,
                        'venta' => $venta_total,
                        'div_locale'        => $this->divisa_master['div_locale'],
                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                        'div_nombre'        => $this->divisa_master['div_nombre'],
                    ]);
                }
            }
        }
    }

    public function obtenerProdProveedores()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

            Http::json_response($this->facturacionModel->obtenerProdProveedores($id));
        }
    }

    public function productosProvReportes()
    {

        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $sucursal = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);
            $proveedor = filter_input(INPUT_GET, 'proveedor', FILTER_SANITIZE_NUMBER_INT);

            if (!validateDate($fecha_desde, 'Y-m-d'))
                $this->array_errors[] = 'La Fecha desde es incorrecta.';
            if (!validateDate($fecha_hasta, 'Y-m-d'))
                $this->array_errors[] = 'La Fecha hasta es incorrecta.';

            $totales_notas  = [];
            $total_notas_id = [];
            $ganancia = 0;

            $notas =  $this->facturacionModel->obtenerProveedoresNEVpr($sucursal, $fecha_desde, $fecha_hasta);
            $factura =  $this->facturacionModel->obtenerProveedoresFactpr($sucursal, $fecha_desde, $fecha_hasta);

            if (is_countable($notas) && count($notas)) {

                foreach ($notas as $row) {

                    if ($row['ne_divid'] != $this->divisa_master['div_id']) {
                        $factor = $this->facturacionModel->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                        $row['neart_procosto'] = round(($row['neart_procosto'] * $factor['df_factor']), 2);
                        $row['neart_prototal'] = round(($row['neart_prototal'] * $factor['df_factor']), 2);
                    }

                    if ($row['pro_tipo'] == 2) {
                        $newpro = new ProductosCompuestos();
                        $prod_compuesto = $newpro->obtenerProductosCompuesto($row['pro_id']);

                        foreach ($prod_compuesto as $row2) {
                            $proveed = $this->facturacionModel->obtenerproveedorProductos($row2['pro_id'], $proveedor);

                            if ($proveed) {

                                if ($row2['pro_ccprecio'] > 1) {
                                    $ganancia = (($row2['pro_ccprecio'] * $row2['pro_cccant']) - ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad']);
                                    $ga = ($ganancia * 100);
                                    $ganc = ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                    if ($ga > 0 && $ganc > 0) {
                                        $ganancia_porct =  $ga / $ganc;
                                    } else {
                                        $ganancia_porct = 0;
                                    }
                                }
                                if (!in_array($row2['pro_id'], $total_notas_id)) {
                                    $totales_notas[$row2['pro_id']] = [
                                        'div_locale'        => $this->divisa_master['div_locale'],
                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                        'productos'         => $row2['pro_descripcion'],
                                        'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                        'cantidad'          => $row['neart_procantidad'],
                                        'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'],
                                        'ganancia'          => $ganancia,
                                    ];
                                    $total_notas_id[] = $row2['pro_id'];
                                } else {
                                    $totales_notas[$row2['pro_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                    $totales_notas[$row2['pro_id']]['cantidad']          += $row['neart_procantidad'];
                                    $totales_notas[$row2['pro_id']]['ganancia']          += $ganancia;
                                    $totales_notas[$row2['pro_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                }
                            }
                        }
                    } else {

                        $proveed = $this->facturacionModel->obtenerproveedorProductos($row['pro_id'], $proveedor);

                        if ($proveed) {
                            if ($row['neart_prototal'] > 1) {
                                $ganancia = $row['neart_prototal'] - ($row['neart_procosto'] * $row['neart_procantidad']);
                            }
                            if (!in_array($row['pro_id'], $total_notas_id)) {
                                $totales_notas[$row['pro_id']] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'productos'         => $row['pro_descripcion'],
                                    'costo'             => $row['neart_procosto'] * $row['neart_procantidad'],
                                    'cantidad'          => $row['neart_procantidad'],
                                    'venta'             => $row['neart_prototal'],
                                    'ganancia'          => $ganancia
                                ];
                                $total_notas_id[] = $row['pro_id'];
                            } else {
                                $totales_notas[$row['pro_id']]['costo']       +=  $row['neart_procosto'] * $row['neart_procantidad'];
                                $totales_notas[$row['pro_id']]['cantidad']          += $row['neart_procantidad'];
                                $totales_notas[$row['pro_id']]['ganancia']          += $ganancia;
                                $totales_notas[$row['pro_id']]['venta']          +=  $row['neart_prototal'];
                            }
                        }
                    }
                }
            }

            if (is_countable($factura) && count($factura)) {

                foreach ($factura as $row) {

                    if ($row['fm_divid'] != $this->divisa_master['div_id']) {
                        $factor = $this->facturacionModel->divisaFactor($row['fm_divid'], $this->divisa_master['div_id']);
                        $row['fa_procosto'] = round(($row['fa_procosto'] * $factor['df_factor']), 2);
                        $row['fa_prototal'] = round(($row['fa_prototal'] * $factor['df_factor']), 2);
                    }

                    $proveed = $this->facturacionModel->obtenerProveedores($row['pro_id']);

                    if ($row['pro_tipo'] == 2) {
                        $newpro = new ProductosCompuestos();
                        $prod_compuesto = $newpro->obtenerProductosCompuesto($row['pro_id']);

                        foreach ($prod_compuesto as $row2) {
                            $proveed = $this->facturacionModel->obtenerproveedorProductos($row2['pro_id'], $proveedor);

                            if ($proveed) {

                                if ($row2['pro_ccprecio'] > 1) {
                                    $ganancia = (($row2['pro_ccprecio'] * $row2['pro_cccant']) - ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad']);
                                    $ga = ($ganancia * 100);
                                    $ganc = ($row2['pro_costo'] * $row2['pro_cccant']) * $row['neart_procantidad'];
                                    if ($ga > 0 && $ganc > 0) {
                                        $ganancia_porct =  $ga / $ganc;
                                    } else {
                                        $ganancia_porct = 0;
                                    }
                                }

                                if (!in_array($row2['pro_id'], $total_notas_id)) {
                                    $totales_notas[$row2['pro_id']] = [
                                        'div_locale'        => $this->divisa_master['div_locale'],
                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                        'productos'         => $row2['pro_descripcion'],
                                        'costo'             => ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                        'cantidad'          => $row['fa_procantidad'],
                                        'venta'             => ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'],
                                        'ganancia'          => $ganancia,
                                    ];
                                    $total_notas_id[] = $row2['pro_id'];
                                } else {
                                    $totales_notas[$row2['pro_id']]['costo']       += ($row2['pro_costo'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                    $totales_notas[$row2['pro_id']]['cantidad']          += $row['fa_procantidad'];
                                    $totales_notas[$row2['pro_id']]['ganancia']          += $ganancia;
                                    $totales_notas[$row2['pro_id']]['venta']          += ($row2['pro_ccprecio'] * $row2['pro_cccant']) * $row['fa_procantidad'];
                                }
                            }
                        }
                    } else {
                        $proveed = $this->facturacionModel->obtenerproveedorProductos($row2['pro_id'], $proveedor);


                        if ($row['fa_prototal'] > 1) {
                            $ganancia = $row['fa_prototal'] - ($row['fa_procosto'] * $row['fa_procantidad']);
                        }
                        if ($proveed) {
                            if (!in_array($row['pro_id'], $total_notas_id)) {
                                $totales_notas[$row['pro_id']] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'productos'         => $row['pro_descripcion'],
                                    'costo'             => $row['fa_procosto'] * $row['fa_procantidad'],
                                    'cantidad'          => $row['fa_procantidad'],
                                    'venta'             => $row['fa_prototal'],
                                    'ganancia'          => $ganancia
                                ];
                                $total_notas_id[] = $row['pro_id'];
                            } else {
                                $totales_notas[$row['pro_id']]['costo']       +=  $row['fa_procosto'] * $row['fa_procantidad'];
                                $totales_notas[$row['pro_id']]['cantidad']          += $row['fa_procantidad'];
                                $totales_notas[$row['pro_id']]['ganancia']          += $ganancia;
                                $totales_notas[$row['pro_id']]['venta']          +=  $row['fa_prototal'];
                            }
                        }
                    }
                }
            }

            Http::json_response($totales_notas);
        }
    }

    public function proveedoresActivos()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {
            Http::json_response($this->facturacionModel->proveedoresActivos());
        }
    }

    public function obtenerCierreDelDia()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $sucursal = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);

            //if (empty($_GET['sucursal'])) {
            //    $this->array_errors[]  = 'EL campo sucursal es obligatorio.';
            // }
            if (empty($_GET['fecha'])) {
                $this->array_errors[]  = 'EL campo fecha es obligatorio.';
            } else {
                if (!validateDate($_GET['fecha'], 'Y-m-d')) {
                    $this->array_errors[] = 'EL campo no es valido.';
                }
            }

            $newCierre = new Ingresosegresos();

            if (empty($this->array_errors)) {

                $list_cierre_de_dia_p = [];
                $list_cierre_de_dia_n = [];
                $total_id_p = [];
                $totales_divisas_p = [];
                $total_id_n = [];
                $totales_divisas_n = [];

                $data_positivo = $newCierre->obtenerCierreDelDia(0, $_GET['fecha'], $sucursal);
                $data_negativo = $newCierre->obtenerCierreDelDia(1, $_GET['fecha'], $sucursal);

                if (is_countable($data_positivo) && count($data_positivo)) {
                    foreach ($data_positivo as $row) {
                        $list_cierre_de_dia_p[] = [
                            'empleado' => [
                                'nombres' => $row['einfo_nombres'],
                                'apellidos' => $row['einfo_apellidos']
                            ],
                            'metodo' => $row['fab_metodo'],
                            'divisa' => $row['div_nombre'],
                            'monto' => Moneda::moneda($row['monto'], $row['div_locale'], $row['div_simbolo']),
                            'banco' => [
                                'codigo' => $row['ban_codigo'],
                                'descripcion' => $row['ban_descripcion'],
                                'cuenta' => $row['bc_cuenta'],
                                'alias' => $row['bc_alias'],
                                'tipo' => $row['bc_tipo'],
                                'metodo' => $row['mp_nombre']
                            ]
                        ];

                        if (!in_array($row['div_id'], $total_id_p)) {
                            $totales_divisas_p[$row['div_id']] = [
                                'divisa' => Moneda::obtenerDivisa($row['div_id']),
                                'total' => $row['monto'],
                            ];
                            $total_id_p[] = $row['div_id'];
                        } else {
                            $totales_divisas_p[$row['div_id']]['total'] += $row['monto'];
                        }
                    }
                }

                if (is_countable($data_negativo) && count($data_negativo)) {
                    foreach ($data_negativo as $row) {
                        $list_cierre_de_dia_n[] = [
                            'empleado' => [
                                'nombres' => $row['einfo_nombres'],
                                'apellidos' => $row['einfo_apellidos']
                            ],
                            'metodo' => $row['fab_metodo'],
                            'divisa' => $row['div_nombre'],
                            'monto' => Moneda::moneda($row['monto'], $row['div_locale'], $row['div_simbolo']),
                            'banco' => [
                                'codigo' => $row['ban_codigo'],
                                'descripcion' => $row['ban_descripcion'],
                                'cuenta' => $row['bc_cuenta'],
                                'alias' => $row['bc_alias'],
                                'tipo' => $row['bc_tipo'],
                                'metodo' => $row['mp_nombre']
                            ]
                        ];

                        if (!in_array($row['div_id'], $total_id_n)) {
                            $totales_divisas_n[$row['div_id']] = [
                                'divisa' => Moneda::obtenerDivisa($row['div_id']),
                                'total' => $row['monto'],
                            ];
                            $total_id_n[] = $row['div_id'];
                        } else {
                            $totales_divisas_n[$row['div_id']]['total'] += $row['monto'];
                        }
                    }
                }

                Http::json_response([
                    'cierre_positivo' => $list_cierre_de_dia_p,
                    'cierre_negativo' =>  $list_cierre_de_dia_n,
                    'total_divisas_p' => $totales_divisas_p,
                    'total_divisas_n' => $totales_divisas_n,
                ]);
            }

            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    public function imprimirCierre()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if (!empty($_GET['fecha']) && !empty($_GET['id'])) {

                $fecha     = $this->solicitud->sanitize($_GET['fecha'], FILTER_SANITIZE_STRING);
                $estatus   = $this->solicitud->sanitize($_GET['estatus'], FILTER_SANITIZE_STRING);
                $id   = $this->solicitud->sanitize($_GET['id'], FILTER_VALIDATE_INT);
                $sucursal = $this->solicitud->sanitize($_GET['sucursal'], FILTER_SANITIZE_NUMBER_INT);

                $ingresosegresos_model = new Ingresosegresos();
                $data = [];
                $list_cierre = [];

                if ($id && $estatus) {
                    if ($estatus == 'positivo') {
                        $data = $ingresosegresos_model->obtenerCierreDelDia(0, $fecha, $sucursal);

                        if (is_countable($data) && count($data)) {
                            foreach ($data as $row) {
                                $list_cierre[] = [
                                    'empleado' => [
                                        'nombres' => $row['einfo_nombres'],
                                        'apellidos' => $row['einfo_apellidos']
                                    ],
                                    'metodo' => $row['fab_metodo'],
                                    'divisa' => $row['div_nombre'],
                                    'monto' => Moneda::moneda($row['monto'], $row['div_locale'], $row['div_simbolo']),
                                    'banco' => [
                                        'codigo' => $row['ban_codigo'],
                                        'descripcion' => $row['ban_descripcion'],
                                        'cuenta' => $row['bc_cuenta'],
                                        'alias' => $row['bc_alias'],
                                        'tipo' => $row['bc_tipo'],
                                        'metodo' => $row['mp_nombre']
                                    ]
                                ];
                            }
                        }
                    }
                    if ($estatus == 'negativo') {
                        $data = $ingresosegresos_model->obtenerCierreDelDia(1, $fecha, $sucursal);

                        if (is_countable($data) && count($data)) {
                            foreach ($data as $row) {
                                $list_cierre[] = [
                                    'empleado' => [
                                        'nombres' => $row['einfo_nombres'],
                                        'apellidos' => $row['einfo_apellidos']
                                    ],
                                    'metodo' => $row['fab_metodo'],
                                    'divisa' => $row['div_nombre'],
                                    'monto' => Moneda::moneda($row['monto'], $row['div_locale'], $row['div_simbolo']),
                                    'banco' => [
                                        'codigo' => $row['ban_codigo'],
                                        'descripcion' => $row['ban_descripcion'],
                                        'cuenta' => $row['bc_cuenta'],
                                        'alias' => $row['bc_alias'],
                                        'tipo' => $row['bc_tipo'],
                                        'metodo' => $row['mp_nombre']
                                    ]
                                ];
                            }
                        }
                    }
                    if ($estatus == 'completo') {

                        $abonos = [];
                        $pagos = [];
                        $dataNto = $ingresosegresos_model->obtenerCierreMovimientocompletoNot($fecha, $sucursal);
                        $dataFact = $ingresosegresos_model->obtenerCierreMovimientocompletoFact($fecha, $sucursal);
                        $dataOrd = $ingresosegresos_model->obtenerCierreMovimientocompletoOrd($fecha, $sucursal);
                        $positivo = 0;
                        $negativo=0;

                        $data_negativo = $ingresosegresos_model->obtenerCierreDelDiaNega(1, $fecha, $sucursal);

                        if (is_countable($data_negativo) && count($data_negativo)) {
                            foreach ($data_negativo as $row) {
                                $monto = ($this->divisa_master['div_id'] != $row['fab_divisa']) ? $row['fab_monto'] / $row['fab_factor_master'] : $row['fab_monto'];
                                $negativo+= $monto*(-1);
                            }
                        }

                        $generico = new Generico();

                        if (is_countable($dataNto) && count($dataNto)) {
                            foreach ($dataNto as $row) {

                                $total_pagos = $generico->totalPagos($row['ne_id'], 1, 1);

                                if ($row['fab_divisa'] != $this->divisa_master['div_id']) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['fab_monto'] *= $factor['df_factor'];
                                }

                                $positivo += $row['fab_monto'];

                                if ((round($total_pagos['total'] ?? 0, 2) >= round($row['ne_total'], 2)) && $total_pagos['total'] == 1) {
                                    $pagos[] = [
                                        'pago' => $row['fab_observacion'],
                                    ];
                                } else {
                                    if ((round($total_pagos['total'] ?? 0, 2) >= round($row['ne_total'], 2))) {
                                         $observacion = str_replace('Pago', 'Abono/ pago completo ', $row['fab_observacion']);
                                        $pagos[] = [
                                        'pago' => $observacion];
                                    } else {
                                        $observacion = str_replace('Pago', 'Abono', $row['fab_observacion']);
                                        $abonos[] = [
                                            'pago' => $observacion,
                                        ];
                                    }
                                }
                            }
                        }

                        if (is_countable($dataFact) && count($dataFact)) {
                            foreach ($dataFact as $row) {

                                $total_pagos = $generico->totalPagos($row['fm_id'], 2, 1);

                                if ($row['fab_divisa'] != $this->divisa_master['div_id']) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['fab_monto'] *= $factor['df_factor'];
                                }

                                $positivo += $row['fab_monto'];

                                if ((round($total_pagos['total'] ?? 0, 2) >= round($row['fm_total'], 2)) && $total_pagos['total'] == 1) {
                                    $pagos[] = [
                                        'pago' => $row['fab_observacion'],
                                    ];
                                } else {
                                    if ((round($total_pagos['total'] ?? 0, 2) >= round($row['fm_total'], 2))) {
                                        $observacion = str_replace('Pago', 'Abono/ pago completo ', $row['fab_observacion']);
                                        $pagos[] = [
                                        'pago' => $observacion,
                                    ];
                                    } else {
                                        $observacion = str_replace('Pago', 'Abono', $row['fab_observacion']);
                                        $abonos[] = [
                                            'pago' => $observacion,
                                        ];
                                    }
                                }
                            }
                        }

                        if (is_countable($dataOrd) && count($dataOrd)) {
                            foreach ($dataOrd as $row) {

                                $total_pagos = $generico->totalPagos($row['n_id'], 12, 1);
                                $planilla = $generico->obtenerPlanillas($row['n_id']);

                                if ($row['fab_divisa'] != $this->divisa_master['div_id']) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['fab_monto'] *= $factor['df_factor'];
                                }

                                $positivo += $row['fab_monto'];

                                if ((round($total_pagos['total'] ?? 0, 2) >= round($row['n_total'], 2)) && $total_pagos['total'] == 1) {
                                    $observacion = str_replace('Pago', 'Pago ' . $planilla['pre_correlativo'] ?? '', $row['fab_observacion']);
                                    $pagos[] = [
                                        'pago' => $observacion,
                                    ];
                                } else {
                                    if ((round($total_pagos['total'] ?? 0, 2) >= round($row['n_total'], 2))) {
                                        $observacion = str_replace('Pago', 'Abono/ pago completo ' . $planilla['pre_correlativo'] ?? '', $row['fab_observacion']);
                                        $abonos[] = [
                                            'pago' => $observacion,
                                        ];
                                    } else {
                                        $observacion = str_replace('Pago', 'Abono ' . $planilla['pre_correlativo'] ?? '', $row['fab_observacion']);
                                        $abonos[] = [
                                            'pago' => $observacion,
                                        ];
                                    }
                                }
                            }
                        }

                        

                        $credito = $ingresosegresos_model->consultar("SELECT n_total as total, n_divid as divisa FROM app_orden_de_entrega WHERE n_estatus=4 AND (DATE(n_fecha) BETWEEN '$fecha' AND '$fecha')")->all();
                        $credito_total = 0;
                        if (is_countable($credito) && count($credito)) {
                            foreach ($credito as $row) {
                                if ($row['divisa'] != $this->divisa_master['div_id']) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['total'] *= $factor['df_factor'];
                                }
                                $credito_total += $row['total'];
                            }
                        }

                        $list_cierre[] = [
                            'ingreso' => Moneda::moneda($positivo-$negativo, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                            'abonos' => $abonos,
                            'pagos' => $pagos,
                            'credito' => Moneda::moneda($credito_total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        ];
                    }
                    $carritoVentas = new CarritoVentasEditar();
                    Http::json_response($carritoVentas->imprimirIngreso($estatus, $list_cierre, $id));
                } else {
                    $this->array_errors[] = 'Acción prohibida';
                }
            } else {
                $this->array_errors[] = 'Acción prohibida';
            }

            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    //OBTIENE LOS PRODUCTOS DE DOCUEMENTOS GENERADOS VENIDOS
    public function obtenerProductosVendidos()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde    = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta    = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $id_divisa      = filter_input(INPUT_GET, 'divisa');
            $sucursal      = filter_input(INPUT_GET, 'sucursal');

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($fecha_desde))
                $fecha_desde = (new DateTime(null, $this->timeZone))->modify('first day of this month')->format('Y-m-d');

            if (empty($fecha_hasta))
                $fecha_hasta = date('Y-m-d');

            if (empty($this->array_errors)) {

                if (!validateDate($fecha_desde, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha desde es incorrecta.';
                if (!validateDate($fecha_hasta, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha hasta es incorrecta.';

                if (empty($this->array_errors)) {

                    if (!empty($id_divisa)) {
                        $divisa = $this->facturacionModel->obtenerDivisa($id_divisa);
                        $this->divisa_master['div_locale'] = $divisa['div_locale'];
                        $this->divisa_master['div_simbolo'] = $divisa['div_simbolo'];
                        $this->divisa_master['div_nombre'] = $divisa['div_nombre'];
                    }

                    $artic_total        = 0;
                    $costo_total        = 0;
                    $venta_total        = 0;
                    $totales_productos  = [];
                    $total_productos_id = [];

                    $productos =  $ingresosegresos_model->obtenerProductos();

                    if (is_countable($productos) && count($productos)) {

                        foreach ($productos as $pro) {

                            if (empty($id_divisa)) {
                                $total_notas = $ingresosegresos_model->obtenerArticulosDeNEV($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta);
                                $total_ordenes = $ingresosegresos_model->obtenerArticulosDeOrd($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta);
                                $total_facv = $ingresosegresos_model->obtenerArticulosDeFACV($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta);
                            } else {
                                $total_notas = $ingresosegresos_model->obtenerArticulosDeNEV($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa);
                                $total_ordenes = $ingresosegresos_model->obtenerArticulosDeOrd($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa);
                                $total_facv = $ingresosegresos_model->obtenerArticulosDeFACV($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa);
                            }

                            if (is_countable($total_notas) && count($total_notas)) {
                                foreach ($total_notas as $row) {

                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa)) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            //$row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /* $this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {

                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }

                                    if (!in_array($pro['pro_id'], $total_productos_id)) {
                                        $totales_productos[$pro['pro_id']] = [
                                            'div_locale'        => $this->divisa_master['div_locale'],
                                            'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                            'div_nombre'        => $this->divisa_master['div_nombre'],
                                            'pro_id'            => $pro['pro_id'],
                                            'pro_descripcion'   => $pro['pro_descripcion'],
                                            'pro_costo'         =>  $row['costo'],
                                            'cantidad'          => $row['cantidad'],
                                            'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                            'total'             => $row['total'],
                                            'ganancia'          => $ganancia,
                                            'ganancia_porct'    => $ganancia_porct,
                                            'sucursal'          => $row['su_nombre'],
                                            'uri'               => 'notasdeentregaeditar/verFactura/' . $row['id'],
                                            'documento'         => 'NEV' . $row['correlativo'],
                                            'fecha'             => $row['fecha'],
                                            'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        ];
                                        $total_productos_id[] = $pro['pro_id'];
                                    } else {
                                        $totales_productos[$pro['pro_id']]['costo_total']       +=  $row['costo'] * $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['cantidad']          += $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['total']             += $row['total'];
                                        $totales_productos[$pro['pro_id']]['ganancia']          += $ganancia;
                                        $totales_productos[$pro['pro_id']]['ganancia_porct']    += $ganancia_porct;
                                    }

                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo']*$row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }

                            if (is_countable($total_facv) && count($total_facv)) {

                                foreach ($total_facv as $row) {

                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa)) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            //$row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /* $this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {
                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }

                                    if (!in_array($pro['pro_id'], $total_productos_id)) {
                                        $totales_productos[$pro['pro_id']] = [
                                            'div_locale'        => $this->divisa_master['div_locale'],
                                            'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                            'div_nombre'        => $this->divisa_master['div_nombre'],
                                            'pro_id'            => $pro['pro_id'],
                                            'pro_descripcion'   => $pro['pro_descripcion'],
                                            'pro_costo'         =>  $row['costo'],
                                            'cantidad'          => $row['cantidad'],
                                            'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                            'total'             => $row['total'],
                                            'ganancia'          => $ganancia,
                                            'ganancia_porct'    => $ganancia_porct,
                                            'sucursal'          => $row['su_nombre'],
                                            'uri'               => 'poseditar/verFactura/' . $row['id'],
                                            'documento'         => 'FACV' . $row['correlativo'],
                                            'fecha'             => $row['fecha'],
                                            'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        ];
                                        $total_productos_id[] = $pro['pro_id'];
                                    } else {
                                        $totales_productos[$pro['pro_id']]['costo_total']       +=  $row['costo'] * $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['cantidad']          += $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['total']             += $row['total'];
                                        $totales_productos[$pro['pro_id']]['ganancia']          += $ganancia;
                                        $totales_productos[$pro['pro_id']]['ganancia_porct']    += $ganancia_porct;
                                    }

                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo'] * $row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }

                            if (is_countable($total_ordenes) && count($total_ordenes)) {

                                foreach ($total_ordenes as $row) {

                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa)) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            // $row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /*$this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $id_divisa);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {
                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }

                                    if (!in_array($pro['pro_id'], $total_productos_id)) {
                                        $totales_productos[$pro['pro_id']] = [
                                            'div_locale'        => $this->divisa_master['div_locale'],
                                            'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                            'div_nombre'        => $this->divisa_master['div_nombre'],
                                            'pro_id'            => $pro['pro_id'],
                                            'pro_descripcion'   => $pro['pro_descripcion'],
                                            'pro_costo'         =>  $row['costo'],
                                            'cantidad'          => $row['cantidad'],
                                            'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                            'total'             => $row['total'],
                                            'ganancia'          => $ganancia,
                                            'ganancia_porct'    => $ganancia_porct,
                                            'sucursal'          => $row['su_nombre'],
                                            'uri'               => 'ordendeentregaeditar/verFactura/' . $row['id'],
                                            'documento'         => 'ORDENV' . $row['correlativo'],
                                            'fecha'             => $row['fecha'],
                                            'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        ];
                                        $total_productos_id[] = $pro['pro_id'];
                                    } else {
                                        $totales_productos[$pro['pro_id']]['costo_total']       +=  $row['costo'] * $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['cantidad']          += $row['cantidad'];
                                        $totales_productos[$pro['pro_id']]['total']             += $row['total'];
                                        $totales_productos[$pro['pro_id']]['ganancia']          += $ganancia;
                                        $totales_productos[$pro['pro_id']]['ganancia_porct']    += $ganancia_porct;
                                    }

                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo'] * $row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }
                        }
                    }

                    $ganancia = 0;
                    $ganancia_porct = 0;

                    if ($venta_total > 0 && $costo_total > 0) {
                        $ganancia = $venta_total - $costo_total;
                        $ganancia_porct   = ($costo_total * 100) / $venta_total;
                    }

                    Http::json_response([
                        'venta_total'   => Moneda::moneda($venta_total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'costo_total'   => Moneda::moneda($costo_total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'artic_total'   => $artic_total,
                        'ganancia'      => Moneda::moneda($ganancia, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'ganancia_porc' => round($ganancia_porct),
                        'productos'     => $totales_productos,
                        'cantidad_articulos' =>  count($totales_productos)
                    ]);
                }
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function obtenerProductosVendidosdocumentos()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde    = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta    = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $id_divisa      = filter_input(INPUT_GET, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $sucursal      = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);
            $estatus      = filter_input(INPUT_GET, 'estatus', FILTER_SANITIZE_NUMBER_INT);
            $agente_emplead      = filter_input(INPUT_GET, 'agente', FILTER_SANITIZE_NUMBER_INT);

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($fecha_desde))
                $fecha_desde = (new DateTime(null, $this->timeZone))->modify('first day of this month')->format('Y-m-d');

            if (empty($fecha_hasta))
                $fecha_hasta = date('Y-m-d');

            // if (empty($sucursal))
            //  $this->array_errors[] = 'Seleccione una sucursal.';

            if (empty($this->array_errors)) {

                if (!validateDate($fecha_desde, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha desde es incorrecta.';
                if (!validateDate($fecha_hasta, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha hasta es incorrecta.';

                if (empty($this->array_errors)) {

                    if (!empty($id_divisa)) {
                        $divisa = $ingresosegresos_model->obtenerDivisa($id_divisa);
                        $this->divisa_master['div_locale'] = $divisa['div_locale'];
                        $this->divisa_master['div_simbolo'] = $divisa['div_simbolo'];
                        $this->divisa_master['div_nombre'] = $divisa['div_nombre'];
                    }

                    $artic_total        = 0;
                    $costo_total        = 0;
                    $venta_total        = 0;
                    $totales_productos  = [];

                    $productos =  $ingresosegresos_model->obtenerProductos();
                    $obtener_agente = new EmpleadoInfo();


                    if (is_countable($productos) && count($productos)) {

                        foreach ($productos as $pro) {

                            if (empty($id_divisa)) {
                                $total_notas = $ingresosegresos_model->obtenerArticulosDeNEVL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, null, $estatus, $agente_emplead);
                                $total_ordenes = $ingresosegresos_model->obtenerArticulosDeOrdL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, null, $estatus, $agente_emplead);
                                $total_facv = $ingresosegresos_model->obtenerArticulosDeFACVL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, null, $estatus, $agente_emplead);
                            } else {

                                $total_notas = $ingresosegresos_model->obtenerArticulosDeNEVL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa, $estatus, $agente_emplead);
                                $total_ordenes = $ingresosegresos_model->obtenerArticulosDeOrdL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa, $estatus, $agente_emplead);
                                $total_facv = $ingresosegresos_model->obtenerArticulosDeFACVL($pro['pro_id'], $sucursal, $fecha_desde, $fecha_hasta, $id_divisa, $estatus, $agente_emplead);
                            }

                            if (is_countable($total_notas) && count($total_notas)) {

                                foreach ($total_notas as $row) {

                                    if ($row['agente'] != NULL) {
                                        $agente = $obtener_agente->empleadoInfo($row['agente']);
                                    }

                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa) && $id_divisa > 0) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            //$row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /* $this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {

                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }

                                    $totales_productos[] = [
                                        'div_locale'        => $this->divisa_master['div_locale'],
                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                        'pro_id'            => $pro['pro_id'],
                                        'pro_descripcion'   => $pro['pro_descripcion'],
                                        'pro_costo'         =>  $row['costo'],
                                        'cantidad'          => $row['cantidad'],
                                        'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                        'total'             => $row['total'],
                                        'estatus'           => ($row['estatus'] == 1) ? 'Pagado' : 'Pendiente',
                                        'ganancia'          => $ganancia,
                                        'ganancia_porct'    => $ganancia_porct,
                                        'sucursal'          => $row['su_nombre'],
                                        'uri'               => 'notasdeentregaeditar/verFactura/' . $row['id'],
                                        'documento'         => 'NEV' . $row['correlativo'],
                                        'fecha'             => $row['fecha'],
                                        'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        'agente'            => ($row['agente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['agente'],
                                        'cliente'           => $row['cli_razon_social'],
                                        'cliente_id'        => $row['cli_id'],
                                        'grupo'             => $row['grup_nombre'],
                                        'grupo_id'           => $row['grup_codigo']
                                    ];


                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo'] * $row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }

                            if (is_countable($total_facv) && count($total_facv)) {

                                foreach ($total_facv as $row) {

                                    if ($row['agente'] != NULL) {
                                        $agente = $obtener_agente->empleadoInfo($row['agente']);
                                    }
                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa) && $id_divisa > 0) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            //$row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /* $this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {
                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }
                                    $totales_productos[] = [
                                        'div_locale'        => $this->divisa_master['div_locale'],
                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                        'pro_id'            => $pro['pro_id'],
                                        'pro_descripcion'   => $pro['pro_descripcion'],
                                        'pro_costo'         =>  $row['costo'],
                                        'cantidad'          => $row['cantidad'],
                                        'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                        'total'             => $row['total'],
                                        'estatus'           => ($row['estatus'] == 1) ? 'Pagado' : 'Pendiente',
                                        'ganancia'          => $ganancia,
                                        'ganancia_porct'    => $ganancia_porct,
                                        'sucursal'          => $row['su_nombre'],
                                        'uri'               => 'poseditar/verFactura/' . $row['id'],
                                        'documento'         => 'FACV' . $row['correlativo'],
                                        'fecha'             => $row['fecha'],
                                        'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        'agente'            => ($row['agente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['agente'],
                                        'cliente'           => $row['cli_razon_social'],
                                        'cliente_id'        => $row['cli_id'],
                                        'grupo'             => $row['grup_nombre'],
                                        'grupo_id'           => $row['grup_codigo']
                                    ];

                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo'] * $row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }

                            if (is_countable($total_ordenes) && count($total_ordenes)) {

                                foreach ($total_ordenes as $row) {

                                    if ($row['agente'] != NULL) {
                                        $agente = $obtener_agente->empleadoInfo($row['agente']);
                                    }

                                    $ganancia = 0;
                                    $ganancia_porct = 0;

                                    if (!empty($id_divisa) && $id_divisa > 0) {

                                        if ($this->divisa_master['div_id'] != $id_divisa) {
                                            $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                            //$row['costo'] = round(($row['costo'] * $div_factor['df_factor']), 2);
                                        }

                                        if ($row['divisa'] != $id_divisa /*$this->divisa_master['div_id']*/) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $id_divisa);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    } else {
                                        if ($row['divisa'] != $this->divisa_master['div_id']) {
                                            $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                            $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                            $row['costo'] = round(($row['costo'] * $factor['df_factor']), 2);
                                        }
                                    }

                                    if ($row['total'] > 1) {
                                        $ganancia = $row['total'] - ($row['costo'] * $row['cantidad']);
                                        $ga = ($ganancia * 100);
                                        $ganc = ($row['costo'] * $row['cantidad']);
                                        if ($ga > 0 && $ganc > 0) {
                                            $ganancia_porct =  $ga / $ganc;
                                        } else {
                                            $ganancia_porct = 0;
                                        }
                                    }
                                    $totales_productos[] = [
                                        'div_locale'        => $this->divisa_master['div_locale'],
                                        'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                        'div_nombre'        => $this->divisa_master['div_nombre'],
                                        'pro_id'            => $pro['pro_id'],
                                        'pro_descripcion'   => $pro['pro_descripcion'],
                                        'pro_costo'         =>  $row['costo'],
                                        'cantidad'          => $row['cantidad'],
                                        'costo_total'       =>  $row['costo'] * $row['cantidad'],
                                        'total'             => $row['total'],
                                        'estatus'           => ($row['estatus'] == 1) ? 'Pagado' : 'Pendiente',
                                        'ganancia'          => $ganancia,
                                        'ganancia_porct'    => $ganancia_porct,
                                        'sucursal'          => $row['su_nombre'],
                                        'uri'               => 'ordendeentregaeditar/verFactura/' . $row['id'],
                                        'documento'         => 'ORDENV' . $row['correlativo'],
                                        'fecha'             => $row['fecha'],
                                        'empleado'          => $row['nombre'] . ' ' . $row['apellido'],
                                        'agente'            => ($row['agente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['agente'],
                                        'cliente'           => $row['cli_razon_social'],
                                        'cliente_id'        => $row['cli_id'],
                                        'grupo'             => $row['grup_nombre'],
                                        'grupo_id'           => $row['grup_codigo']
                                    ];


                                    $artic_total += $row['cantidad'];
                                    $costo_total +=  $row['costo'] * $row['cantidad'];
                                    $venta_total += $row['total'];
                                }
                            }
                        }
                    }

                    $ganancia = 0;
                    $ganancia_porct = 0;

                    if ($venta_total > 0 && $costo_total > 0) {
                        $ganancia = $venta_total - $costo_total;
                        $ganancia_porct   = ($costo_total * 100) / $venta_total;
                    }

                    Http::json_response([
                        'venta_total'   => Moneda::moneda($venta_total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'costo_total'   => Moneda::moneda($costo_total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'artic_total'   => $artic_total,
                        'ganancia'      => Moneda::moneda($ganancia, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                        'ganancia_porc' => round($ganancia_porct),
                        'productos'     => $totales_productos,
                        'cantidad_articulos' =>  count($totales_productos)
                    ]);
                }
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function obtenerDocumentosVentaDia()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde    = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta    = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $id_divisa      = filter_input(INPUT_GET, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $select_doc     = filter_input(INPUT_GET, 'documento', FILTER_SANITIZE_NUMBER_INT);
            $sucursal       = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($fecha_desde))
                $fecha_desde = (new DateTime(null, $this->timeZone))->modify('first day of this month')->format('Y-m-d');

            if (empty($fecha_hasta))
                $fecha_hasta = date('Y-m-d');

            if (empty($this->array_errors)) {

                if (!validateDate($fecha_desde, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha desde es incorrecta.';
                if (!validateDate($fecha_hasta, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha hasta es incorrecta.';

                if (empty($this->array_errors)) {

                    if (!empty($id_divisa)) {
                        $divisa = $ingresosegresos_model->obtenerDivisa($id_divisa);
                        $this->divisa_master['div_locale'] = $divisa['div_locale'];
                        $this->divisa_master['div_simbolo'] = $divisa['div_simbolo'];
                    }

                    $array_documentos = [];
                    $art_total = 0;
                    $pendiente = 0;
                    $acumulado_t = 0;
                    $total = 0;
                    $i = 0;
                    $total_productos_id = [];
                    $cantidad_art = 0;

                    if ($select_doc == 2 || $select_doc == 0) {
                        $facturas = $ingresosegresos_model->obtenerFacturasVentasDelDia($id_divisa, $fecha_desde, $fecha_hasta, $sucursal);
                        if (is_countable($facturas) && count($facturas)) {
                            $documento = $ingresosegresos_model->obtenerDocumento(2);
                            foreach ($facturas as $row) {

                                $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 2);
                                $total_artic = $ingresosegresos_model->obtenerNotFacttotalArt($row['id'], 2);

                                foreach ($total_artic as $row2) {
                                    if (!in_array($row2['fa_proid'], $total_productos_id)) {
                                        $total_productos_id[] = $row2['fa_proid'];
                                        $art_total += 1;
                                    }
                                }

                                if ($row['div_id'] != $this->divisa_master['div_id'] && $id_divisa == 0) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                    $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                                }

                                $acumulado_total = ($acumulado['total']) ?? 0;
                                $array_documentos[] = [
                                    'id'            => $row['id'],
                                    'cliente'       => $row['cliente'],
                                    'uri'           => 'poseditar/verFactura/' . $row['id'],
                                    'documento'     => $documento['doc_prefijo'],
                                    'correlativo'   => $row['correlativo'],
                                    'div_locale'    => $row['div_locale'],
                                    'div_simbolo'   => $row['div_simbolo'],
                                    'total'         => $row['total'],
                                    'fecha'         => $row['fecha'],
                                    'acumulado'     => $acumulado_total,
                                    'pendiente'     => $row['total'] - $acumulado_total
                                ];
                                $acumulado_t += $array_documentos[$i]['acumulado'];
                                $pendiente += $array_documentos[$i]['pendiente'];
                                $total += $array_documentos[$i]['total'];
                                $cantidad_art += $row['art_total'];

                                $i++;
                            }
                        }
                    }

                    if ($select_doc == 1 || $select_doc == 0) {
                        $notas = $ingresosegresos_model->obtenerNotasVentasDelDia($id_divisa, $fecha_desde, $fecha_hasta, $sucursal);
                        if (is_countable($notas) && count($notas)) {
                            $documento = $ingresosegresos_model->obtenerDocumento(1);
                            foreach ($notas as $row) {

                                $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 1);
                                $total_artic = $ingresosegresos_model->obtenerNotFacttotalArt($row['id'], 1);


                                foreach ($total_artic as $row2) {
                                    if (!in_array($row2['neart_proid'], $total_productos_id)) {
                                        $total_productos_id[] = $row2['neart_proid'];
                                        $art_total += 1;
                                    }
                                }

                                if ($row['div_id'] != $this->divisa_master['div_id'] && $id_divisa == 0) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    // $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                    $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                                }

                                $acumulado_total = ($acumulado['total']) ?? 0;

                                $array_documentos[] = [
                                    'id'            => $row['id'],
                                    'cliente'       => $row['cliente'],
                                    'uri'           => 'notasdeentregaeditar/verFactura/' . $row['id'],
                                    'documento'     => $documento['doc_prefijo'],
                                    'correlativo'   => $row['correlativo'],
                                    'div_locale'    => $row['div_locale'],
                                    'div_simbolo'   => $row['div_simbolo'],
                                    'total'         => $row['total'],
                                    'fecha'         => $row['fecha'],
                                    'acumulado'     => $acumulado_total,
                                    'pendiente'     => $row['total'] - $acumulado_total
                                ];
                                $acumulado_t += $array_documentos[$i]['acumulado'];
                                $pendiente += $array_documentos[$i]['pendiente'];
                                $total += $array_documentos[$i]['total'];
                                $cantidad_art += $row['art_total'];

                                $i++;
                            }
                        }
                    }

                    if ($select_doc == 12 || $select_doc == 0) {
                        $ordenes = $ingresosegresos_model->obtenerOrdenesVentasDelDia($id_divisa, $fecha_desde, $fecha_hasta, $sucursal);
                        if (is_countable($ordenes) && count($ordenes)) {
                            $documento = $ingresosegresos_model->obtenerDocumento(2);
                            foreach ($ordenes as $row) {

                                $acumulado = $ingresosegresos_model->obtenerAcumulado($row['id'], 12);
                                $total_artic = $ingresosegresos_model->obtenerNotFacttotalArt($row['id'], 12);

                                foreach ($total_artic as $row2) {
                                    if (!in_array($row2['nart_proid'], $total_productos_id)) {
                                        $total_productos_id[] = $row2['nart_proid'];
                                        $art_total += 1;
                                    }
                                }

                                if ($row['div_id'] != $this->divisa_master['div_id'] && $id_divisa == 0) {
                                    $factor = $ingresosegresos_model->divisaFactor($row['div_id'], $this->divisa_master['div_id']);
                                    $row['total'] = $factor['df_factor'];
                                    $acumulado['total'] = round($acumulado['total'] * $factor['df_factor'], 2);
                                }

                                $acumulado_total = ($acumulado['total']) ?? 0;
                                $array_documentos[] = [
                                    'id'            => $row['id'],
                                    'cliente'       => $row['cliente'],
                                    'uri'           => 'ordendeentregaeditar/verFactura/' . $row['id'],
                                    'documento'     => $documento['doc_prefijo'],
                                    'correlativo'   => $row['correlativo'],
                                    'div_locale'    => $row['div_locale'],
                                    'div_simbolo'   => $row['div_simbolo'],
                                    'total'         => $row['total'],
                                    'fecha'         => $row['fecha'],
                                    'acumulado'     => $acumulado_total,
                                    'pendiente'     => $row['total'] - $acumulado_total
                                ];
                                $acumulado_t += $array_documentos[$i]['acumulado'];
                                $pendiente += $array_documentos[$i]['pendiente'];
                                $total += $array_documentos[$i]['total'];
                                $cantidad_art += $row['art_total'];

                                $i++;
                            }
                        }
                    }
                }

                Http::json_response([
                    'artic_total'   => $art_total,
                    'acumulado'     => Moneda::moneda($acumulado_t, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                    'pendiente'     => Moneda::moneda($pendiente, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                    'total'         => Moneda::moneda($total, $this->divisa_master['div_locale'], $this->divisa_master['div_simbolo']),
                    'documentos'    => $array_documentos,
                    'cantidad_art'  => $cantidad_art ?? 0
                ]);
            }

            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    public function produccionDia()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio   = filter_input(INPUT_GET, 'anio', FILTER_SANITIZE_NUMBER_INT);
            $mes    = filter_input(INPUT_GET, 'mes', FILTER_SANITIZE_NUMBER_INT);
            $div_id = filter_input(INPUT_GET, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $sucursal = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($anio))
                $anio = date('Y');

            if (empty($mes))
                $mes = date('m');

            if (empty($this->array_errors)) {

                $array_notas        = [];
                $array_notas_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;
                $ganancia           = 0;
                $porcentaje         = 0;

                $notas = $ingresosegresos_model->obtenerProduccionNEVDia($mes, $anio, $div_id, $sucursal);
                $ordenes = $ingresosegresos_model->obtenerProduccionORDENDia($mes, $anio, $div_id, $sucursal);
                $facturas = $ingresosegresos_model->obtenerProduccionFACVDia($mes, $anio, $div_id, $sucursal);

                if ($div_id > 0) {
                    $divisa = $ingresosegresos_model->obtenerDivisa($div_id);
                } else {
                    $divisa = $ingresosegresos_model->obtenerDivisa($this->divisa_master['div_id']);
                }

                if (is_countable($notas) && count($notas)) {

                    foreach ($notas as $row) {

                        if (!in_array($row['dia'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    // $row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['dia']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'dia'           => $row['dia'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['dia'];
                        } else {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //  $row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['dia']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['dia']]['costo']      += $row['total_costo'];
                            $array_notas[$row['dia']]['venta']      += $row['total_venta'];
                            $array_notas[$row['dia']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['dia']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($ordenes) && count($ordenes)) {

                    foreach ($ordenes as $row) {

                        if (!in_array($row['dia'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['dia']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'dia'           => $row['dia'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['dia'];
                        } else {

                            if ($row['total_venta'] > 0) {
                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['dia']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['dia']]['costo']      += $row['total_costo'];
                            $array_notas[$row['dia']]['venta']      += $row['total_venta'];
                            $array_notas[$row['dia']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['dia']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($facturas) && count($facturas)) {

                    foreach ($facturas as $row_dos) {

                        if (!in_array($row_dos['dia'], $array_notas_id)) {

                            if ($row_dos['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row_dos['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row_dos['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row_dos['fm_divid'], $this->divisa_master['div_id']);
                                    $row_dos['total_costo'] *= $div_factor['df_factor'];
                                    $row_dos['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row_dos['total_venta'] - $row_dos['total_costo']) * 100 / $row_dos['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row_dos['dia']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'dia'           => $row_dos['dia'],
                                'cantidad'      => $row_dos['cantidad'],
                                'costo'         => $row_dos['total_costo'],
                                'venta'         => $row_dos['total_venta'],
                                'ganancia'      => $row_dos['total_venta'] - $row_dos['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row_dos['su_nombre'],
                            ];
                            $array_notas_id[] = $row_dos['dia'];
                        } else {

                            if ($row_dos['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row_dos['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row_dos['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row_dos['fm_divid'], $this->divisa_master['div_id']);
                                    $row_dos['total_costo'] *= $div_factor['df_factor'];
                                    $row_dos['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row_dos['total_venta'] - $row_dos['total_costo']) * 100 / $row_dos['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row_dos['dia']]['cantidad']   += $row_dos['cantidad'];
                            $array_notas[$row_dos['dia']]['costo']      += $row_dos['total_costo'];
                            $array_notas[$row_dos['dia']]['venta']      += $row_dos['total_venta'];
                            $array_notas[$row_dos['dia']]['ganancia']   += $row_dos['total_venta'] - $row_dos['total_costo'];
                            $array_notas[$row_dos['dia']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row_dos['cantidad'];
                        $costo          += $row_dos['total_costo'];
                        $venta          += $row_dos['total_venta'];
                    }
                }

                if ($costo > 0 && $venta > 0) {
                    $ganancia = $venta - $costo;
                    $porcentaje = round(($ganancia * 100 / $venta), 2);
                }

                Http::json_response([
                    'costo'         => Moneda::moneda($costo, $divisa['div_locale'], $divisa['div_simbolo']),
                    'venta'         => Moneda::moneda($venta, $divisa['div_locale'], $divisa['div_simbolo']),
                    'ganancia'      => Moneda::moneda($ganancia, $divisa['div_locale'], $divisa['div_simbolo']),
                    'porcentaje'    => round($porcentaje),
                    'art_total'     => $artic_total,
                    'dias'          => $array_notas
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function produccionMes()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $anio   = filter_input(INPUT_POST, 'anio', FILTER_SANITIZE_NUMBER_INT);
            $div_id = filter_input(INPUT_POST, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $sucursal = filter_input(INPUT_POST, 'sucursal', FILTER_SANITIZE_NUMBER_INT);

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($anio))
                $anio = date('Y');

            if (empty($this->array_errors)) {

                $array_notas        = [];
                $array_notas_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;
                $ganancia           = 0;
                $porcentaje         = 0;

                $notas = $ingresosegresos_model->obtenerProduccionNEVMes($anio, $div_id, $sucursal);
                $ordenes = $ingresosegresos_model->obtenerProduccionORDENMes($anio, $div_id, $sucursal);
                $facturas = $ingresosegresos_model->obtenerProduccionFACVMes($anio, $div_id, $sucursal);

                if ($div_id > 0) {
                    $divisa = $ingresosegresos_model->obtenerDivisa($div_id);
                } else {
                    $divisa = $ingresosegresos_model->obtenerDivisa($this->divisa_master['div_id']);
                }

                if (is_countable($notas) && count($notas)) {

                    foreach ($notas as $row) {

                        if (!in_array($row['mes'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }


                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'mes'           => $row['mes'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['mes'];
                        } else {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['mes']]['costo']      += $row['total_costo'];
                            $array_notas[$row['mes']]['venta']      += $row['total_venta'];
                            $array_notas[$row['mes']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['mes']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($ordenes) && count($ordenes)) {

                    foreach ($ordenes as $row) {

                        if (!in_array($row['mes'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                     $row['total_costo'] *= $div_factor['df_factor'];
                                     $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'mes'           => $row['mes'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['mes'];
                        } else {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                     $row['total_costo'] *= $div_factor['df_factor'];
                                     $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['mes']]['costo']      += $row['total_costo'];
                            $array_notas[$row['mes']]['venta']      += $row['total_venta'];
                            $array_notas[$row['mes']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['mes']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($facturas) && count($facturas)) {

                    foreach ($facturas as $row) {

                        if (!in_array($row['mes'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                     $row['total_costo'] *= $div_factor['df_factor'];
                                     $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['fm_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'mes'           => $row['mes'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['mes'];
                        } else {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                     $row['total_costo'] *= $div_factor['df_factor'];
                                     $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['fm_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['mes']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['mes']]['costo']      += $row['total_costo'];
                            $array_notas[$row['mes']]['venta']      += $row['total_venta'];
                            $array_notas[$row['mes']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['mes']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if ($costo > 0 && $venta > 0) {
                    $ganancia = $venta - $costo;
                    $porcentaje = round((($ganancia) * 100 / $venta), 2);
                }

                Http::json_response([
                    'costo'         => Moneda::moneda($costo, $divisa['div_locale'], $divisa['div_simbolo']),
                    'venta'         => Moneda::moneda($venta, $divisa['div_locale'], $divisa['div_simbolo']),
                    'ganancia'      => Moneda::moneda($ganancia, $divisa['div_locale'], $divisa['div_simbolo']),
                    'porcentaje'    => round($porcentaje),
                    'art_total'     => $artic_total,
                    'meses'         => $array_notas,
                    'div_locale'    => $divisa['div_locale'],
                    'div_simbolo'  => $divisa['div_simbolo'],
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function obtenerClientesConDocumentosPendientesPorPagar()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $array_factura = [];
            $array_notas = [];
            $array_ordenes = [];
            $ventas_pendientes = 0;
            $totales_divisas = [];
            $facturas_divisas = [];
            $facturas_divisas_id = [];
            $notas_divisas = [];
            $notas_divisas_id = [];
            $ordenes_divisas = [];
            $ordenes_divisas_id = [];
            $totales_divisas = [];
            $total_divisa_id = [];

            $ingresosegresos_model = new Ingresosegresos();

            $facturas = $ingresosegresos_model->obtenerFacturasPendientes();
            $notas = $ingresosegresos_model->obtenerNotasdeentregaPendiente();
            $ordenes = $ingresosegresos_model->obtenerOrdendeentregaPendiente();

            $obtener_agente = new EmpleadoInfo();


            if (is_countable($facturas) && count($facturas)) {

                foreach ($facturas as $row) {

                    $acumulado = $ingresosegresos_model->obtenerAcumulado($row['fm_id'], 2);
                    $acumulado_total = ($acumulado['total']) ?? 0;

                    if ($row['fm_empagente'] != NULL) {
                        $agente = $obtener_agente->empleadoInfo($row['fm_empagente']);
                    }

                    $array_factura[] = [
                        'dni'           => $row['cli_dni'],
                        'nombrecompl'   => $row['cli_razon_social'],
                        'id_cliente'   => $row['cli_id'],
                        'id_grupo'   => $row['grup_id'],
                        'grupo'   => $row['grup_nombre'],
                        'id'            => $row['fm_id'],
                        'correlativo'   => $row['fm_correlativo'],
                        'divisa'        => $row['div_nombre'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         => $row['fm_total'],
                        'estatus'       => $row['fm_estatus'],
                        'fecha'         => $row['fecha'],
                        'acumulado'     => $acumulado_total,
                        'sucursal'      => $row['su_nombre'],
                        'tipo'          => 'FACV' . $row['fm_correlativo'],
                        'url'           => 'poseditar/verFactura/' . $row['fm_id'],
                        'agente'        => ($row['fm_empagente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['fm_empagente'],
                        'pendiente'     => $row['fm_total'] - $acumulado_total
                    ];

                    $ventas_pendientes += 1;

                    if (!in_array($row['div_id'], $facturas_divisas_id)) {
                        $facturas_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => round(($row['fm_total'] - $acumulado_total), 2),
                        ];
                        $facturas_divisas_id[] = $row['div_id'];
                    } else {
                        $facturas_divisas[$row['div_id']]['total'] += $row['fm_total'] - $acumulado_total;
                    }
                }
            }

            if (is_countable($notas) && count($notas)) {

                foreach ($notas as $row) {

                    $acumulado = $ingresosegresos_model->obtenerAcumulado($row['ne_id'], 1);
                    $acumulado_total = ($acumulado['total']) ?? 0;

                    if ($row['ne_empagente'] != NULL) {
                        $agente = $obtener_agente->empleadoInfo($row['ne_empagente']);
                    }

                    $array_notas[] = [
                        'dni'           => $row['cli_dni'],
                        'nombrecompl'   => $row['cli_razon_social'],
                        'id_cliente'   => $row['cli_id'],
                        'id_grupo'   => $row['grup_id'],
                        'grupo'   => $row['grup_nombre'],
                        'id'            => $row['ne_id'],
                        'correlativo'   => $row['ne_correlativo'],
                        'tipo'          => 'NEV' . $row['ne_correlativo'],
                        'divisa'        => $row['div_nombre'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         => $row['ne_total'],
                        'estatus'       => $row['ne_estatus'],
                        'fecha'         => $row['fecha'],
                        'acumulado'     => $acumulado_total,
                        'sucursal'      => $row['su_nombre'],
                        'agente'        => ($row['ne_empagente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['ne_empagente'],
                        'url'           => 'notasdeentregaeditar/verFactura/' . $row['ne_id'],
                        'pendiente'     => $row['ne_total'] - $acumulado_total
                    ];

                    $ventas_pendientes += 1;

                    if (!in_array($row['div_id'], $notas_divisas_id)) {
                        $notas_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => $row['ne_total'] - $acumulado_total
                        ];
                        $notas_divisas_id[] = $row['div_id'];
                    } else {
                        $notas_divisas[$row['div_id']]['total'] += $row['ne_total'] - $acumulado_total;
                    }
                }
            }

            if (is_countable($ordenes) && count($ordenes)) {

                foreach ($ordenes as $row) {

                    $acumulado = $ingresosegresos_model->obtenerAcumulado($row['n_id'], 12);
                    $acumulado_total = ($acumulado['total']) ?? 0;

                    if ($row['n_empagente'] != NULL) {
                        $agente = $obtener_agente->empleadoInfo($row['n_empagente']);
                    }

                    $array_ordenes[] = [
                        'dni'           => $row['cli_dni'],
                        'nombrecompl'   => $row['cli_razon_social'],
                        'id_cliente'   => $row['cli_id'],
                        'id_grupo'   => $row['grup_id'],
                        'grupo'   => $row['grup_nombre'],
                        'id'            => $row['n_id'],
                        'correlativo'   => $row['n_correlativo'],
                        'divisa'        => $row['div_nombre'],
                        'div_locale'    => $row['div_locale'],
                        'div_simbolo'   => $row['div_simbolo'],
                        'total'         => $row['n_total'],
                        'estatus'       => $row['n_estatus'],
                        'fecha'         => $row['fecha'],
                        'acumulado'     => $acumulado_total,
                        'sucursal'      => $row['su_nombre'],
                        'tipo'          => 'ORDENV' . $row['n_correlativo'],
                        'url'           => 'ordendeentregaeditar/verFactura/' . $row['n_id'],
                        'agente'        => ($row['n_empagente'] != NULL) ? $agente['einfo_nombres'] . ' ' . $agente['einfo_apellidos'] : $row['n_empagente'],
                        'pendiente'     => $row['n_total'] - $acumulado_total
                    ];

                    $ventas_pendientes += 1;

                    if (!in_array($row['div_id'], $ordenes_divisas_id)) {
                        $ordenes_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => $row['n_total'] - $acumulado_total
                        ];
                        $ordenes_divisas_id[] = $row['div_id'];
                    } else {
                        $ordenes_divisas[$row['div_id']]['total'] += $row['n_total'] - $acumulado_total;
                    }
                }
            }

            if (is_countable($facturas_divisas) && count($facturas_divisas)) {
                foreach ($facturas_divisas as $row) {
                    if (!in_array($row['div_id'], $total_divisa_id)) {
                        $totales_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => $row['total'],
                        ];
                        $total_divisa_id[] = $row['div_id'];
                    } else {
                        $totales_divisas[$row['div_id']]['total'] += $row['total'];
                    }
                }
            }

            if (is_countable($notas_divisas) && count($notas_divisas)) {
                foreach ($notas_divisas as $row) {
                    if (!in_array($row['div_id'], $total_divisa_id)) {
                        $totales_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => $row['total'],
                        ];
                        $total_divisa_id[] = $row['div_id'];
                    } else {
                        $totales_divisas[$row['div_id']]['total'] += $row['total'];
                    }
                }
            }

            if (is_countable($ordenes_divisas) && count($ordenes_divisas)) {
                foreach ($ordenes_divisas as $row) {
                    if (!in_array($row['div_id'], $total_divisa_id)) {
                        $totales_divisas[$row['div_id']] = [
                            'div_id'        => $row['div_id'],
                            'div_nombre'    => $row['div_nombre'],
                            'div_locale'    => $row['div_locale'],
                            'div_simbolo'   => $row['div_simbolo'],
                            'total'         => $row['total'],
                        ];
                        $total_divisa_id[] = $row['div_id'];
                    } else {
                        $totales_divisas[$row['div_id']]['total'] += $row['total'];
                    }
                }
            }

            Http::json_response([
                'facturas_pendiente'    => $array_factura,
                'notas_pendiente'       => $array_notas,
                'ordenes_pendientes'    => $array_ordenes,
                'totales_divisas_ord'   => $ordenes_divisas,
                'totales_divisas_fac'   => $facturas_divisas,
                'totales_divisas_not'   => $notas_divisas,
                'divisas_totales'       => $totales_divisas,
            ]);
        }
    }

    public function obtenerPrecioProductoVendidos()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha_desde    = filter_input(INPUT_GET, 'fecha_desde', FILTER_SANITIZE_STRING);
            $fecha_hasta    = filter_input(INPUT_GET, 'fecha_hasta', FILTER_SANITIZE_STRING);
            $id_divisa      = filter_input(INPUT_GET, 'divisa',FILTER_SANITIZE_NUMBER_INT);
            $sucursal      = filter_input(INPUT_GET, 'sucursal',FILTER_SANITIZE_NUMBER_INT);
            $filtro         = filter_input(INPUT_GET, 'filtro',FILTER_SANITIZE_NUMBER_INT);

            $ingresosegresos_model = new Ingresosegresos();

            if (empty($fecha_desde))
                $fecha_desde = (new DateTime(null, $this->timeZone))->modify('first day of this month')->format('Y-m-d');

            if (empty($fecha_hasta))
                $fecha_hasta = date('Y-m-d');

            if (empty($this->array_errors)) {

                if (!validateDate($fecha_desde, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha desde es incorrecta.';
                if (!validateDate($fecha_hasta, 'Y-m-d'))
                    $this->array_errors[] = 'La Fecha hasta es incorrecta.';

                if (empty($this->array_errors)) {

                    if (!empty($id_divisa)) {
                        $divisa = $ingresosegresos_model->obtenerDivisa($id_divisa);
                        $this->divisa_master['div_locale'] = $divisa['div_locale'];
                        $this->divisa_master['div_simbolo'] = $divisa['div_simbolo'];
                        $this->divisa_master['div_nombre'] = $divisa['div_nombre'];
                    }

                    $totales_productos  = [];

                    $total_notas = $ingresosegresos_model->obtenerArticulosDeNEVPREC($fecha_desde, $fecha_hasta, $id_divisa, $sucursal);
                    $total_facv = $ingresosegresos_model->obtenerArticulosDeFACVPREC($fecha_desde, $fecha_hasta, $id_divisa, $sucursal);

                    if (is_countable($total_notas) && count($total_notas)) {
                        foreach ($total_notas as $row) {

                            $pro =  $ingresosegresos_model->obtenerProductosid($row['proid']);

                            $ganancia = 0;
                            $ganancia_porct = 0;
                           
                            if ($this->divisa_master['div_id'] != $id_divisa && $id_divisa > 0) {
                                $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                $pro['pro_costo'] = round(($pro['pro_costo'] * $div_factor['df_factor']), 2);
                                $pro['pro_precio'] = round(($pro['pro_precio'] * $div_factor['df_factor']), 2);
                            }

                            if ($row['divisa'] != $id_divisa && $id_divisa > 0 /* $this->divisa_master['div_id']*/) {
                                $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                $row['precio'] = round(($row['precio'] * $div_factor['df_factor']), 2);
                            }

                            if ($row['divisa'] != $this->divisa_master['div_id'] && $id_divisa == 0 /* $this->divisa_master['div_id']*/) {
                                $factor = $ingresosegresos_model->divisaFactor($row['divisa'], $this->divisa_master['div_id']);
                                $row['total'] = round($row['total'] * $factor['df_factor'], 2);
                                $row['precio'] = round(($row['precio'] * $factor['df_factor']), 2);
                            }

                            $descuento = ($row['precio'] * $row['descuento']) / 100;
                            //$pro =  $ingresosegresos_model->obtenerProductosid($row['proid']);

                            if (($filtro == 1) && ($row['descuento'] == 0 && ($row['precio'] > $pro['pro_precio']))) {
                                $totales_productos[] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'pro_id'            => $pro['pro_id'],
                                    'pro_descripcion'   => $pro['pro_descripcion'],
                                    'pro_costo'         => $pro['pro_costo'],
                                    'precio_venta'      => $pro['pro_precio'],
                                    'precio_factura'    => $row['precio'],
                                    'precio_desc'       => $descuento,
                                    'descuento'         => $row['descuento'],
                                    'cantidad'          => $row['cantidad'],
                                    'costo_total'       => $pro['pro_costo'] * $row['cantidad'],
                                    'total'             => $row['total'],
                                    'id'                => $row['id'],
                                    'tipo'              => 'NEV',
                                    'url'               => 'notasdeentregaeditar/verFactura/' . $row['id'],
                                    'ganancia'          => $ganancia,
                                    'ganancia_porct'    => $ganancia_porct,
                                ];
                            }
                            if ($filtro == 2 && (($row['descuento'] == 0 && ($row['precio'] < $pro['pro_precio'])) || ($row['descuento'] > 0 && ($descuento < $pro['pro_precio'])))) {
                                $totales_productos[] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'pro_id'            => $pro['pro_id'],
                                    'pro_descripcion'   => $pro['pro_descripcion'],
                                    'pro_costo'         => $pro['pro_costo'],
                                    'precio_venta'      => $pro['pro_precio'],
                                    'precio_factura'    => $row['precio'],
                                    'precio_desc'       => $descuento,
                                    'descuento'         => $row['descuento'],
                                    'cantidad'          => $row['cantidad'],
                                    'costo_total'       => $pro['pro_costo'] * $row['cantidad'],
                                    'total'             => $row['total'],
                                    'id'                => $row['id'],
                                    'tipo'              => 'NEV',
                                    'url'               => 'notasdeentregaeditar/verFactura/' . $row['id'],
                                    'ganancia'          => $ganancia,
                                    'ganancia_porct'    => $ganancia_porct,
                                ];
                            }
                        }
                    }

                    if (is_countable($total_facv) && count($total_facv)) {

                        foreach ($total_facv as $row_dos) {

                            $pro =  $ingresosegresos_model->obtenerProductosid($row_dos['proid']);

                            $ganancia = 0;
                            $ganancia_porct = 0;

                            if (!empty($id_divisa) && $id_divisa > 0) {

                                if ($this->divisa_master['div_id'] != $id_divisa) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $id_divisa);
                                    $pro['pro_costo'] = round(($pro['pro_costo'] * $div_factor['df_factor']), 2);
                                    $pro['pro_precio'] = round(($pro['pro_precio'] * $div_factor['df_factor']), 2);
                                }

                                if ($row_dos['divisa'] != $id_divisa /* $this->divisa_master['div_id']*/) {
                                    $factor = $ingresosegresos_model->divisaFactor($row_dos['divisa'], $this->divisa_master['div_id']);
                                    $row_dos['total'] = round($row_dos['total'] * $factor['df_factor'], 2);
                                    $row_dos['precio'] = round(($row_dos['precio'] * $div_factor['df_factor']), 2);
                                }
                            } else {
                                if ($row_dos['divisa'] != $this->divisa_master['div_id']) {
                                    $factor = $ingresosegresos_model->divisaFactor($row_dos['divisa'], $this->divisa_master['div_id']);
                                    $row_dos['total'] = round($row_dos['total'] * $factor['df_factor'], 2);
                                    $row_dos['precio'] = round(($row_dos['precio'] * $factor['df_factor']), 2);
                                }
                            }
                            $descuento = ($row_dos['precio'] * $row_dos['descuento']) / 100;

                            if ($filtro == 1 && ($row_dos['descuento'] == 0 && ($row_dos['precio'] > $pro['pro_precio']))) {
                                $totales_productos[] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'pro_id'            => $pro['pro_id'],
                                    'pro_descripcion'   => $pro['pro_descripcion'],
                                    'pro_costo'         => $pro['pro_costo'],
                                    'precio_venta'      => $pro['pro_precio'],
                                    'precio_factura'    => $row_dos['precio'],
                                    'precio_desc'       => $descuento,
                                    'descuento'         => $row_dos['descuento'],
                                    'cantidad'          => $row_dos['cantidad'],
                                    'costo_total'       => $pro['pro_costo'] * $row_dos['cantidad'],
                                    'total'             => $row_dos['total'],
                                    'id'                => $row_dos['id'],
                                    'tipo'              => 'FACV',
                                    'url'               => 'poseditar/verFactura/' . $row_dos['id'],
                                    'ganancia'          => $ganancia,
                                    'ganancia_porct'    => $ganancia_porct,
                                ];
                            }
                            if ($filtro == 2 && ($row_dos['descuento'] == 0 && ($row_dos['precio'] < $pro['pro_precio'])) || ($row_dos['descuento'] > 0 && ($descuento < $pro['pro_precio']))) {
                                $totales_productos[] = [
                                    'div_locale'        => $this->divisa_master['div_locale'],
                                    'div_simbolo'       => $this->divisa_master['div_simbolo'],
                                    'div_nombre'        => $this->divisa_master['div_nombre'],
                                    'pro_id'            => $pro['pro_id'],
                                    'pro_descripcion'   => $pro['pro_descripcion'],
                                    'pro_costo'         => $pro['pro_costo'],
                                    'precio_venta'      => $pro['pro_precio'],
                                    'precio_factura'    => $row_dos['precio'],
                                    'precio_desc'       => $descuento,
                                    'descuento'         => $row_dos['descuento'],
                                    'cantidad'          => $row_dos['cantidad'],
                                    'costo_total'       => $pro['pro_costo'] * $row_dos['cantidad'],
                                    'total'             => $row_dos['total'],
                                    'id'                => $row_dos['id'],
                                    'tipo'              => 'FACV',
                                    'url'               => 'poseditar/verFactura/' . $row_dos['id'],
                                    'ganancia'          => $ganancia,
                                    'ganancia_porct'    => $ganancia_porct,
                                ];
                            }
                        }
                    }

                    Http::json_response([
                        'productos'     => $totales_productos
                    ]);
                }
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function produccionDiaHora()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $fecha   = filter_input(INPUT_GET, 'fecha', FILTER_SANITIZE_NUMBER_INT);
            $div_id = filter_input(INPUT_GET, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $sucursal = filter_input(INPUT_GET, 'sucursal', FILTER_SANITIZE_NUMBER_INT);

            if (empty($this->array_errors)) {

                $ingresosegresos_model = new Ingresosegresos();

                $array_notas        = [];
                $array_notas_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;
                $ganancia           = 0;
                $porcentaje         = 0;

                $notas = $ingresosegresos_model->obtenerProduccionNEVDiaHora($fecha, $div_id, $sucursal);
                $ordenes = $ingresosegresos_model->obtenerProduccionORDENDiaHora($fecha, $div_id, $sucursal);
                $facturas = $ingresosegresos_model->obtenerProduccionFACVDiaHora($fecha, $div_id, $sucursal);

                if ($div_id > 0) {
                    $divisa = $ingresosegresos_model->obtenerDivisa($div_id);
                } else {
                    $divisa = $ingresosegresos_model->obtenerDivisa($this->divisa_master['div_id']);
                }

                if (is_countable($notas) && count($notas)) {
                    foreach ($notas as $row) {
                        if (!in_array($row['hora'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    // $row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['hora']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'hora'           => $row['hora'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['hora'];
                        } else {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //  $row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['hora']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['hora']]['costo']      += $row['total_costo'];
                            $array_notas[$row['hora']]['venta']      += $row['total_venta'];
                            $array_notas[$row['hora']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['hora']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($ordenes) && count($ordenes)) {

                    foreach ($ordenes as $row) {

                        if (!in_array($row['hora'], $array_notas_id)) {

                            if ($row['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }
                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['hora']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'hora'           => $row['hora'],
                                'cantidad'      => $row['cantidad'],
                                'costo'         => $row['total_costo'],
                                'venta'         => $row['total_venta'],
                                'ganancia'      => $row['total_venta'] - $row['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row['su_nombre'],
                            ];
                            $array_notas_id[] = $row['hora'];
                        } else {

                            if ($row['total_venta'] > 0) {
                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                                    $row['total_costo'] *= $div_factor['df_factor'];
                                    $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row['total_venta'] - $row['total_costo']) * 100 / $row['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row['hora']]['cantidad']   += $row['cantidad'];
                            $array_notas[$row['hora']]['costo']      += $row['total_costo'];
                            $array_notas[$row['hora']]['venta']      += $row['total_venta'];
                            $array_notas[$row['hora']]['ganancia']   += $row['total_venta'] - $row['total_costo'];
                            $array_notas[$row['hora']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row['cantidad'];
                        $costo          += $row['total_costo'];
                        $venta          += $row['total_venta'];
                    }
                }

                if (is_countable($facturas) && count($facturas)) {

                    foreach ($facturas as $row_dos) {

                        if (!in_array($row_dos['hora'], $array_notas_id)) {

                            if ($row_dos['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row_dos['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row_dos['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row_dos['fm_divid'], $this->divisa_master['div_id']);
                                    $row_dos['total_costo'] *= $div_factor['df_factor'];
                                    $row_dos['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row_dos['total_venta'] - $row_dos['total_costo']) * 100 / $row_dos['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row_dos['hora']] = [
                                'div_locale'    => $divisa['div_locale'],
                                'div_simbolo'   => $divisa['div_simbolo'],
                                'hora'           => $row_dos['hora'],
                                'cantidad'      => $row_dos['cantidad'],
                                'costo'         => $row_dos['total_costo'],
                                'venta'         => $row_dos['total_venta'],
                                'ganancia'      => $row_dos['total_venta'] - $row_dos['total_costo'],
                                'porcentaje'    => $porc,
                                'sucursal'    => $row_dos['su_nombre'],
                            ];
                            $array_notas_id[] = $row_dos['hora'];
                        } else {

                            if ($row_dos['total_venta'] > 0) {

                                if ($this->divisa_master['div_id'] != $div_id && $div_id > 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($this->divisa_master['div_id'], $div_id);
                                    //$row_dos['total_costo'] *= $div_factor['df_factor'];
                                    // $row['total_venta'] *= $div_factor['df_factor'];
                                }

                                if ($row_dos['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                                    $div_factor = $ingresosegresos_model->divisaFactor($row_dos['fm_divid'], $this->divisa_master['div_id']);
                                    $row_dos['total_costo'] *= $div_factor['df_factor'];
                                    $row_dos['total_venta'] *= $div_factor['df_factor'];
                                }

                                $porc = round((($row_dos['total_venta'] - $row_dos['total_costo']) * 100 / $row_dos['total_venta']), 2);
                            } else {
                                $porc = 0;
                            }

                            $array_notas[$row_dos['hora']]['cantidad']   += $row_dos['cantidad'];
                            $array_notas[$row_dos['hora']]['costo']      += $row_dos['total_costo'];
                            $array_notas[$row_dos['hora']]['venta']      += $row_dos['total_venta'];
                            $array_notas[$row_dos['hora']]['ganancia']   += $row_dos['total_venta'] - $row_dos['total_costo'];
                            $array_notas[$row_dos['hora']]['porcentaje'] += $porc;
                        }

                        $artic_total    += $row_dos['cantidad'];
                        $costo          += $row_dos['total_costo'];
                        $venta          += $row_dos['total_venta'];
                    }
                }

                if ($costo > 0 && $venta > 0) {
                    $ganancia = $venta - $costo;
                    $porcentaje = round(($ganancia * 100 / $venta), 2);
                }

                Http::json_response([
                    'costo'         => Moneda::moneda($costo, $divisa['div_locale'], $divisa['div_simbolo']),
                    'venta'         => Moneda::moneda($venta, $divisa['div_locale'], $divisa['div_simbolo']),
                    'ganancia'      => Moneda::moneda($ganancia, $divisa['div_locale'], $divisa['div_simbolo']),
                    'porcentaje'    => round($porcentaje),
                    'art_total'     => $artic_total,
                    'horas'          => $array_notas
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function obtenerIngresosDiariosDocumentos()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if (empty($this->array_errors)) {

                $div_id = $this->solicitud->sanitize($_POST['divisa'], FILTER_SANITIZE_NUMBER_INT);
                $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);
                $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);

                $array_notas        = [];
                $array_notas_id     = [];
                $array_documentos_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;
                if($div_id==0){
                    $notas = $this->facturacionModel->obtenerProduccionNEVDiaTodas($sucursal,$mes);
                    $facturas = $this->facturacionModel->obtenerProduccionFACVDiaTodas($sucursal,$mes);
                    $orden = $this->facturacionModel->obtenerProduccionORDVDiaTodas($sucursal,$mes);
                    $divisa = $this->facturacionModel->obtenerDivisaMaster();
                }else{
                    $notas = $this->facturacionModel->obtenerProduccionNEVDia($sucursal,$mes,$div_id);
                    $facturas = $this->facturacionModel->obtenerProduccionFACVDia($sucursal,$mes,$div_id);
                    $orden = $this->facturacionModel->obtenerProduccionORDVDia($sucursal,$mes,$div_id);
                    $divisa = $this->facturacionModel->obtenerDivisa($div_id);
                }

                if (is_countable($notas) && count($notas)) {

                    foreach ($notas as $row) {

                        if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                            $row['total'] *= $div_factor['df_factor'];
                        }

                        if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row['n_dia_semana']] = [
                                'n_dia_semana'  => $row['n_dia_semana'],
                                'venta'         => $row['total'],
                                'documentos'    => $row['documentos']
                            ];
                            $array_notas_id[] = $row['n_dia_semana'];
                        } else {
                            $array_notas[$row['n_dia_semana']]['venta']      += $row['total'];
                            $array_notas[$row['n_dia_semana']]['documentos']      += $row['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row['total'];
                    }
                }

                if (is_countable($facturas) && count($facturas)) {

                    foreach ($facturas as $row_dos) {

                        if ($row_dos['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row_dos['fm_divid'], $this->divisa_master['div_id']);
                            $row_dos['total'] *= $div_factor['df_factor'];
                        }

                        if (!in_array($row_dos['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row_dos['n_dia_semana']] = [
                                'n_dia_semana'  => $row_dos['n_dia_semana'],
                                'venta'         => $row_dos['total'],
                                'documentos'    =>$row_dos['documentos']
                            ];
                            $array_notas_id[] = $row_dos['n_dia_semana'];
                        } else {
                            $array_notas[$row_dos['n_dia_semana']]['venta']      += $row_dos['total'];
                            $array_notas[$row_dos['n_dia_semana']]['documentos']      += $row_dos['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row_dos['total'];
                    }
                }

                if (is_countable($orden) && count($orden)) {

                    foreach ($orden as $row) {

                        if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                            $row['total'] *= $div_factor['df_factor'];
                        }


                        if (!in_array($row['n_dia_semana'], $array_notas_id)) {
                            $array_notas[$row['n_dia_semana']] = [
                                'n_dia_semana'  => $row['n_dia_semana'],
                                'venta'         => $row['total'],
                                'documentos'    => $row['documentos']
                            ];
                            $array_notas_id[] = $row['n_dia_semana'];
                        } else {
                            $array_notas[$row['n_dia_semana']]['venta']      += $row['total'];
                            $array_notas[$row['n_dia_semana']]['documentos']      += $row['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row['total'];
                    }
                }


                Http::json_response([
                    'dias_semana'   => $array_notas,
                    'div_locale'    => $divisa['div_locale'],
                    'div_simbolo'  => $divisa['div_simbolo'],
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }

    public function obtenerIngresosDiariosDocumentosHora()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            if (empty($this->array_errors)) {

                $div_id = $this->solicitud->sanitize($_POST['divisa'], FILTER_SANITIZE_NUMBER_INT);
                $sucursal = $this->solicitud->sanitize($_POST['sucursal'], FILTER_SANITIZE_NUMBER_INT);
                $mes = $this->solicitud->sanitize($_POST['mes'], FILTER_SANITIZE_NUMBER_INT);

                $array_notas        = [];
                $array_notas_id     = [];
                $array_documentos_id     = [];
                $artic_total        = 0;
                $costo              = 0;
                $venta              = 0;

                if($div_id==0){
                    $notas = $this->facturacionModel->obtenerProduccionNEVDiaHoraTodas($sucursal,$mes);
                    $facturas = $this->facturacionModel->obtenerProduccionFACVDiaHoraTodas($sucursal,$mes);
                    $orden = $this->facturacionModel->obtenerProduccionORDVDiaHoraTodas($sucursal,$mes);
                    $divisa = $this->facturacionModel->obtenerDivisaMaster();
                }else{
                    $notas = $this->facturacionModel->obtenerProduccionNEVDiaHora($sucursal,$mes,$div_id);
                    $facturas = $this->facturacionModel->obtenerProduccionFACVDiaHora($sucursal,$mes,$div_id);
                    $orden = $this->facturacionModel->obtenerProduccionORDVDiaHora($sucursal,$mes,$div_id);
                    $divisa = $this->facturacionModel->obtenerDivisa($div_id);
                }
                

                if (is_countable($notas) && count($notas)) {

                    foreach ($notas as $row) {

                        if ($row['ne_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row['ne_divid'], $this->divisa_master['div_id']);
                            $row['total'] *= $div_factor['df_factor'];
                        }

                        if (!in_array($row['hora'], $array_notas_id)) {
                            $array_notas[$row['hora']] = [
                                'hora'  => $row['hora'],
                                'venta'         => $row['total'],
                                'documentos'    => $row['documentos']
                            ];
                            $array_notas_id[] = $row['hora'];
                        } else {
                            $array_notas[$row['hora']]['venta']      += $row['total'];
                            $array_notas[$row['hora']]['documentos']      += $row['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row['total'];
                    }
                }

                if (is_countable($facturas) && count($facturas)) {

                    foreach ($facturas as $row) {

                        if ($row['fm_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row['fm_divid'], $this->divisa_master['div_id']);
                            $row['total'] *= $div_factor['df_factor'];
                        }

                        if (!in_array($row['hora'], $array_notas_id)) {
                            $array_notas[$row['hora']] = [
                                'hora'  => $row['hora'],
                                'venta'         => $row['total'],
                                'documentos'    => $row['documentos']
                            ];
                            $array_notas_id[] = $row['hora'];
                        } else {
                            $array_notas[$row['hora']]['venta']      += $row['total'];
                            $array_notas[$row['hora']]['documentos']      += $row['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row['total'];
                    }
                }

                if (is_countable($orden) && count($orden)) {

                    foreach ($orden as $row) {

                        if ($row['n_divid'] != $this->divisa_master['div_id'] && $div_id == 0) {
                            $div_factor = $this->facturacionModel->divisaFactor($row['n_divid'], $this->divisa_master['div_id']);
                            $row['total'] *= $div_factor['df_factor'];
                        }

                        if (!in_array($row['hora'], $array_notas_id)) {
                            $array_notas[$row['hora']] = [
                                'hora'  => $row['hora'],
                                'venta'         => $row['total'],
                                'documentos'    => $row['documentos']
                            ];
                            $array_notas_id[] = $row['hora'];
                        } else {
                            $array_notas[$row['hora']]['venta']      += $row['total'];
                            $array_notas[$row['hora']]['documentos']      += $row['documentos'];
                        }

                        $artic_total    += 1;
                        $venta          += $row['total'];
                    }
                }

                Http::json_response([
                    'horas'   => $array_notas,
                    'div_locale'    => $divisa['div_locale'],
                    'div_simbolo'  => $divisa['div_simbolo'],
                ]);
            }

            Http::json_response([
                'errors'   => $this->array_errors,
            ]);
        }
    }
}
