!C99Shell v. 2.0 [PHP 7 Update] [25.02.2019]!

Software: Apache/2.4.18 (Ubuntu). PHP/7.0.33-0ubuntu0.16.04.16 

uname -a: Linux digifus 3.13.0-57-generic #95-Ubuntu SMP Fri Jun 19 09:28:15 UTC 2015 x86_64 

uid=33(www-data) gid=33(www-data) groups=33(www-data) 

Safe-mode: OFF (not secure)

/var/www/html/almazenServer/application/models/   drwxr-xr-x
Free 10.11 GB of 29.4 GB (34.38%)
Home    Back    Forward    UPDIR    Refresh    Search    Buffer    Encoder    Tools    Proc.    FTP brute    Sec.    SQL    PHP-code    Update    Feedback    Self remove    Logout    


Viewing file:     consultas_model.php (171.98 KB)      -rw-r--r--
Select action/file-type:
(+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
if (!defined('BASEPATH')) {
    exit(
'No direct script access allowed');
}

class 
Consultas_model extends CI_Model
{
    public function 
__construct()
    {
        
parent::__construct();
    }

    
//get the username & password from tbl_usrs
    
public function get_user($usr$pwd)
    {
        
$sql   "select * from tbl_usrs where username = '" $usr "' and password = '" md5($pwd) . "' and status = 'active'";
        
$query $this->db->query($sql);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    
//obtenemos las entradas de todos o un usuario, dependiendo
    // si le pasamos le id como argument o no
    
public function users_entrys($id false)
    {
        if (
$id === false) {
            
$this->db->select('u.username,u.fname,u.lname,u.register_date,e.titulo,e.entrada,e.publish_date');
            
$this->db->from('users u');
            
$this->db->join('entradas e''u.id = e.id_user');
        } else {
            
$this->db->select('u.username,u.fname,u.lname,u.register_date,e.titulo,e.entrada,e.publish_date');
            
$this->db->from('users u');
            
$this->db->join('entradas e''u.id = e.id_user');
            
$this->db->where('u.id'$id);
        }
        
$query $this->db->get();
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    
//obtenemos todos los comentarios de un usuario y sus datos si le pasamos
    //un id como argumento, y si no los cogemos todos
    
public function users_coments($id false)
    {
        if (
$id === false) {
            
$this->db->select('u.username,c.titulo_comentario,c.comentario,c.comment_date');
            
$this->db->from('comentarios c');
            
$this->db->join('users u''c.id_user = u.id');
        } else {
            
$this->db->select('u.username,c.titulo_comentario,c.comentario,c.comment_date');
            
$this->db->from('comentarios c');
            
$this->db->join('users u''c.id_user = u.id');
            
$this->db->where('u.id'$id);
        }
        
$query $this->db->get();
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_encadendada($id)
    {
        
$this->db->select('username')->from('users')->where('id >='$id)->limit(010);
        
$query $this->db->get();
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDatosPagoPedido($nroPedido)
    {
        
$query $this->db->query("select id as id, a.fechaPago as fechaPago,b.tipoPago as tipoPago,a.datoPago as datoPago,a.valor as valor,a.recibo as recibo, a.saldo_pago as saldo from pago_pedido a left join tipo_pago b ON b.id_pago=a.id_tipo_pago where a.id_pedido='" $nroPedido "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    
// terminando
    
public function ventasTotalesArticuloPorEstadoPagados($articulo$fechaInicio$fechaFin)
    {
        
$fechaF date('Y-m-d');
        
$fechaF "'" $fechaF "'";

        if (
$articulo == null) {
            
$articulo "3402-1";
        }

        if (
$fechaInicio == null) {
            
$fechaInicio "2015-08-01";
        }
        if (
$fechaFin == null) {
            
$fechaFin $fechaF;
        }

        
$consulta "select  c.nombre  as NOMBRE,SUM(a.cantidad) as cantidad,d.estado as estado from detalle_pedido a
         left join pedidos b ON b.id_pedido=a.id_pedido
        left join productos c ON c.nombre=a.nombre_producto
        left join estado_pedidos d on d.id=b.id_estado
        right join detalle_check_pago e ON e.id_pedido=b.id_pedido
        where  c.nombre ='" 
$articulo "'  and e.id_check='1' and b.id_estado != '3' and b.fecha>='" $fechaInicio "' and b.fecha<=" $fechaFin " and  b.id_cliente not in (3364,3365,3366,3514)
         group by 3 order by 3 desc;"
;

        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
ventasTotalesArticuloPorEstadoNoPagados($articulo$fechaInicio$fechaFin)
    {
        
$fechaF date('Y-m-d');
        
$fechaF "'" $fechaF "'";

        if (
$articulo == null) {
            
$articulo "3402-1";
        }

        if (
$fechaInicio == null) {
            
$fechaInicio "2015-08-01";
        }
        if (
$fechaFin == null) {
            
$fechaFin $fechaF;
        }

        
$consulta "select  c.nombre  as NOMBRE,SUM(a.cantidad) as cantidad,d.estado as estado from detalle_pedido a
         left join pedidos b ON b.id_pedido=a.id_pedido
        left join productos c ON c.nombre=a.nombre_producto
        left join estado_pedidos d on d.id=b.id_estado
        left join detalle_check_pago e ON e.id_pedido=b.id_pedido
        where  c.nombre ='" 
$articulo "'  and e.id_pedido is null and b.id_estado != '3' and b.fecha>='" $fechaInicio "' and b.fecha<=" $fechaFin " and  b.id_cliente not in (3364,3365,3366,3514)
         group by 3 order by 3 desc;"
;

        
$query $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }
    public function 
ventasTotalesArticulo($articulo$fechaInicio$fechaFin)
    {

        
$fechaF date('Y-m-d');
        
$fechaF "'" $fechaF "'";

        if (
$articulo == null) {
            
$articulo "3402-1";
        }

        if (
$fechaInicio == null) {
            
$fechaInicio "2015-08-01";
        }
        if (
$fechaFin == null) {
            
$fechaFin $fechaF;
        }

        
$consulta "select  c.nombre  as NOMBRE,SUM(a.cantidad) as cantidad from detalle_pedido a left join pedidos b ON b.id_pedido=a.id_pedido
        left join productos c ON c.nombre=a.nombre_producto
        where  c.nombre ='" 
$articulo "' and b.id_estado != '3' and b.fecha>='" $fechaInicio "' and b.fecha<=" $fechaFin " and  b.id_cliente not in (3364,3365,3366,3514)
         group by c.nombre order by 1 desc;"
;

        
$query $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
ventasTotalesArticuloPagado($articulo$fechaInicio$fechaFin)
    {
        
$fechaF date('Y-m-d');
        
$fechaF "'" $fechaF "'";

        if (
$articulo == null) {
            
$articulo "3402-1";
        }

        if (
$fechaInicio == null) {
            
$fechaInicio "2015-08-01";
        }
        if (
$fechaFin == null) {
            
$fechaFin $fechaF;
        }

        
$consulta "select  c.nombre  as NOMBRE,SUM(a.cantidad) as cantidad from detalle_pedido a left join pedidos b ON b.id_pedido=a.id_pedido
        left join productos c ON c.nombre=a.nombre_producto
        right join detalle_check_pago e ON e.id_pedido=b.id_pedido
        where  c.nombre ='" 
$articulo "' and e.id_check='1' and b.id_estado != '3' and b.fecha>='" $fechaInicio "' and b.fecha<=" $fechaFin " and  b.id_cliente not in (3364,3365,3366,3514)
         group by c.nombre order by 1 desc;"
;

        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
ventasTotalesArticuloNoPagado($articulo$fechaInicio$fechaFin)
    {
        
$fechaF date('Y-m-d');
        
$fechaF "'" $fechaF "'";

        if (
$articulo == null) {
            
$articulo "3402-1";
        }

        if (
$fechaInicio == null) {
            
$fechaInicio "2015-08-01";
        }
        if (
$fechaFin == null) {
            
$fechaFin $fechaF;
        }

        
$consulta "select  c.nombre  as NOMBRE,SUM(a.cantidad) as cantidad from detalle_pedido a left join pedidos b ON b.id_pedido=a.id_pedido
        left join productos c ON c.nombre=a.nombre_producto
        left join detalle_check_pago e ON e.id_pedido=b.id_pedido
        where  c.nombre ='" 
$articulo "' and e.id_pedido is null  and e.id_pedido is null and b.id_estado != '3' and b.fecha>='" $fechaInicio "' and b.fecha<=" $fechaFin " and  b.id_cliente not in (3364,3365,3366,3514)
         group by c.nombre order by 1 desc;"
;

        
$query $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getPedidos15DiasDepo()
    {

        
$fechaInicial date('Y-m-d');
        
$fechaFinal   strtotime('-15 day'strtotime($fechaInicial));
        
$fechaFinal   date('Y-m-d'$fechaFinal);
        
$fechaFinal   "'" $fechaFinal "'";

        
$consulta "select *,c.fecha as fechaConfirmado from pedidos a left join clientes b ON b.id=a.id_cliente
                left join auditoria c ON c.id_pedido=a.id_pedido
                where a.id_estado in (7,11) and c.fecha<=" 
$fechaFinal " order by c.fecha asc";

        
$query $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
registrarPago($nroPedido$tipo$dato$valor$saldo$recibo)
    {

        
$data = array(
            
'id_pedido'    => $nroPedido,
            
'fechaPago'    => date('Y-m-d H:i:s'),
            
'id_tipo_pago' => $tipo,
            
'datoPago'     => $dato,
            
'valor'        => $valor,
            
'saldo_pago'   => $saldo,
            
'recibo'       => $recibo,
        );
        
$this->db->insert('pago_pedido'$data);
    }

    public function 
registrarRetencion($retencion$cliente$recibo$tipoRetencion)
    {
        
$data = array(
            
'id_cliente'    => $cliente,
            
'tipoRetencion' => $tipoRetencion,
            
'monto'         => $retencion,
            
'fecha'         => date('Y-m-d'),
            
'nroRecibo'     => $recibo,
        );
        
$this->db->insert('retenciones'$data);
    }

    public function 
borrarReg($nroPedido$producto)
    {
        
$query $this->db->query("delete from detalle_pedido where id_pedido='" $nroPedido "' and nombre_producto='" $producto "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
eliminarCheque($nro)
    {
        
$query $this->db->query("delete from cheques where nro_cheque='" $nro "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
eliminarRegistroPagoPedido($nro)
    {

        
$this->db->delete('pago_pedido', array('id' => $nro));
        return 
$this->db->affected_rows() > true false;

    }

    public function 
registrarCheque($nroCheque$cliente$estado$titular$fechaVenc$banco$monto)
    {
        
$data = array(
            
'nro_cheque'        => $nroCheque,
            
'id_cliente'        => $cliente,
            
'id_estado'         => $estado,
            
'titular'           => $titular,
            
'fecha_vencimiento' => $fechaVenc,
            
'banco'             => $banco,
            
'monto'             => $monto,
        );
        
$this->db->insert('cheques'$data);
    }

    public function 
getCheques($buscador$num$offset)
    {

        
$consulta "cheques a left join estadoscheque b ON  a.id_estado=b.id_estado left join clientes c ON a.id_cliente=c.id ";

        if (
$buscador != null) {
            
$this->db->where('nro_cheque'$buscador);

        }
        
$query $this->db->get($consulta$num$offset);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getRemitosByCliente($id)
    {
        
$query $this->db->query("select nro_remito from remito where id_cliente='" $id "' and id_estado='1';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getStockArticulo($articulo)
    {
        
$query $this->db->query("select stock from stock_productos where nombre_producto='" $articulo "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->stock;
        }
    }

    public function 
consulta_pedido($id)
    {
        
$query $this->db->query("select * from pedidos where id_pedido='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
consulta_pago($id)
    {
        
$query $this->db->query("select * from pago_pedido where id='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
eliminarContacto($id)
    {
        
$query $this->db->query("delete from contactos where id='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
search_users($string$pos_comodin)
    {
        
$this->db->like('username'$string$pos_comodin);
        
$query $this->db->get('users');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_clientes($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('clientes'$num$offset);
        return 
$query;
    }

    public function 
consulta_clientesA($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }
        
$this->db->where('iva'"Resp Inscripto");
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('clientes'$num$offset);
        return 
$query;
    }

    public function 
consulta_clientesB($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }

        
$this->db->where('iva'"Monotributista");
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('clientes'$num$offset);
        return 
$query;
    }

    public function 
consulta_pedidos($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('clientes.razon_social'$buscador);
        }

        
$this->db->where('pedidos.id_estado'"1");
        
$this->db->order_by("fecha""desc");
        
$this->db->join('clientes''clientes.id = pedidos.id_cliente''left');
        
$query $this->db->get('pedidos'$num$offset);
        return 
$query;
    }

    public function 
consulta_proveedores($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('proveedores'$num$offset);
        return 
$query;
    }

    public function 
cantidadProductos()
    {
        
$query $this->db->query("SELECT count(*) as cant FROM productos");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
getMedioPago()
    {
        
$query $this->db->get('medios_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getCondPago()
    {
        
$query $this->db->get('cond_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdpedido($numero)
    {
        
$query $this->db->query("SELECT id_estado FROM pedidos where id_pedido='" $numero "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->id_estado;
        }
    }

    public function 
getIdDetalleMedioPago($pedido)
    {
        
$query $this->db->get_where('detalle_medio_pago', array('id_pedido' => $pedido));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }
    }

    public function 
getIdDetalleCondPago($pedido)
    {
        
$query $this->db->get_where('detalle_cond_pago', array('id_pedido' => $pedido));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }
    }

    public function 
getIdDetalleCheckPago($pedido)
    {
        
$query $this->db->get_where('detalle_check_pago', array('id_pedido' => $pedido));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }
    }

    public function 
registrarMedioPago($nroPedido$medioPago)
    {
        
$respuesta $this->getIdDetalleMedioPago($nroPedido);

        if (
$respuesta->id_detalle != null) {
            
$data = array(
                
'id_pago' => $medioPago,
            );
            
$this->db->where('id_detalle'$respuesta->id_detalle);
            
$this->db->update('detalle_medio_pago'$data);

        } else {
            
$data = array(
                
'id_pago'   => $medioPago,
                
'id_pedido' => $nroPedido,

            );
            
$this->db->insert('detalle_medio_pago'$data);
        }
    }
    public function 
getIdDetalleBultos($pedido)
    {
        
$query $this->db->get_where('bultos', array('id_pedido' => $pedido));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }
    }
    public function 
updateArticulo($nombreArticulo$descripcionArticulo,
        
$estadoArticulo$categoriaArticulo$numeroArticulo$precio) {

        
$data = array(
            
'descripcion'  => $descripcionArticulo,
            
'id_estado'    => $estadoArticulo,
            
'id_categoria' => $categoriaArticulo,
            
'numero'       => $numeroArticulo,
            
'precio'       => $precio,
            
'precio_venta' => $precio,
        );
        
$this->db->where('nombre'$nombreArticulo);
        
$this->db->update('productos'$data);

        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
cerrarOrdenAbierta($orden$usuario)
    {

        
$data = array(
            
'id_estado' => '1',
            
'usuario'   => $usuario,
            
'fecha'     => $this->getFechaOrden($orden),
        );

        
$this->db->where('id_impresion'$orden);
        
$this->db->update('impresiones'$data);

        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
getFechaOrden($nropedido)
    {
        
$query $this->db->query("SELECT fecha FROM impresiones where id_impresion ='" $nropedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->fecha;
        }
    }

    public function 
getOrdenAbierta($usuario)
    {
        
$query $this->db->query("SELECT id_impresion FROM impresiones where usuario ='" $usuario "' and id_estado='4';");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->id_impresion;
        }
    }

    public function 
getInfoPedido($nroPedido)
    {
        
$query $this->db->query("select a.subtotal as subtotal,a.total as total,b.razon_social as cliente from pedidos a
                left join clientes b ON a.id_cliente=b.id where a.id_pedido ='" 
$nroPedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDatosArticuloActualizacion($articulo)
    {
        
$query $this->db->query("select * from productos a
                left join stock_productos b ON a.nombre=b.nombre_producto where a.nombre ='" 
$articulo "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0];
        }
    }

    public function 
getDatosArticulo($articulo)
    {
        
$query $this->db->query("select a.nombre as nombre,a.descripcion as descripcion,
                a.precio_venta as precio,a.numero as numero,c.estado as estado,b.stock as stock , d.categoria as categoria
                from productos a
                left join stock_productos b on b.nombre_producto=a.nombre
                left join estado_productos c on a.id_estado=c.id
                left join categorias_productos d on d.id=a.id_categoria
                where a.nombre ='" 
$articulo "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0];
        }
    }

    public function 
crearOrdenAbierta($usuario)
    {
        
$data = array(
            
'usuario'   => $usuario,
            
'id_estado' => '4',
            
'fecha'     => date('Y-m-d'),
        );
        
$this->db->insert('impresiones'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
llenarLogArticulos($nombreArticulo$descripcionArticulo,
        
$estado$categoria$numeroArticulo$precio$stock$usuario) {
        
$data = array(
            
'nombre'       => $nombreArticulo,
            
'descripcion'  => $descripcionArticulo,
            
'id_estado'    => $estado,
            
'id_categoria' => $categoria,
            
'numero'       => $numeroArticulo,
            
'precio'       => $precio,
            
'stock'        => $stock,
            
'usuario'      => $usuario,
            
'fecha'        => date('Y-m-d'),
            
'precio_venta' => $precio,

        );
        
$this->db->where('nombre'$nombreArticulo);
        
$this->db->insert('productos_log'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
insertarStock($articulo$stock)
    {

        
$data = array(
            
'nombre_producto' => $articulo,
            
'stock'           => $stock,
        );

        
$this->db->insert('stock_productos'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
crearArticulo($nombreArticulo$descripcionArticulo,
        
$estado$categoria$numeroArticulo$precio) {
        
$data = array(
            
'nombre'       => $nombreArticulo,
            
'descripcion'  => $descripcionArticulo,
            
'precio'       => $precio,
            
'id_estado'    => $estado,
            
'id_proveedor' => '0',
            
'id_modelo'    => '0',
            
'numero'       => $numeroArticulo,
            
'id_categoria' => $categoria,
            
'precio_venta' => $precio,

        );
        
$this->db->insert('productos'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
registrarBultos($nroPedido$usuario$bultosPeralta$bultosLista$unidadPeralta$unidadLista)
    {

        
$respuesta $this->getIdDetalleBultos($nroPedido);
        
//si no tiene inserto sino actualizo
        
if ($respuesta->id_despacho != null) {
            
$data = array(
                
'username'         => $usuario,
                
'fecha'            => date('Y-m-d'),
                
'bulto_peralta'    => $bultosPeralta,
                
'bulto_lista'      => $bultosLista,
                
'unidades_peralta' => $unidadPeralta,
                
'unidades_lista'   => $unidadLista,

            );
            
$this->db->where('id_pedido'$nroPedido);
            
$this->db->update('bultos'$data);
        } else {

            
$data = array(
                
'id_pedido'        => $nroPedido,
                
'username'         => $usuario,
                
'fecha'            => date('Y-m-d'),
                
'bulto_peralta'    => $bultosPeralta,
                
'bulto_lista'      => $bultosLista,
                
'unidades_peralta' => $unidadPeralta,
                
'unidades_lista'   => $unidadLista,

            );
            
$this->db->insert('bultos'$data);
        }

    }

    public function 
registrarCondPago($nroPedido$cond)
    {
        
$respuesta $this->getIdDetalleCondPago($nroPedido);

        if (
$respuesta->id_detalle_cond != null) {
            
$data = array(
                
'id_cond' => $cond,
            );
            
$this->db->where('id_detalle_cond'$respuesta->id_detalle_cond);
            
$this->db->update('detalle_cond_pago'$data);

        } else {
            
$data = array(
                
'id_cond'   => $cond,
                
'id_pedido' => $nroPedido,

            );
            
$this->db->insert('detalle_cond_pago'$data);
        }
    }

    public function 
registrarCheckPago($nroPedido$check)
    {
        
$respuesta $this->getIdDetalleCheckPago($nroPedido);
        if (
$respuesta->id_detalle_check != null) {
            
$data = array(
                
'id_check' => $check,
            );
            
$this->db->where('id_detalle_check'$respuesta->id_detalle_check);
            
$this->db->update('detalle_check_pago'$data);

        } else {
            
$data = array(
                
'id_check'  => $check,
                
'id_pedido' => $nroPedido,

            );
            
$this->db->insert('detalle_check_pago'$data);
        }
    }

    public function 
getVendedoresTotalesAajax()
    {
        
$query $this->db->get('vendedores');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['name'] = $r->nombre;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getPagosAajax()
    {

        
$this->db->join('tipo_pago ''tipo_pago.id_pago = pago_pedido.id_tipo_pago''left');
        
$this->db->order_by("fechaPago""desc");
        
$query $this->db->get('pago_pedido');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']        = $r->id;
            
$arr[$i]['id_pedido'] = $r->id_pedido;
            
$arr[$i]['datoPago']  = $r->datoPago;
            
$arr[$i]['valor']     = $r->valor;

            
$arr[$i]['saldo']     = $r->saldo_pago;
            
$fechaReal            explode(" "$r->fechaPago);
            
$fecha                $fechaReal[0];
            
$fecha                date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fechaPago'] = $fecha;
            
$arr[$i]['recibo']    = $r->recibo;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getDetallesByidAjaxDepo($nro)
    {
        {

            
$consulta "select b.nombre as nombre, b.descripcion as descripcion,a.cantidad as cantidad,
                        a.id as id, a.precio as precio,c.estado as estado from detalle_pedido a

                        left join productos b on b.nombre=a.nombre_producto
                        left join estado_productos c on b.id_estado=c.id
                        where a.id_pedido= " 
$nro "
                        order by 1 asc"
;

            
$query $this->db->query($consulta);
            
$i     0;
            
$arr   = array();
            foreach (
$query->result() as $r) {
                
$arr[$i]['nombre']      = $r->nombre;
                
$arr[$i]['descripcion'] = $r->descripcion;
                
$arr[$i]['cantidad']    = $r->cantidad;
                
$arr[$i]['id']          = $r->id;
                
$arr[$i]['precio']      = $r->precio;
                
$arr[$i]['estado']      = $r->estado;
                
$i++;
            }
            
# JSON-encode the response
            
$json_response json_encode($arr);

            
// # Return the response
            
echo $json_response;

        }

    }

    public function 
getSeguimiento()
    {
        
$consulta "select b.id_pedido as pedido,a.nombre_producto as nombre,d.estado as estado,sum(a.cantidad) as cantidad, c.razon_social as cliente,b.fecha as fecha,b.vendedor as vendedor from detalle_pedido a left join pedidos b ON b.id_pedido=a.id_pedido left join clientes c ON c.id=b.id_cliente left join estado_pedidos d ON d.id=b.id_estado where a.cantidad>'0' and b.fecha > '2017-03-01' group by 1,2 order by 6 desc;";
        
$query    $this->db->query($consulta);
        
$i        0;
        
$arr      = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido'] = $r->pedido;
            
$arr[$i]['articulo']  = $r->nombre;
            
$arr[$i]['cantidad']  = $r->cantidad;
            
$arr[$i]['estado']    = $r->estado;
            
$arr[$i]['cliente']   = $r->cliente;
            
$fechaReal            explode(" "$r->fecha);
            
$fecha                $fechaReal[0];
            
$fecha                date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']     = $fecha;
            
$arr[$i]['vendedor']  = $r->vendedor;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getPedidosFinalizadosAajax()
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"10");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosFinalizadosClientesAajax($id)
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"10");
        
$this->db->where('id_cliente'$id);
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getOrdenesQueryAajax()
    {
        
$cotizador $this->session->userdata('username');
        
$consulta  "select * from impresiones";
        
$query     $this->db->query($consulta);
        
$i         0;
        
$arr       = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_impresion'] = $r->id_impresion;
            
$arr[$i]['usuario']      = $r->usuario;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosQueryExternoAajax()
    {
        
$cotizador $this->session->userdata('username');
        
$consulta  "select *,g.id as id_cliente,a.id_pedido as nro_pedido
                from pedidos a
                left join clientes g on a.id_cliente = g.id

                left join estado_pedidos d on d.id=a.id_estado
                left join detalle_check_pago e on e.id_pedido=a.id_pedido
                left join check_pago f on f.id_check=e.id_check
                left join detalle_medio_pago h on h.id_pedido=a.id_pedido
                left join medios_pago i on i.id_medio=h.id_pago
                where a.id_estado not in (3,16,17) and a.fecha>'2017-03-01'
                and a.vendedor='" 
$cotizador "' order by nro_pedido desc";
        
$query $this->db->query($consulta);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->nro_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['pagado']       = $r->pagado;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['medio']        = $r->medio;
            
$arr[$i]['id_cliente']   = $r->id_cliente;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosQueryAajax()
    {
        
/*    $this->db->join('estado_pedidos ', 'pedidos.id_estado = estado_pedidos.id','left');
        $this->db->join('detalle_check_pago ', 'pedidos.id_pedido = detalle_check_pago.id_pedido','left');
        $this->db->join('check_pago ', 'detalle_check_pago.id_check = check_pago.id_check','left');
        $this->db->join('detalle_medio_pago ', 'pedidos.id_pedido = detalle_medio_pago.id_pedido','left');
        $this->db->join('medios_pago ', 'detalle_medio_pago.id_pago = medios_pago.id_medio','left');
        $this->db->join('clientes ', 'pedidos.id_cliente = clientes.id','left');
        //descarto pedidos borrados
        $this->db->where('pedidos.id_estado !=','3');
        $this->db->order_by("fecha","desc");
        $query = $this->db->get('pedidos');
         */

        /*
        consulta que traia los tipos y formas de pago actualizada para traer mas datos en mayo del 2022

        $query = $this->db->query('select a.vendedor as vendedor ,a.fecha as fecha,g.razon_social as razon_social, a.descuento as descuento, a.subtotal as subtotal, a.total as total,
        i.medio as medio,f.pagado as pagado,d.estado as estado,  g.id as id_cliente,a.saldo as saldo, a.id_pedido as nro_pedido
        from pedidos a
        left join clientes g on a.id_cliente = g.id

        left join estado_pedidos d on d.id=a.id_estado
        left join detalle_check_pago e on e.id_pedido=a.id_pedido
        left join check_pago f on f.id_check=e.id_check
        left join detalle_medio_pago h on h.id_pedido=a.id_pedido
        left join medios_pago i on i.id_medio=h.id_pago
        where a.id_estado not in (3,16,17,10) and a.fecha>"2020-09-01"
        order by nro_pedido desc');

         */

        
$query $this->db->query('select a.vendedor as vendedor ,a.fecha as fecha,g.razon_social as razon_social, a.descuento as descuento, a.subtotal as subtotal, a.total as total,d.estado as estado,  g.id as id_cliente,a.saldo as saldo, a.id_pedido as nro_pedido
                from pedidos a
                left join clientes g on a.id_cliente = g.id
                left join estado_pedidos d on d.id=a.id_estado
                where a.id_estado not in (3,16,17) and a.fecha>"2020-09-01"
                order by nro_pedido desc'
);
/* query previo al cambio del php version 7

$query = $this->db->query('select *,g.id as id_cliente,a.id_pedido as nro_pedido
from pedidos a
left join clientes g on a.id_cliente = g.id

left join estado_pedidos d on d.id=a.id_estado
left join detalle_check_pago e on e.id_pedido=a.id_pedido
left join check_pago f on f.id_check=e.id_check
left join detalle_medio_pago h on h.id_pedido=a.id_pedido
left join medios_pago i on i.id_medio=h.id_pago
where a.id_estado not in (3,16,17) and a.fecha>"2020-03-01"
order by nro_pedido desc');
 */

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido'] = $r->nro_pedido;
            
$arr[$i]['vendedor']  = $r->vendedor;
            
$arr[$i]['pagado']    = $r->pagado;
            
$arr[$i]['estado']    = $r->estado;
            
//    $arr[$i]['id']=$r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['medio']        = $r->medio;
            
$arr[$i]['id_cliente']   = $r->id_cliente;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosAPrepararAajax()
    {

        
$query $this->db->query('select a.*,i.*,f.*,g.id as id_cliente_pedido, a.id_pedido as numero_pedido,g.razon_social as razon_social,d.estado as estado
               ,i.medio as medioPago,a.fecha as fechaPedido,f.pagado as pagado,max(c.fecha) as fechaConfirmacion
                from pedidos a left join clientes g on a.id_cliente = g.id
                left join auditoria c on a.id_pedido = c.id_pedido
                left join estado_pedidos d on d.id=a.id_estado left join detalle_check_pago e on e.id_pedido=a.id_pedido
                left join check_pago f on f.id_check=e.id_check left join detalle_medio_pago h on h.id_pedido=a.id_pedido
                left join medios_pago i on i.id_medio=h.id_pago where a.id_estado in (7,15,20,22)
                group by a.id_pedido,i.id_medio,f.id_check order by id_cliente_pedido,a.fecha desc
'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->numero_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id_cliente_pedido;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fechaPedido);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['pagado']       = $r->pagado;
            if (
$r->fechaConfirmacion != null) {
                
$fechaReal2                 explode(" "$r->fechaConfirmacion);
                
$fecha2                     $fechaReal2[0];
                
$fecha2                     date('d/m/Y'strtotime($fecha2));
                
$arr[$i]['fechaConfirmado'] = $fecha2;
            }
            
$arr[$i]['medio']     = $r->medioPago;
            
$arr[$i]['descuento'] = $r->descuento;
            
$arr[$i]['saldo']     = $r->saldo;
            
$arr[$i]['subtotal']  = number_format($r->subtotal0'''.');
            
$arr[$i]['total']     = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosAPendienteAajax()
    {

        
$query $this->db->query('select a.*,g.id as id_cliente_pedido, a.id_pedido as numero_pedido,a.fecha as fechaPedido,max(c.fecha) as fechaConfirmacion
                from pedidos a
                left join clientes g on a.id_cliente = g.id
                left join auditoria c on a.id_pedido = c.id_pedido
                left join estado_pedidos d on d.id=a.id_estado
                left join detalle_check_pago e on e.id_pedido=a.id_pedido
                left join check_pago f on f.id_check=e.id_check
                where a.id_estado in (15)
                group by a.id_pedido order by a.fecha desc'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->numero_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id_cliente_pedido;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fechaPedido);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['pagado']       = $r->pagado;
            if (
$r->fechaConfirmacion != null) {
                
$fechaReal2                 explode(" "$r->fechaConfirmacion);
                
$fecha2                     $fechaReal2[0];
                
$fecha2                     date('d/m/Y'strtotime($fecha2));
                
$arr[$i]['fechaConfirmado'] = $fecha2;
            }

            
$arr[$i]['descuento'] = $r->descuento;
            
$arr[$i]['saldo']     = $r->saldo;
            
$arr[$i]['subtotal']  = number_format($r->subtotal0'''.');
            
$arr[$i]['total']     = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosPreparadosAajax()
    {

        
$query $this->db->query('select a.*,a.id_pedido as numeroPedido,d.razon_social as razon_social,a.fecha as fechaPedido,max(c.fecha) as fechaArmado
                from pedidos a
                left join clientes d on a.id_cliente = d.id
                left join auditoria c on a.id_pedido = c.id_pedido
                where a.id_estado="9"
                group by a.id_pedido,d.id order by a.fecha desc'
);
        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->numeroPedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fechaPedido);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;

            
$fechaReal2             explode(" "$r->fechaArmado);
            
$fecha2                 $fechaReal2[0];
            
$fecha2                 date('d/m/Y'strtotime($fecha2));
            
$arr[$i]['fechaArmado'] = $fecha2;

            
$arr[$i]['descuento'] = $r->descuento;
            
$arr[$i]['saldo']     = $r->saldo;
            
$arr[$i]['subtotal']  = number_format($r->subtotal0'''.');
            
$arr[$i]['total']     = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosPendienteEntregaAajax()
    {

        
$query $this->db->query('select a.*,a.id_pedido as numeroPedido,a.fecha as fechaPedido,d.razon_social as razon_social,max(c.fecha) as fechaFacturado
                from pedidos a
                left join clientes d on a.id_cliente = d.id
                left join auditoria c on a.id_pedido = c.id_pedido
                where a.id_estado="13"
                group by a.id_pedido order by a.fecha desc'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->numeroPedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fechaPedido);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;

            
$fechaReal2                explode(" "$r->fechaFacturado);
            
$fecha2                    $fechaReal2[0];
            
$fecha2                    date('d/m/Y'strtotime($fecha2));
            
$arr[$i]['fechaFacturado'] = $fecha2;

            
$arr[$i]['descuento'] = $r->descuento;
            
$arr[$i]['saldo']     = $r->saldo;
            
$arr[$i]['subtotal']  = number_format($r->subtotal0'''.');
            
$arr[$i]['total']     = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getArticulosAlertaAjax()
    {
        
$query $this->db->query('select a.nombre as nombre,a.descripcion as descripcion,
                a.precio_venta as precio,c.estado as estado,b.stock as stock
                from productos a
                left join stock_productos b on b.nombre_producto=a.nombre
                left join estado_productos c on a.id_estado=c.id
                where b.stock<=0 and c.estado="CON STOCK" order by 5 desc'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']      = $r->nombre;
            
$arr[$i]['descripcion'] = $r->descripcion;
            
$arr[$i]['precio']      = $r->precio;
            
$arr[$i]['estado']      = $r->estado;
            
$arr[$i]['stock']       = $r->stock;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosFechaPuntual($fecha)
    {

        
$date   date_create($fecha);
        
$inicio date_format($date'Y-m-d ');

        
$this->db->where('fecha BETWEEN "' date('Y-m-d'strtotime($inicio)) . '" and "' date("Y-m-d"strtotime($inicio "+ 1 days")) . '"');

        
$query $this->db->get('pedidos');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getPagado($id_pedido)
    {
        
$this->db->where('id_pedido'$id_pedido);
        
$query $this->db->get('detalle_check_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getPedidosAutorizadosAajax()
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"5");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosEntregadosAajax()
    {

        
$query $this->db->query('select a.*,a.id_pedido as numeroPedido,d.razon_social as razon_social,a.fecha as fechaPedido,max(c.fecha) as fechaEntregado
                from pedidos a
                left join clientes d on a.id_cliente = d.id
                left join auditoria c on a.id_pedido = c.id_pedido
                where  a.id_estado="14"
                group by a.id_pedido order by a.fecha desc'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->numeroPedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fechaPedido);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;

            
$fechaReal2                explode(" "$r->fechaEntregado);
            
$fecha2                    $fechaReal2[0];
            
$fecha2                    date('d/m/Y'strtotime($fecha2));
            
$arr[$i]['fechaEntregado'] = $fecha2;

            
$arr[$i]['descuento'] = $r->descuento;
            
$arr[$i]['saldo']     = $r->saldo;
            
$arr[$i]['subtotal']  = number_format($r->subtotal0'''.');
            
$arr[$i]['total']     = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getEstadosTotalesPedidosAajax()
    {

        
$query $this->db->get('estado_pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']     = $r->id;
            
$arr[$i]['estado'] = $r->estado;

            
$i++;
        }
        return 
$arr;

    }
    public function 
getPedidosAuditoria()
    {

        
$query $this->db->query("select  PEDIDO as pedido,cliente as CLIENTE,vendedor as Vendedor,INICIO as inicio,total as TOTAL,  max(confirmador)  as confirmador,
max(fechaConfirmador) as fechaconfirmacion,max(preparador) as preparador,max(fechaPreparacion) as fechaPreparacion,
 max(facturador) as facturador,max(fechaFacturador) as fechaFacturador,
   max(entregador) as entregador,max(fechaEntregador) as fechaentregador,
max(finalizador) as finalizador,max(fechaFinalizador) as fechafinalizador
from (

  select a.id_pedido as PEDIDO,d.razon_social as CLIENTE,a.vendedor as Vendedor,a.fecha as INICIO,a.total as TOTAL,
  b.username as confirmador,b.fecha as fechaConfirmador,
  null as preparador,null as fechaPreparacion,
  null as facturador,null as fechaFacturador,
  null as entregador,null as fechaEntregador,
  null as finalizador,null as fechaFinalizador from pedidos a
  left join auditoria b ON b.id_pedido=a.id_pedido
  left join  estado_pedidos c on b.id_estado=c.id
  left join clientes d ON a.id_cliente=d.id
  where  c.id='7'

  UNION  select a.id_pedido as PEDIDO,d.razon_social as CLIENTE,a.vendedor as Vendedor,a.fecha as INICIO,a.total as TOTAL,
  null as confirmador,null as fechaConfirmador,
   b.username as preparador,b.fecha as fechaPreparacion,
     null as facturador,null as fechaFacturador,
   null as entregador,null as fechaEntregador,
   null as finalizador,null as fechaFinalizador from pedidos a
  left join auditoria b ON b.id_pedido=a.id_pedido
  left join  estado_pedidos c on b.id_estado=c.id
  left join clientes d ON a.id_cliente=d.id
  where    c.id='9'


  UNION select a.id_pedido as PEDIDO,d.razon_social as CLIENTE,a.vendedor as Vendedor,a.fecha as INICIO,a.total as TOTAL,
  null as confirmador,null as fechaConfirmador,
  null as preparador,null as  fechaPreparacion,
 b.username as facturador,b.fecha as fechaFacturador,
  null as entregador, null as fechaEntregador,
  null as finalizador,null as fechaFinalizador from pedidos a
  left join auditoria b ON b.id_pedido=a.id_pedido
  left join  estado_pedidos c on b.id_estado=c.id
  left join clientes d ON a.id_cliente=d.id
  where   c.id='13'

   UNION  select a.id_pedido as PEDIDO,d.razon_social as CLIENTE,a.vendedor as Vendedor,a.fecha as INICIO,a.total as TOTAL,
  null as confirmador,null as fechaConfirmador,
   null as preparador,null as  fechaPreparacion,
  null as facturador,null as fechaFacturador,
    b.username as entregador, b.fecha as fechaEntregador,
  null as finalizador,null as fechaFinalizador from pedidos a
  left join auditoria b ON b.id_pedido=a.id_pedido
  left join  estado_pedidos c on b.id_estado=c.id
  left join clientes d ON a.id_cliente=d.id
  where   c.id='14'

      UNION  select a.id_pedido as PEDIDO,d.razon_social as CLIENTE,a.vendedor as Vendedor,a.fecha as INICIO,a.total as TOTAL,
  null as confirmador,null as fechaConfirmador,
    null as preparador,null as  fechaPreparacion,
  null as facturador,null as fechaFacturador,
  null as entregador, null as fechaEntregador,
  b.username as finalizador,b.fecha as fechaFinalizador from pedidos a
  left join auditoria b ON b.id_pedido=a.id_pedido
  left join  estado_pedidos c on b.id_estado=c.id
  left join clientes d ON a.id_cliente=d.id
  where   c.id='10'

  )t
  group by 1
order by 1 desc;"
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']          = $r->pedido;
            
$arr[$i]['cliente']     = $r->CLIENTE;
            
$arr[$i]['vendedor']    = $r->Vendedor;
            
$fechaReal              explode(" "$r->inicio);
            
$fecha                  $fechaReal[0];
            
$fecha                  date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fechaPedido'] = $fecha;
            
$arr[$i]['total']       = $r->TOTAL;
            
$arr[$i]['confirma']    = $r->confirmador;
            if (
$r->fechaconfirmacion == null) {
                
$fecha null;
            } else {
                
$fechaReal explode(" "$r->fechaconfirmacion);
                
$fecha     $fechaReal[0];
                
$fecha     date('d/m/Y'strtotime($fecha));
            }
            
$arr[$i]['fechaConfirmacion'] = $fecha;

            
$arr[$i]['facturador'] = $r->facturador;

            if (
$r->fechaFacturador == null) {
                
$fecha null;
            } else {
                
$fechaReal explode(" "$r->fechaFacturador);
                
$fecha     $fechaReal[0];
                
$fecha     date('d/m/Y'strtotime($fecha));
            }
            
$arr[$i]['fechaFacturador'] = $fecha;

            
$arr[$i]['preparador'] = $r->preparador;

            if (
$r->fechaPreparacion == null) {
                
$fecha null;
            } else {
                
$fechaReal explode(" "$r->fechaPreparacion);
                
$fecha     $fechaReal[0];
                
$fecha     date('d/m/Y'strtotime($fecha));
            }
            
$arr[$i]['fechaPreparacion'] = $fecha;

            
$arr[$i]['finalizador'] = $r->finalizador;

            if (
$r->fechafinalizador == null) {
                
$fecha null;
            } else {
                
$fechaReal explode(" "$r->fechafinalizador);
                
$fecha     $fechaReal[0];
                
$fecha     date('d/m/Y'strtotime($fecha));
            }
            
$arr[$i]['fechaFinalizacion'] = $fecha;

            
$arr[$i]['entregador'] = $r->entregador;
            if (
$r->fechaentregador == null) {
                
$fecha null;
            } else {
                
$fechaReal explode(" "$r->fechaentregador);
                
$fecha     $fechaReal[0];
                
$fecha     date('d/m/Y'strtotime($fecha));
            }

            
$arr[$i]['fechaEntregador'] = $fecha;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getEstadosPedidosTotalesMartinAajax()
    {
        
$query $this->db->query("select * FROM estado_pedidos where id not in(0,3,4,5,6) order by 1 asc;");

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']     = $r->id;
            
$arr[$i]['estado'] = $r->estado;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getEstadosPedidosTotalesAajax()
    {

        
$query $this->db->get('estado_pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']     = $r->id;
            
$arr[$i]['estado'] = $r->estado;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getEstadosTotalesAajax()
    {

        
$query $this->db->get('estado_productos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']     = $r->id;
            
$arr[$i]['estado'] = $r->estado;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getCategorias()
    {

        
$query $this->db->get('categorias_productos');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getCategoriasAajax()
    {

        
$query $this->db->get('categorias_productos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id']        = $r->id;
            
$arr[$i]['categoria'] = $r->categoria;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getProductosTotalesAajax2()
    {

        
//      $this->db->join('estado_productos ', 'productos.id_estado = estado_productos.id','left');
        //     $this->db->order_by("fecha","desc");
        //    $this->db->where('id_estado', "1");
        
$query $this->db->get('productos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['name']         = $r->nombre;
            
$arr[$i]['description']  = $r->descripcion;
            
$arr[$i]['ordenamiento'] = $r->ordenamiento;
            
$arr[$i]['sale_price']   = $r->precio;
            
$arr[$i]['code']         = $r->numero;
            
$arr[$i]['state']        = $r->id_estado;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getPedidosVendedoresExternosAajaxAajax()
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"1");
        
$this->db->like('vendedor'$this->session->userdata('username'));
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }

        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosClientesExternosAajaxAajax($id_cliente)
    {

        
$consulta "select * from pedidos a left join estado_pedidos b on b.id=a.id_estado left join clientes c on c.id=a.id_cliente
                where a.id_cliente='" 
$id_cliente "' and a.id_estado not in (3,10) order by a.fecha desc";

        
$query $this->db->query($consulta);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            if (
$r->estado != 'BORRADO') {
                
$arr[$i]['id_pedido'] = $r->id_pedido;
                
$arr[$i]['vendedor']  = $r->vendedor;
                
$arr[$i]['cotizador'] = $r->cotizador;
                
$arr[$i]['id']        = $r->id;
                if (
$r->estado == "ACTIVO") {
                    
$arr[$i]['estado'] = "PENDIENTE APROBACION";
                } else {
                    
$arr[$i]['estado'] = $r->estado;
                }
                
$arr[$i]['razon_social'] = $r->razon_social;
                
$fechaReal               explode(" "$r->fecha);
                
$fecha                   $fechaReal[0];
                
$fecha                   date('d/m/Y'strtotime($fecha));
                
$arr[$i]['fecha']        = $fecha;
                
$arr[$i]['descuento']    = $r->descuento;
                
$arr[$i]['saldo']        = $r->saldo;
                
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
                
$arr[$i]['total']        = number_format($r->total0'''.');
                
$i++;
            }

        }

        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getProductosStockAajax()
    {

        
$query $this->db->query('select a.nombre as nombre,a.descripcion as descripcion,
                a.precio_venta as precio,c.estado as estado,b.stock as stock , d.categoria as categoria
                from productos a
                left join stock_productos b on b.nombre_producto=a.nombre
                left join estado_productos c on a.id_estado=c.id
                left join categorias_productos d on d.id=a.id_categoria
                group by 5 order by 1 asc'
);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']      = $r->nombre;
            
$arr[$i]['descripcion'] = $r->descripcion;
            
$arr[$i]['precio']      = $r->precio;
            
$arr[$i]['categoria']   = $r->categoria;
            
$arr[$i]['estado']      = $r->estado;
            
$arr[$i]['stock']       = $r->stock;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getRecibosBorradosAajax()
    {

        
$this->db->join('clientes ''recibos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('recibos.id_estado''2');
        
$query $this->db->get('recibos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$subParcial               "0";
            
$arr[$i]['id_recibo']     = $r->id_recibo;
            
$arr[$i]['pagador']       = $r->pagador;
            
$arr[$i]['numero_pedido'] = $r->numero_pedido;
            
$arr[$i]['vendedor']      = $r->vendedor;
            
$arr[$i]['razon_social']  = $r->razon_social;
            
$fechaReal                explode(" "$r->fecha);
            
$fecha                    $fechaReal[0];
            
$fecha                    date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']         = $fecha;

            
$arr[$i]['total'] = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }
    public function 
getRecibosTotalesAajax()
    {

        
$this->db->join('clientes ''recibos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('recibos.id_estado''1');
        
$query $this->db->get('recibos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$subParcial               "0";
            
$arr[$i]['id_recibo']     = $r->id_recibo;
            
$arr[$i]['pagador']       = $r->pagador;
            
$arr[$i]['numero_pedido'] = $r->numero_pedido;
            
$arr[$i]['vendedor']      = $r->vendedor;
            
$arr[$i]['razon_social']  = $r->razon_social;
            
$fechaReal                explode(" "$r->fecha);
            
$fecha                    $fechaReal[0];
            
$fecha                    date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']         = $fecha;

            
$arr[$i]['total'] = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getItemsOrdenImpresionAajax($id)
    {

        
$this->db->where('id_impresion'$id);
        
$query $this->db->get('detalle_impresion');
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre_producto'] = $r->nombre_producto;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosPuntualAajax($id)
    {

        
$this->db->join('clientes ''recibos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('numero_pedido'$id);
        
$this->db->where('id_estado''1');
        
$query $this->db->get('recibos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$subParcial               "0";
            
$arr[$i]['id_recibo']     = $r->id_recibo;
            
$arr[$i]['pagador']       = $r->pagador;
            
$arr[$i]['numero_pedido'] = $r->numero_pedido;
            
$arr[$i]['vendedor']      = $r->vendedor;
            
$arr[$i]['razon_social']  = $r->razon_social;
            
$fechaReal                explode(" "$r->fecha);
            
$fecha                    $fechaReal[0];
            
$fecha                    date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']         = $fecha;

            
$arr[$i]['total'] = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getOrdenesTiendaNubeTotalesAajax()
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"1");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$subParcial                   "0";
            
$arr[$i]['id_pedido']         = $r->id_pedido;
            
$arr[$i]['vendedor']          = $r->vendedor;
            
$arr[$i]['cotizador']         = $r->cotizador;
            
$arr[$i]['id']                = $r->id;
            
$arr[$i]['razon_social']      = $r->razon_social;
            
$fechaReal                    explode(" "$r->fecha);
            
$fecha                        $fechaReal[0];
            
$fecha                        date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']             = $fecha;
            
$arr[$i]['descuento']         = $r->descuento;
            
$arr[$i]['saldo']             = $r->saldo;
            
$subParcial                   round($r->subtotal round($r->subtotal $r->descuento 1002), 2);
            
$arr[$i]['subtotalDescuento'] = number_format($subParcial0'''.');
            
$arr[$i]['subtotal']          = number_format($r->subtotal0'''.');
            
$arr[$i]['total']             = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosTotalesAajax()
    {

        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
$this->db->order_by("fecha""desc");
        
$this->db->where('id_estado'"1");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$subParcial                   "0";
            
$arr[$i]['id_pedido']         = $r->id_pedido;
            
$arr[$i]['vendedor']          = $r->vendedor;
            
$arr[$i]['cotizador']         = $r->cotizador;
            
$arr[$i]['id']                = $r->id;
            
$arr[$i]['razon_social']      = $r->razon_social;
            
$fechaReal                    explode(" "$r->fecha);
            
$fecha                        $fechaReal[0];
            
$fecha                        date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']             = $fecha;
            
$arr[$i]['descuento']         = $r->descuento;
            
$arr[$i]['saldo']             = $r->saldo;
            
$subParcial                   round($r->subtotal round($r->subtotal $r->descuento 1002), 2);
            
$arr[$i]['subtotalDescuento'] = number_format($subParcial0'''.');
            
$arr[$i]['subtotal']          = number_format($r->subtotal0'''.');
            
$arr[$i]['total']             = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getUsuariosAajax()
    {
        
$this->db->order_by("id""desc");
        
$query $this->db->get('tbl_usrs');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre'] = $r->username;
            
$arr[$i]['perfil'] = $r->perfil;
            
$arr[$i]['clave']  = $r->password;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosEliminadosAajax()
    {
        
$this->db->join('estado_pedidos ''pedidos.id_estado = estado_pedidos.id''left');
        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
//descarto pedidos borrados
        
$this->db->where('pedidos.id_estado''3');
        
$this->db->order_by("fecha""desc");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosPagadosAajax()
    {
        
$consulta "select a.id_pedido as id_pedido,c.razon_social as cliente,a.id_cliente as id_cliente,a.fecha as fecha,
                round(sum(b.valor),2) as pagado, round((a.total-round(sum(b.valor),2)),2) as adeudado,
                 b.fechaPago as fecha_pago,a.subtotal as subtotal,a.total as total
                from pedidos a left join detalle_recibo b on b.id_pedido=a.id_pedido
                left join clientes c on c.id=a.id_cliente

 where a.id_estado='1' and b.valor!=''
                group by 1 order by fecha_pago asc;"
;
        
$query $this->db->query($consulta);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['cliente']      = $r->cliente;
            
$arr[$i]['id_cliente']   = $r->id_cliente;
            
$arr[$i]['subtotal']     = $r->subtotal;
            
$arr[$i]['total']        = $r->total;
            
$arr[$i]['condicion']    = $r->medio;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha_pedido'] = $fecha;
            
$fechaReal               explode(" "$r->fecha_pago);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha_pago']   = $fecha;

            
$arr[$i]['adeudado'] = number_format($r->adeudado0'''.');
            
$arr[$i]['pagado']   = number_format($r->pagado0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getPedidosDesarmadosAajax()
    {
        
$this->db->join('estado_pedidos ''pedidos.id_estado = estado_pedidos.id''left');
        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
//descarto pedidos borrados
        
$this->db->where('pedidos.id_estado''21');
        
$this->db->order_by("fecha""desc");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosStandByAajax()
    {
        
$this->db->join('estado_pedidos ''pedidos.id_estado = estado_pedidos.id''left');
        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
//descarto pedidos borrados
        
$this->db->where('pedidos.id_estado''19');
        
$this->db->order_by("fecha""desc");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosStandByFeriaAajax()
    {
        
$this->db->join('estado_pedidos ''pedidos.id_estado = estado_pedidos.id''left');
        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
// me traigo los pedidos en estado =>'STAND BY FERIA'
        
$this->db->where('pedidos.id_estado''23');
        
$this->db->order_by("fecha""desc");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getPedidosEliminadosClientesAajax($id)
    {
        
$this->db->join('estado_pedidos ''pedidos.id_estado = estado_pedidos.id''left');
        
$this->db->join('clientes ''pedidos.id_cliente = clientes.id''left');
        
//descarto pedidos borrados
        
$this->db->where('pedidos.id_estado''3');
        
$this->db->where('pedidos.id_cliente'$id);
        
$this->db->where('pedidos.cotizador'"AUTO_PEDIDO");
        
$this->db->order_by("fecha""desc");
        
$query $this->db->get('pedidos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_pedido']    = $r->id_pedido;
            
$arr[$i]['vendedor']     = $r->vendedor;
            
$arr[$i]['cotizador']    = $r->cotizador;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['id']           = $r->id;
            
$arr[$i]['razon_social'] = $r->razon_social;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['descuento']    = $r->descuento;
            
$arr[$i]['saldo']        = $r->saldo;
            
$arr[$i]['subtotal']     = number_format($r->subtotal0'''.');
            
$arr[$i]['total']        = number_format($r->total0'''.');
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
getProductosTotalesAajax()
    {
        
$query $this->db->get('productos');

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']      = $r->nombre;
            
$arr[$i]['descripcion'] = $r->descripcion;
            
$arr[$i]['precio']      = $r->precio;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
productosAbmSearch($buscador)
    {

        
$this->db->select('nombre');
        
$this->db->like('nombre'$buscador'after');
        
$resultados $this->db->get('productos'12);
        
//si existe algún resultado lo devolvemos
        
if ($resultados->num_rows() > 0) {
            foreach (
$resultados->result_array() as $row) {
                
$data[] = array("nombre" => $row['nombre']);
            }
            echo 
json_encode($data);

            
//en otro caso devolvemos false
        
} else {

            echo 
"No encontrado";

        }
    }

    public function 
productosSinPag($buscador)
    {

        
$this->db->select('nombre');
        
$this->db->like('nombre'$buscador'after');
        
$resultados $this->db->get('productos'12);
        
//si existe algún resultado lo devolvemos
        
if ($resultados->num_rows() > 0) {
            foreach (
$resultados->result_array() as $row) {
                
$row_set[] = htmlentities(stripslashes($row['nombre'])); //build an array
            
}
            echo 
json_encode($row_set);

            
//en otro caso devolvemos false
        
} else {

            echo 
"No encontrado";

        }
    }

    public function 
getCodigos($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('productos'$num$offset);
        return 
$query->result();
    }
    public function 
getDatosBultos($pedido)
    {
        
$query $this->db->get_where('bultos', array('id_pedido' => $pedido));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }
    }

    public function 
getSaldo($id)
    {
        
$query $this->db->get_where('saldos', array('id_cliente' => $id));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        } else {
            
$data = array(
                
'id_cliente'  => $id,
                
'valor_saldo' => '0',
            );
            
$this->db->insert('saldos'$data);
        }
    }

    public function 
getSaldoProveedor($id)
    {
        
$query $this->db->get_where('saldosProv', array('id_proveedor' => $id));
        if (
$query->num_rows() > 0) {
            return 
$query->row();
        } else {
            
$data = array(
                
'id_proveedor' => $id,
                
'valor_saldo'  => '0',
            );
            
$this->db->insert('saldosProv'$data);
        }
    }

    public function 
getVendedores()
    {
        
$query $this->db->query("select nombre FROM vendedores");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_Cantidad_clientes()
    {
        
$query $this->db->query("SELECT count(*) as cant FROM clientes");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
consulta_cantidad_pedidos()
    {
        
$query $this->db->query("SELECT count(*) as cant FROM pedidos");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
consulta_Cantidad_clientesA()
    {
        
$query $this->db->query("SELECT count(*) as cant FROM clientes where iva='Resp Inscripto'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
deleteProducto($producto)
    {
        
$this->db->delete('productos', array('nombre' => $producto->nombre));
        if (
$this->db->_error_message()) {
            
$result 'Error! [' $this->db->_error_message() . ']';
        } else if (!
$this->db->affected_rows()) {
            
$result 'Error! ID [' $id '] not found';
        } else {
            
$result 'Success';
        }
    }

    public function 
getCheck()
    {
        
$query $this->db->query("select pagado FROM check_pago");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getArrayCheck()
    {
        
$query $this->db->query("select * FROM check_pago");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
updateStockAbm($articulo$stock)
    {
        
$data = array(
            
'stock' => $stock,
        );
        
$this->db->where('nombre_producto'$articulo);
        
$this->db->update('stock_productos'$data);
    }
    public function 
updateProducto($producto)
    {
        
$data = array(
            
'descripcion'  => $producto->descripcion,
            
'precio'       => $producto->precio,
            
'precio_venta' => $producto->precio,
            
'numero'       => $producto->numero,
        );
        
$this->db->where('nombre'$producto->nombre);
        
$this->db->update('productos'$data);
    }
    public function 
getStock($producto)
    {
        
$this->db->where('nombre_producto'$producto);
        
$query     $this->db->get('stock_productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            return 
$respuesta $query->row()->stock;
        }
    }

    public function 
updateStock($producto$cantidad)
    {
        
$cantidadAgregada null;
        
$cantidadAgregada $this->getStock($producto);
        if (
$cantidadAgregada != null) {
            
$cantidadAgregada = ($cantidadAgregada $cantidad);
            
$data             = array(
                
'stock' => $cantidadAgregada,
            );
            
$this->db->where('nombre_producto'$producto);
            
$this->db->update('stock_productos'$data);
        }

    }
    public function 
updateStockEliminando($producto$cantidad)
    {
        
$cantidadAgregada null;
        
$cantidadAgregada $this->getStock($producto);
        if (
$cantidadAgregada != null) {
            
$cantidadAgregada = ($cantidadAgregada $cantidad);
            
$data             = array(
                
'stock' => $cantidadAgregada,
            );
            
$this->db->where('nombre_producto'$producto);
            
$this->db->update('stock_productos'$data);
        }

    }

    public function 
registrarComentario($nroPedido$comentario)
    {
        
$data = array(
            
'observacion' => $comentario,
            
'fecha'       => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
cambiarEstadoPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "2",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
borrarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "3",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
borrarRecibo($nroPedido)
    {
        
$data = array(
            
'id_estado' => "2",
            
'fecha'     => $this->getFechaRecibo($nroPedido),
        );
        
$this->db->where('id_recibo'$nroPedido);
        
$this->db->update('recibos'$data);
    }

    public function 
standBy($nroPedido)
    {
        
$data = array(
            
'id_estado' => "19",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
restaurarPedidoCliente($nroPedido)
    {
        
$data = array(
            
'id_estado' => "17",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
restaurarRecibo($nroPedido)
    {
        
$data = array(
            
'id_estado' => "1",
            
'fecha'     => $this->getFechaRecibo($nroPedido),
        );
        
$this->db->where('id_recibo'$nroPedido);
        
$this->db->update('recibos'$data);
    }
    public function 
recotizarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "1",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
pasarPedidoPreparacionTramite($nroPedido)
    {
        
$data = array(
            
'id_estado' => "20",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
pasarPedidoPendienteImpreso($nroPedido)
    {
        
$data = array(
            
'id_estado' => '22',
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }
    public function 
pendienteEnvioCliente($nroPedido)
    {
        
$data = array(
            
'id_estado' => "13",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
finalizarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "10",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
entregarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "14",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }
    public function 
autorizarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "7",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
cambiarEstadoPedidoMartin($nroPedido$estado)
    {
        
$data = array(
            
'id_estado' => $estado,
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }
    public function 
envioAFacturacion($nroPedido)
    {
        
$data = array(
            
'id_estado' => "9",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
confirmarPedido($nroPedido)
    {
        
$data = array(
            
'id_estado' => "5",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
confirmarPedidoCliente($nroPedido)
    {
        
$data = array(
            
'id_estado' => "1",
            
'fecha'     => $this->getFecha($nroPedido),
        );
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->update('pedidos'$data);
    }
    public function 
consulta_Cantidad_proveedores()
    {
        return 
$this->db->count_all('proveedores');
    }

    public function 
consulta_Cantidad_Transferencias()
    {
        return 
$this->db->count_all('transferencia');
    }

    public function 
consulta_Cantidad_Cheques()
    {
        return 
$this->db->count_all('cheques');
    }

    public function 
consulta_Cantidad_frasCompras($buscaProv$filtroTipo$fechaInicio$fechaFinal)
    {
        
$consulta "select sum(total) as valor from compras ";
        if ((
$fechaInicio != null) || ($fechaFinal != null) || ($buscaProv != null)) {
            
$consulta .= " where ";
            
$habia "";
            if ((
$fechaInicio != null) && ($fechaFinal != null)) {
                
$habia "1";
                
$consulta .= " fechaFactura >= '" $fechaInicio "' and fechaFactura <= '" $fechaFinal "'";
            }

            if (
$buscaProv != null) {
                if (
$habia == "") {
                    
$consulta .= " id_proveedor= '" $buscaProv "'";
                } else {
                    
$consulta .= " and id_proveedor= '" $buscaProv "'";
                }
            }
        }
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdClientePedido($id)
    {
        
$this->db->where("id_pedido"$id);
        
$query $this->db->get('pedidos');
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->id_cliente;
        }
    }

    public function 
getIdMedioPago($desc)
    {
        
$this->db->like("medio"$desc);
        
$query $this->db->get('medios_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdCondPago($desc)
    {
        
$this->db->like("condicion"$desc);
        
$query $this->db->get('cond_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdcheckPago($desc)
    {
        
$this->db->like("pagado"$desc);
        
$query $this->db->get('check_pago');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoCreditoByDesc($desc)
    {
        
$this->db->like("descripcion"$desc);
        
$query $this->db->get('tipocredito');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_Cantidad_Retenciones($tipo$buscador)
    {
        
$this->db->like($tipo$buscador);
        return 
$this->db->count_all('retenciones');
    }

    public function 
consulta_cantidad_registros($id)
    {
        
$query $this->db->query("select count(id) as cantidad from detalle_movimiento where id_cliente='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_cantidad_registrosProv($id)
    {
        
$query $this->db->query("select count(id) as cantidad from detalle_movimiento_proveedores where id_proveedor='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_Cantidad_movimientos($cliente)
    {
        
$query $this->db->query("SELECT count(*) as cant FROM detalle_movimiento where id_cliente='" $cliente "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getRemitoByOC($nroOrden)
    {
        
$query $this->db->query("select nro_remito from remito where nro_orden='" $nroOrden "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getNroOrdenByOT($nroOrden)
    {
        
$query $this->db->query("select nro_oc from ordentrabajo where nro_ot='" $nroOrden "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getNextFactura()
    {
        
$query $this->db->query("SELECT MAX(id_factura)+1 as cant FROM factura");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getNextFacturaB()
    {
        
$query $this->db->query("SELECT MAX(id_factura)+1 as cant FROM facturaB");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getNextRemito()
    {
        
$query $this->db->query("SELECT MAX(nro_remito)+1 as cant FROM remito");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getClientebyId($id)
    {
        
$query $this->db->query("SELECT nombre from clientes where id='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProveedores()
    {
        
$query $this->db->get('proveedores');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoCompra()
    {
        
$query $this->db->get('tipoCompra');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoRetByName($name)
    {
        
$this->db->like('descripcion'$name);
        
$query $this->db->get('tiporetencion');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    
/*   public function getTotal($factura,$cliente)
    {
    $query =$this->db->query("SELECT total FROM totales where nroFactura='".$factura. "' and id_cliente='".$cliente."';");
    if($query->num_rows() > 0 )
    {
    return $query->result();
    }

    }*/

    
public function getPedidoAbierto($usuario)
    {
        
$query $this->db->query("SELECT id_pedido,id_cliente FROM pedidos where id_estado='4' and vendedor='" $usuario "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getPedidoAbiertoCliente($usuario)
    {
        
$query $this->db->query("SELECT id_pedido,id_cliente FROM pedidos where id_estado='16' and id_cliente='" $usuario "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getNextRecibo()
    {
        
$query $this->db->query("SELECT MAX(nro_recibo)+1 as cant FROM recibo");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getLastFactura()
    {
        
$query $this->db->query("SELECT MAX(id_factura) as cant FROM factura");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getLastFacturaB()
    {
        
$query $this->db->query("SELECT MAX(id_factura) as cant FROM facturaB");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoRetencion()
    {

        
$query $this->db->query("SELECT id,descripcion FROM tipoRetencion");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoCredito()
    {

        
$query $this->db->query("SELECT id,descripcion FROM tipocredito");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getLastCreditoB()
    {

        
$query $this->db->query("SELECT MAX(nro_nota_credito) as cant FROM notaCreditoB");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getLastCredito()
    {

        
$query $this->db->query("SELECT MAX(nro_nota_credito) as cant FROM notaCredito");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getDisponible($nroOrdenCompra$idProducto)
    {
        
$query $this->db->query("select cant_disponible from detalle_oc where id_OC='" $nroOrdenCompra "' and id_producto='" $idProducto "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
actualizarCantidadOC($nroOrdenCompra$idProducto$cantidad)
    {

        
$cantidadAnterior $this->getDisponible($nroOrdenCompra$idProducto);
        
$cant             $cantidadAnterior[0]->cant_disponible $cantidad;

        
$data = array(
            
'cant_disponible' => $cant,
        );

        
$this->db->where('id_OC'$nroOrdenCompra);
        
$this->db->where('id_producto'$idProducto);

        
$this->db->update('detalle_oc'$data);
    }

    public function 
consulta_Cantidad_clientes_B()
    {
        
$query $this->db->query("SELECT count(*) as cant FROM clientes where iva='Monotributista'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }

    }

    public function 
cancelarFactura($nro)
    {
        
$data = array(
            
'id_estado' => '3',
        );

        
$this->db->where('nro_factura'$nro);
        
$this->db->update('factura'$data);
    }

    public function 
getAcumuladoPago($numeroPedido)
    {
        
$query $this->db->query("SELECT sum(valor) as suma FROM pago_pedido where id_pedido ='" $numeroPedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->suma;
        }
    }

    public function 
getSaldos($nropedido)
    {
        
$query $this->db->query("SELECT saldo FROM pedidos where id_pedido ='" $nropedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->saldo;
        }

    }

    public function 
getFecha($nropedido)
    {
        
$query $this->db->query("SELECT fecha FROM pedidos where id_pedido ='" $nropedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->fecha;
        }

    }

    public function 
getFechaRecibo($nropedido)
    {
        
$query $this->db->query("SELECT fecha FROM recibos where id_recibo ='" $nropedido "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->fecha;
        }

    }

    
//actualizo el pedido nuevo desglozado
    
public function actualizarPedidoNuevo($nroPEdido$subtotal$total)
    {
        
$data = array(
            
'fecha'    => $this->getFecha($nroPEdido),
            
'subtotal' => $subtotal,
            
'total'    => $total,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);

    }

    
//actualizo el total y subtotal del pedido viejo
    
public function actualizarPedidoViejo($nroPEdido$subtotal$total)
    {
        
$data = array(
            
'fecha'    => $this->getFecha($nroPEdido),
            
'subtotal' => $subtotal,
            
'total'    => $total,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
    }

    public function 
actualizarPedidoDepo($nroPEdido$subtotal$total$vendedor$cotizador)
    {
        
$data = array(
            
'fecha'     => $this->getFecha($nroPEdido),
            
'vendedor'  => $vendedor,
            
'cotizador' => $cotizador,
            
'subtotal'  => $subtotal,
            
'total'     => $total,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
    }

    public function 
registrarSaldo($nroPEdido$saldo)
    {
        
$data = array(
            
'fecha' => $this->getFecha($nroPEdido),
            
'saldo' => $saldo,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
    }

    public function 
agotarArticulo($articulo)
    {
        
$data = array(
            
'id_estado' => '1',
        );

        
$this->db->where('nombre'$articulo);
        
$this->db->update('productos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
actualizarPedido($nroPEdido$subtotal$total$vendedor$cotizador)
    {
        
$data = array(
            
'id_estado' => '1',
            
'fecha'     => $this->getFecha($nroPEdido),
            
'vendedor'  => $vendedor,
            
'cotizador' => $cotizador,
            
'subtotal'  => $subtotal,
            
'total'     => $total,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
        return 
$this->db->affected_rows();
    }

    public function 
actualizarPedidoIva($nroPEdido$iva$subtotal$total$cotizador)
    {
        
$data = array(
            
'fecha'     => $this->getFecha($nroPEdido),
            
'cotizador' => $cotizador,
            
'subtotal'  => $subtotal,
            
'total'     => $total,
            
'iva'       => $iva,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
    }

    public function 
sumarStockPedido($id_pedido)
    {
        
$consulta "UPDATE stock_productos t2,
            (
            select nombre_producto as NOMBRE,cantidad as CANTIDAD
             from detalle_pedido where id_pedido='" 
$id_pedido "' )t1
            SET t2.stock = (t2.stock + t1.CANTIDAD)
            WHERE t1.NOMBRE = t2.nombre_producto;
            "
;
        
$query $this->db->query($consulta);

    }

    public function 
restarStockPedido($id_pedido)
    {
        
$consulta "UPDATE stock_productos t2,
            (
            select nombre_producto as NOMBRE,cantidad as CANTIDAD
             from detalle_pedido where id_pedido='" 
$id_pedido "' )t1
            SET t2.stock = (t2.stock - t1.CANTIDAD)
            WHERE t1.NOMBRE = t2.nombre_producto;
            "
;
        
$query $this->db->query($consulta);
    }

    public function 
actualizarPedidoClientes($nroPEdido$subtotal$total$vendedor$cotizador)
    {
        
$data = array(
            
'id_estado' => '17',
            
'fecha'     => $this->getFecha($nroPEdido),
            
'vendedor'  => $vendedor,
            
'cotizador' => "AUTO_PEDIDO",
            
'subtotal'  => $subtotal,
            
'total'     => $total,
        );

        
$this->db->where('id_pedido'$nroPEdido);
        
$this->db->update('pedidos'$data);
    }

    public function 
actualizarPago($id$datoPago$valor$saldo)
    {
        
$data = array(
            
'datoPago'   => $datoPago,
            
'valor'      => $valor,
            
'saldo_pago' => $saldo,
        );

        
$this->db->where('id'$id);
        
$this->db->update('pago_pedido'$data);
    }

    public function 
actualizarEstadoOR($nro$estado)
    {
        
$data = array(
            
'id_estado' => $estado,
        );

        
$this->db->where('nro_ot'$nro);
        
$this->db->update('ordentrabajo'$data);
    }

    public function 
getNextCredito()
    {
        
$query $this->db->query("SELECT MAX(nro_nota_credito)+1 as cant FROM notaCredito");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
registrarPagoParcialRemito($remito$monto)
    {
        
$data = array(
            
'monto_acumulado' => $monto,
        );

        
$this->db->where('nro_remito'$remito);
        
$this->db->update('remito'$data);
    }

    public function 
registrarPagoParcial($factura$monto)
    {
        
$data = array(
            
'monto_acumulado' => $monto,
        );

        
$this->db->where('nro_factura'$factura);
        
$this->db->update('factura'$data);
    }

    public function 
cambiarEstadoFactura($factura$tipoNuevo)
    {
        
$data = array(
            
'id_estado' => $tipoNuevo,
        );

        
$this->db->where('nro_factura'$factura);
        
$this->db->update('factura'$data);
    }

    public function 
cambiarEstadoRemito($remito$tipoNuevo)
    {
        
$data = array(
            
'id_estado' => $tipoNuevo,
        );

        
$this->db->where('nro_remito'$factura);
        
$this->db->update('remito'$data);
    }

    
/*  public function actualizarTotal($nroFactura,$suma,$cliente,$operacion)
    {
    $totalAnterior=$this->getTotal($nroFactura,$cliente);
    if($totalAnterior!=null){
    if($operacion=='1'){
    $totalActual=($totalAnterior[0]->total + $suma);
    }
    else{
    $totalActual=($totalAnterior[0]->total - $suma);
    }

    $data = array(
    'nroFactura' => $nroFactura,
    'total' => $totalActual,
    'id_cliente' => $cliente
    );
    $this->db->where('nroFactura', $nroFactura);
    $this->db->where('id_cliente', $cliente);
    $this->db->update('totales', $data);
    }
    else{

    $data = array(
    'nroFactura' => $nroFactura,
    'total'=>$suma,
    'id_cliente' => $cliente
    );
    $this->db->insert('totales',$data);
    }

    }*/

    
public function registrarAuditoria($pedido$estado$usuario)
    {
        
$data = array(
            
'id_pedido' => $pedido,
            
'fecha'     => date('Y-m-d H:i:s'),
            
'username'  => $usuario,
            
'id_estado' => $estado,
        );
        
$this->db->insert('auditoria'$data);
    }

    
//duplico pedidos con ids distintos en depo
    
public function duplicarPedido($datos$cotizador)
    {
        
$cotiz 0;

        if (
$cotizador != null) {
            
$cotiz $cotizador;
        } else {
            
$cotiz $datos->cotizador;
        }

        
$data = array(
            
'id_estado'   => '15',
            
'fecha'       => $datos->fecha,
            
'id_cliente'  => $datos->id_cliente,
            
'total'       => $datos->total,
            
'iva'         => $datos->iva,
            
'descuento'   => $datos->descuento,
            
'vendedor'    => $datos->vendedor,
            
'observacion' => $datos->observacion,
            
'subtotal'    => $datos->subtotal,
            
'saldo'       => $datos->saldo,
            
'pendiente'   => $datos->pendiente,
            
'cotizador'   => $cotiz,
        );
        
$this->db->insert('pedidos'$data);
        
$insert_id $this->db->insert_id();

        return 
$insert_id;
    }

    
//actualizo los registros con los nuevos pedidos.
    
public function actualizarRegistro($id$pedido)
    {
        
$data = array(
            
'id_pedido' => $pedido,
        );
        
$this->db->where('id'$id);
        
$this->db->update('detalle_pedido'$data);
        return 
$this->db->affected_rows();
    }

    public function 
crearNuevoRecibo($id_cliente$nro_pedido$vendedor$observacion$total$pagador)
    {
        
$sql "INSERT INTO recibos(id_cliente, id_estado,numero_pedido, fecha,vendedor,observacion,total,pagador) VALUES('" $id_cliente "','1','" $nro_pedido "',null,'" $vendedor "','" $observacion "','" $total "','" $pagador "')";

        if (
$this->db->query($sql)) {
            return 
$this->db->insert_id();
        } else {
            return 
false;
        }

    }

    public function 
getDatosRecibo($id_recibo)
    {

        
$query $this->db->query("SELECT * from recibos where id_recibo='" $id_recibo "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }

    public function 
getDetallesRecibo($id_recibo$id_pedido)
    {
        
$consulta "SELECT * from detalle_recibo where id_recibo='" $id_recibo "' and id_pedido='" $id_pedido "';";
        
$query    $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getClienteRecibo($id)
    {
        
$query $this->db->query("SELECT * from clientes where id='" $id "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
crearNuevoPedido($usuario)
    {
        
$data = array(
            
'id_estado'   => '4',
            
'fecha'       => date('Y-m-d H:i:s'),
            
'id_cliente'  => '0',
            
'total'       => '0',
            
'iva'         => '1.21',
            
'descuento'   => '0',
            
'vendedor'    => $usuario,
            
'observacion' => "",
            
'pendiente'   => '0',
            
'cotizador'   => $usuario,
        );
        
$this->db->insert('pedidos'$data);
    }

    public function 
crearNuevoPedidoCliente($usuario)
    {
        
$data = array(
            
'id_estado'   => '16',
            
'fecha'       => date('Y-m-d H:i:s'),
            
'id_cliente'  => $usuario,
            
'total'       => '0',
            
'iva'         => '0',
            
'descuento'   => '0',
            
'pendiente'   => '0',
            
'vendedor'    => "AUTO_PEDIDO",
            
'observacion' => "",
            
'cotizador'   => "AUTO_PEDIDO",
        );
        
$this->db->insert('pedidos'$data);
    }

    public function 
getMontoCheque($nroCheque)
    {
        
$query $this->db->query("select monto from cheques where nro_cheque='" $nroCheque "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0];
        }
    }

    public function 
getConfirmacionNro($cliente)
    {
        
$query $this->db->query("SELECT * FROM nrosoc where id_cliente='" $cliente "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0];
        }
    }

    public function 
crearRecibo($nroRecibo$cliente)
    {
        
$data = array(
            
'nro_recibo' => $nroRecibo,
            
'fecha'      => date('Y-m-d'),
            
'id_cliente' => $cliente,
            
'monto'      => '0',
            
'id_factura' => '0',
        );
        
$this->db->insert('recibo'$data);
    }

    
//consulta ventas
    
public function ventas($filtro$vendedor)
    {
        
$mesActual  date("m");
        
$añoActual date("Y");
        
$query      $this->db->query("SET lc_time_names = 'es_VE';");
        
$consulta   "select t.mes,CAST(t.mes2 AS UNSIGNED ) as mes2, round(sum(t.cant),2) as cant from (select DATE_FORMAT(a.fecha,'%M') as mes,DATE_FORMAT(a.fecha,'%c') as mes2, a.total as cant from pedidos a where a.id_estado not in ('3','15','22','19','4','17','22') and a.fecha BETWEEN  CAST('" $añoActual "/01/01' AS DATE) and  CAST('" $añoActual "/" $mesActual "/31' AS DATE) ";

        
//    $consulta .="union select DATE_FORMAT(b.fecha,'%M') as mes, b.total as cant from facturab b";
        //    $consulta .=" union select DATE_FORMAT(c.fecha,'%M') as mes, c.total as cant from remito c";

        
if ($filtro != null) {
            
$consulta .= " and a.id_cliente= '" $filtro "'";
        }

        if (
$vendedor != null) {
            
$consulta .= " and a.vendedor= '" $vendedor "'";
        }

        
$consulta .= ") as t ";

        
$consulta .= " group by t.mes order by t.mes2 ASC";

        
$query $this->db->query($consulta);
        
$datos = array();

        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $cant) {

                
$mes         $cant->mes;
                
$datos[$mes] = $cant->cant;
                
$total += $cant->cant;
            }

            
$i 0;
            foreach (
$datos as $mes => $cant) {
                
$vDatos[$i]["mes"]        = $mes;
                
$vDatos[$i]["porcentaje"] = number_format(($cant $total) * 1002);
                
$vDatos[$i]["cant"]       = $cant;
                
$i++;
            }
            return 
$vDatos;
        }
    }

    
//consulta ventas cantidades pedidos
    
public function ventasPedidosCantidades($filtro)
    {

        
$consulta " select count(a.id_pedido) as cant,id_estado as estado from pedidos a where id_estado ='" $filtro "'";

        
$query  $this->db->query($consulta);
        
$vDatos = array();
        
$i      0;
        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $cant) {

                
$vDatos[$i]["cant"] = $cant->cant;
                
$i++;
            }
            return 
$vDatos;
        }
    }

    
//consulta ventas Diarias
    
public function ventasMensual($filtro$vendedor)
    {
        
$mesActual  date("m");
        
$añoActual date("Y");
        
$query      $this->db->query("SET lc_time_names = 'es_VE';");
        
$consulta   "select DATE_FORMAT(a.fecha,'%d') as dia, round(sum(a.total),2) as cant from pedidos a  where a.id_estado='1' and a.fecha>' " "01/" $mesActual "/" $añoActual "' and a.fecha<='" "31/" $mesActual "/" $añoActual "'";

        
$consulta .= "group by 1 order by 1 asc";

        
$query $this->db->query($consulta);
        
$datos = array();

        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $cant) {

                
$mes         $cant->dia;
                
$datos[$mes] = $cant->cant;
                
$total += $cant->cant;
            }

            
$i 0;
            foreach (
$datos as $mes => $cant) {
                
$vDatos[$i]["dia"]        = $mes;
                
$vDatos[$i]["porcentaje"] = number_format(($cant $total) * 1002);
                
$vDatos[$i]["cant"]       = $cant;
                
$i++;
            }
            return 
$vDatos;
        }
    }

    
//consulta compras
    
public function compras($filtro)
    {

        
$query    $this->db->query("SET lc_time_names = 'es_VE';");
        
$consulta " select DATE_FORMAT(fechaFactura,'%M') as mes, sum(total) as cant from compras ";

        if (
$filtro != null) {
            
$consulta .= " where id_proveedor= '" $filtro "'";
        }

        
$consulta .= "group by 1 order by 1 desc";
        
$query $this->db->query($consulta);
        
$datos = array();

        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $cant) {

                
$mes         $cant->mes;
                
$datos[$mes] = $cant->cant;
                
$total += $cant->cant;
            }

            
$i 0;
            foreach (
$datos as $mes => $cant) {
                
$vDatos[$i]["mes"]        = $mes;
                
$vDatos[$i]["porcentaje"] = number_format(($cant $total) * 1002);
                
$vDatos[$i]["cant"]       = $cant;
                
$i++;
            }
            return 
$vDatos;
        }
    }

    public function 
cantidadPendientesRemito()
    {

        
$fechaInicial date('Y-m-d');
        
$fechaFinal   strtotime('-1 month'strtotime($fechaInicial));
        
$fechaFinal   date('Y-m-d'$fechaFinal);
        
$fechaFinal   "'" $fechaFinal "'";

        
$query $this->db->query("SELECT count(*) as cant FROM remito where id_estado='1' and fecha <= " $fechaFinal);

        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
cantidadPendientes()
    {

        
$fechaInicial date('Y-m-d');
        
$fechaFinal   strtotime('-1 month'strtotime($fechaInicial));
        
$fechaFinal   date('Y-m-d'$fechaFinal);
        
$fechaFinal   "'" $fechaFinal "'";

        
$query $this->db->query("SELECT count(*) as cant FROM factura where id_estado='1' and fecha <= " $fechaFinal);

        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
cantidadPendientesB()
    {

        
$fechaInicial date('Y-m-d');
        
$fechaFinal   strtotime('-1 month'strtotime($fechaInicial));
        
$fechaFinal   date('Y-m-d'$fechaFinal);
        
$fechaFinal   "'" $fechaFinal "'";

        
$query $this->db->query("SELECT count(*) as cant FROM facturab where id_estado='1' and fecha <= " $fechaFinal);

        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }
    }

    public function 
getProductosVenditos($filtro)
    {
        
$consulta "select sum(a.cantidad) as suma,b.nombre from detalle_pedido a left join productos b ON a.nombre_producto=b.nombre left join pedidos c ON c.id_pedido=a.id_pedido";

        if (
$filtro != null) {
            
$idCliente $this->consultas_model->consulta_clientesByName($filtro);
            
$consulta .= " where c.id_cliente= '" $idCliente[0]->id "'";
        }

        
$consulta .= " GROUP BY 2 order by 1 desc limit 20";

        
$query $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getConstantes()
    {
        
$query $this->db->query("SELECT * FROM config;");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
Cobros($filtro)
    {
        
$query    $this->db->query("SET lc_time_names = 'es_VE';");
        
$consulta "select DATE_FORMAT(fechaPago,'%M') as mes, sum(valor) as cant from pago_pedido ";

        
$consulta .= "group by 1 order by 1 desc";

        
$query $this->db->query($consulta);
        
$datos = array();

        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $cant) {

                
$mes         $cant->mes;
                
$datos[$mes] = $cant->cant;
                
$total += $cant->cant;

            }

            
$i 0;

            foreach (
$datos as $mes => $cant) {
                
$vDatos[$i]["mes"]        = $mes;
                
$vDatos[$i]["porcentaje"] = number_format(($cant $total) * 1002);
                
$vDatos[$i]["cant"]       = $cant;
                
$i++;
            }
            return 
$vDatos;
        }
    }

    public function 
getTransferencias($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('codigo'$buscador);
        }
        
$query "transferencia a left join clientes b ON a.id_cliente=b.id";

        
$this->db->order_by("fecha""desc");

        
$query $this->db->get($query$num$offset);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
registrarDetallePedido($nroPedido$nombreProducto$cant$precio)
    {
        
$data = array(
            
'id_pedido'       => $nroPedido,
            
'nombre_producto' => $nombreProducto,
            
'cantidad'        => $cant,
            
'precio'          => $precio,
        );
        
$this->db->insert('detalle_pedido'$data);
    }

    public function 
registrarDetalleImpresion($nroOrden$nombreProducto)
    {
        
$data = array(
            
'id_impresion'    => $nroOrden,
            
'nombre_producto' => $nombreProducto,

        );
        
$this->db->insert('detalle_impresion'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
borrarDetalleImpresion($nroOrden$nombreProducto)
    {
        
$query $this->db->query("delete from detalle_impresion where id_impresion='" $nroOrden "' and nombre_producto='" $nombreProducto "'");
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
registrarLogProductos($accion$nroPEdido$cotizador$producto$cantidad$precio)
    {

        
$data = array(
            
'accion'    => $accion,
            
'id_pedido' => $nroPEdido,
            
'producto'  => $producto,
            
'usuario'   => $cotizador,
            
'cantidad'  => $cantidad,
            
'precio'    => $precio,
            
'fecha_log' => date('Y-m-d'),
        );
        
$this->db->insert('log_productos'$data);
    }

    public function 
getIdNotaCredA($nro)
    {
        
$this->db->like('nro_nota_credito'$nro);
        
$query $this->db->get('notacredito');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getLogsProductos($numeroPedido)
    {

        
$this->db->where('id_pedido'$numeroPedido);
        
$query $this->db->get('log_productos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdNotaCredB($nro)
    {
        
$this->db->like('nro_nota_credito'$nro);
        
$query $this->db->get('notacreditoB');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getCompras($buscaRet$filtroTipo$fechaInicio$fechaFinal)
    {
        
$fechaInicio $fechaInicio;
        
$fechaFinal  $fechaFinal;

        
$query "select * from compras a left join proveedores b ON a.id_proveedor=b.id";

        if ((
$fechaInicio != null) || ($fechaFinal != null) || ($buscaRet != null)) {
            
$query .= " where ";
            
$habia "";
            if ((
$fechaInicio != null) && ($fechaFinal != null)) {
                
$habia "1";
                
$query .= " fechaFactura >= '" $fechaInicio "' and fechaFactura <= '" $fechaFinal "'";
            }

            if (
$buscaRet != null) {
                if (
$habia == "") {
                    
$query .= " b.id= '" $buscaRet "'";
                } else {
                    
$query .= " and b.id= '" $buscaRet "'";
                }

            }
        }

        
$query $this->db->query($query);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getRetenciones($buscaRet$fechaInicio$fechaFinal)
    {
        
$fechaInicio $fechaInicio;
        
$fechaFinal  $fechaFinal;
        
$query       "select * from retenciones a left join clientes b ON a.id_cliente=b.id left join tiporetencion c ON c.id=a.tipoRetencion";

        if ((
$fechaInicio != null) || ($fechaFinal != null) || ($buscaRet != null)) {
            
$query .= " where ";
            
$habia "";
            if ((
$fechaInicio != null) && ($fechaFinal != null)) {
                
$habia "1";
                
$query .= " fecha >= '" $fechaInicio "' and fecha <= '" $fechaFinal "'";
            }

            if (
$buscaRet != null) {
                if (
$habia == "") {
                    
$query .= " c.id= '" $buscaRet "'";
                } else {
                    
$query .= " and c.id= '" $buscaRet "'";
                }

            }
        }

        
$query $this->db->query($query);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTotalRetenciones($buscaRet$fechaInicio$fechaFinal)
    {
        
$consulta "select sum(monto) as valor from retenciones ";
        if ((
$fechaInicio != null) || ($fechaFinal != null) || ($buscaRet != null)) {
            
$consulta .= " where ";
            
$habia "";
            if ((
$fechaInicio != null) && ($fechaFinal != null)) {
                
$habia "1";
                
$consulta .= " fecha >= '" $fechaInicio "' and fecha <= '" $fechaFinal "'";
            }

            if (
$buscaRet != null) {
                if (
$habia == "") {
                    
$consulta .= " tipoRetencion= '" $buscaRet "'";
                } else {
                    
$consulta .= " and tipoRetencion= '" $buscaRet "'";
                }
            }
        }

        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProveedorbyName($proveedor)
    {
        
$this->db->like('razon_social'$proveedor);
        
$query     $this->db->get('proveedores');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }

    public function 
getIdPago($desc)
    {
        
$this->db->like('tipoPago'$desc);
        
$query     $this->db->get('tipo_pago');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id_pago;
        }
        return 
$respuesta;
    }
    public function 
getMedioPagoPedido($nro_pedido)
    {
        
$this->db->where('id_pedido'$nro_pedido);
        
$this->db->join('medios_pago a''a.id_medio = b.id_pago');
        
$query $this->db->get('detalle_medio_pago b');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getcondPagoPedido($nro_pedido)
    {
        
$this->db->where('id_pedido'$nro_pedido);
        
$this->db->join('cond_pago a''a.id_cond = b.id_cond');
        
$query $this->db->get('detalle_cond_pago b');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getCheckPagoPedido($nro_pedido)
    {
        
$this->db->where('id_pedido'$nro_pedido);
        
$this->db->join('check_pago a''a.id_check = b.id_check');
        
$query $this->db->get('detalle_check_pago b');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDataPedido($nro_pedido)
    {
        
$this->db->where('id_pedido'$nro_pedido);
        
$query $this->db->get('pedidos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getEstadoPedido($nro_pedido)
    {
        
$this->db->where('id_pedido'$nro_pedido);
        
$query $this->db->get('pedidos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
getIdItems($nro_pedido$producto$cantidad)
    {
        
$respuesta "";
        
$this->db->where('id_pedido'$nro_pedido);
        
$this->db->where('nombre_producto'$producto);
        
$this->db->where('cantidad'$cantidad);
        
$query $this->db->get('detalle_pedido');
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;

    }
    public function 
getIdDetallePago($nroPedido$tipoId$dato$valor)
    {
        
$respuesta "";
        
$this->db->where('id_pedido'$nroPedido);
        
$this->db->where('id_tipo_pago'$tipoId);
        if (
$dato != null) {

            
$this->db->where('datoPago'$dato);
        }
        
$this->db->where('valor'$valor);
        
$query $this->db->get('pago_pedido');
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;

    }

    public function 
getDescProductoByName($producto)
    {
        
$this->db->like('nombre'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->descripcion;
        }
        return 
$respuesta;
    }
    public function 
getTipoComprabyName($tipo)
    {
        
$this->db->like('descripcion'$tipo);
        
$query     $this->db->get('tipoCompra');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id_tipo;
        }
        return 
$respuesta;
    }

    public function 
registrarCompra($nroFact$tipoCompra$comboProveedor$fechaFacturas$iva$monto$descuento)
    {
        
$data = array(
            
'nro_factura'  => $nroFact,
            
'id_estado'    => '1',
            
'tipo_compra'  => $tipoCompra,
            
'total'        => $monto,
            
'id_proveedor' => $comboProveedor,
            
'ivaC'         => $iva,
            
'fechaActual'  => date('Y-m-d'),
            
'fechaFactura' => $fechaFacturas,
            
'descuento'    => $descuento,
        );
        
$this->db->insert('compras'$data);

    }

    public function 
registrarTransferencia($codTransf$monto$cliente$nroRecibo)
    {
        
$data = array(
            
'codigo'     => $codTransf,
            
'id_cliente' => $cliente,
            
'monto'      => $monto,
            
'fecha'      => date('Y-m-d'),
            
'nroRecibo'  => $nroRecibo,
        );
        
$this->db->insert('transferencia'$data);

    }

    public function 
registrarDetalleRecibo($cliente$descripcion$monto$nroRecibo$saldoAnterior)
    {

        
$data = array(
            
'descripcion'    => $descripcion,
            
'fecha'          => date('Y-m-d'),
            
'id_cliente'     => $cliente,
            
'debe'           => '',
            
'haber'          => $monto,
            
'saldo_anterior' => $saldoAnterior,
        );
        
$this->db->insert('detalle_movimiento'$data);
    }

    public function 
registrarDetalleFactura($cliente$factura$monto$saldoAnterior)
    {

        
$data = array(
            
'descripcion'    => "Venta efectuada factura Nro " $factura,
            
'fecha'          => date('Y-m-d'),
            
'id_cliente'     => $cliente,
            
'debe'           => $monto,
            
'haber'          => '',
            
'saldo_anterior' => $saldoAnterior,
        );
        
$this->db->insert('detalle_movimiento'$data);
    }

    public function 
registrarDetalleFacturaB($cliente$factura$monto$saldoAnterior)
    {

        
$data = array(
            
'descripcion'    => "Venta efectuada factura B Nro " $factura,
            
'fecha'          => date('Y-m-d'),
            
'id_cliente'     => $cliente,
            
'debe'           => $monto,
            
'haber'          => '',
            
'saldo_anterior' => $saldoAnterior,
        );
        
$this->db->insert('detalle_movimiento'$data);
    }

    
//actualizo el recibo
    
public function updateRecibo($id_recibo$total)
    {

        
$data = array(
            
'total' => $total,
        );

        
$this->db->where('id_recibo'$id_recibo);
        
$this->db->update('recibos'$data);
    }

    
//inserto detalles en los recibos a crear
    
public function insertarDetallePago($detalle$numeroRecibo$id_pedido)
    {
        
$fechaCobro null;
        if (!
$detalle->fechaCobro) {
            
$fechaCobro date('Y-m-d');
        } else {
            
$fechaCobro $detalle->fechaCobro;
        }
        
$data = array(
            
'id_pedido'    => $id_pedido,
            
'id_tipo_pago' => $this->getIdDetallePagoPuntual($detalle->tipoPago),
            
'id_recibo'    => $numeroRecibo,
            
'banco'        => $detalle->banco,
            
'nro_cheque'   => $detalle->nro_cheque,
            
'valor'        => round($detalle->valor2),
            
'fechaPago'    => date('Y-m-d'),
            
'fechaCobro'   => $fechaCobro,
        );
        
$this->db->insert('detalle_recibo'$data);
        if (
$this->db->affected_rows() > 0) {
            return 
true;
        } else {
            return 
false;
        }

    }

    public function 
getIdDetallePagoPuntual($pago)
    {
        
$this->db->like('tipoPago'$pago);
        
$query     $this->db->get('tipo_pago');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id_pago;
        }
        return 
$respuesta;
    }

    public function 
registrarDetalleRemito($nroRemito$producto$cantidad$cliente$descuento)
    {

        
$data = array(
            
'id_remito'   => $nroRemito,
            
'id_producto' => $producto,
            
'id_cliente'  => $cliente,
            
'cantidad'    => $cantidad,
            
'descuento'   => $descuento,
        );
        
$this->db->insert('detalle_remito'$data);
    }

    public function 
ingresaContacto($cliente$nombre$mail$interno$depto)
    {
        
$data = array(
            
'id_clientes' => $cliente,
            
'nombre'      => $nombre,
            
'mail'        => $mail,
            
'interno'     => $interno,
            
'depto'       => $depto,
        );
        
$this->db->insert('contactos'$data);
    }

    public function 
registrarDescuento($pedido$descuento)
    {
        
$data = array(
            
'fecha'     => $this->getFecha($pedido),
            
'descuento' => $descuento,
        );
        
$this->db->where('id_pedido'$pedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
actualizarClientePedido($pedido$cliente)
    {
        
$data = array(
            
'id_cliente' => $cliente,
            
'fecha'      => $this->getFecha($pedido),
        );
        
$this->db->where('id_pedido'$pedido);
        
$this->db->update('pedidos'$data);
    }

    public function 
actualizarSaldo($cliente$monto$operacion)
    {
        
$saldo $this->getSaldo($cliente);
        if (
$operacion == '1') {
            
$saldoFinal = ($saldo->valor_saldo $monto);
        }

        if (
$operacion == '2') {
            
$saldoFinal = ($saldo->valor_saldo $monto);
        }

        
$data = array(
            
'id_cliente'  => $cliente,
            
'valor_saldo' => $saldoFinal,
        );
        
$this->db->where('id_cliente'$cliente);
        
$this->db->update('saldos'$data);
    }

    public function 
chequearID($cliente)
    {
        
$usuario $this->get($cliente);

        
$saldoFinal = ($saldo->valor_saldo $monto);

        
$data = array(
            
'id_cliente'  => $cliente,
            
'valor_saldo' => $saldoFinal,
        );
        
$this->db->where('id_cliente'$cliente);
        
$this->db->update('saldos'$data);
    }

    public function 
getCliente($id)
    {
        
$query $this->db->query("select id_cliente from saldos where id_cliente='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTotalByIdFactura($factura)
    {
        
$query $this->db->query("select total from factura where nro_factura='" $factura "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTotalByIdRemito($remito)
    {
        
$query $this->db->query("select total from remito where nro_remito='" $remito "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
insertarClienteSaldo($id)
    {

        
$data = array(
            
'id_cliente'  => $id,
            
'valor_saldo' => '0',
        );
        
$this->db->insert('saldos'$data);

    }

    public function 
consulta_pedidosById($id)
    {
        
$query $this->db->query("select * from pedidos where id_pedido='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
consulta_clientesById($id)
    {
        
$query $this->db->query("select * from clientes where id='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_ProveedoresById($id)
    {
        
$query $this->db->query("select * from proveedores where id='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_clientesByName($name)
    {

        
$this->db->like('razon_social'$name);
        
$query $this->db->get('clientes');
        if (
$query->num_rows() > 0) {
            return 
$query->row()->id;
        }

    }

    public function 
consulta_clientesSaldos($id)
    {
        
$cliente $this->getCliente($id);
        if (
$cliente == null) {
            
$this->insertarClienteSaldo($id);
        }
    }

    public function 
getSiyaEntro($producto$ordenRef)
    {
        
$query $this->db->query("select id_producto,nro_Referencia from detalle_factura where id_producto='" $producto "' and nro_Referencia='" $ordenRef "';");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
registrarDetalleFactaura($nroFactura$producto$cantidad$cliente$descuento)
    {

        
$data = array(
            
'id_factura'  => $nroFactura,
            
'id_producto' => $producto,
            
'id_cliente'  => $cliente,
            
'cantidad'    => $cantidad,
            
'descuento'   => $descuento,
        );
        
$this->db->insert('detalle_factura'$data);
    }

    public function 
registrarDetalleFactauraB($nroFactura$producto$cantidad$cliente$iva$descuento)
    {
        
$data = array(
            
'id_factura'  => $nroFactura,
            
'id_producto' => $producto,
            
'id_cliente'  => $cliente,
            
'cantidad'    => $cantidad,
            
'iva'         => $iva,
            
'descuento'   => $descuento,
        );
        
$this->db->insert('detalle_factura_b'$data);

    }

    public function 
getDescByProducto($producto)
    {
        
$query $this->db->query("select id,descripcion from productos where nombre='" $producto "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getTipoMensajeCredito($motivo)
    {
        
$query $this->db->query("select descripcion from tipocredito where id='" $motivo "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDescByNameDescByID($id)
    {
        
$query $this->db->query("select nombre,descripcion from productos where id='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDescuentos()
    {
        
$data  = array();
        
$query $this->db->get('descuentos');
        if (
$query->num_rows() > 0) {
            
$i 1;
            foreach (
$query->result() as $fila) {
                
$data[$i] = $fila->descripcion;
                
$i++;
            }
        }
        return 
$data;
    }

    public function 
getTiposEstados()
    {
        
$data  = array();
        
$query $this->db->get('estado_pedidos');
        if (
$query->num_rows() > 0) {
            
$i 1;
            foreach (
$query->result() as $fila) {
                
$data[$i] = $fila->estado;
                
$i++;
            }
        }
        return 
$data;
    }
    public function 
getTiposPagos()
    {
        
$data  = array();
        
$query $this->db->get('tipo_pago');
        if (
$query->num_rows() > 0) {
            
$i 1;
            foreach (
$query->result() as $fila) {
                
$data[$i] = $fila->tipoPago;
                
$i++;
            }
        }
        return 
$data;
    }
    public function 
getIDByProducto($producto)
    {

        
$this->db->like('nombre'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }

    public function 
getDetallesPedidoByIdDepo($nroPedido)
    {

        
$query $this->db->query("select b.nombre as nombre,c.ordenamiento as orden,b.descripcion as descripcion,
                a.cantidad as cantidad ,a.precio as precio, a.id as id,d.estado as estado,f.ubicacion from detalle_pedido a
                left join productos b ON b.nombre=a.nombre_producto
                left join estado_productos d ON d.id=b.id_estado
                left join ubicacion_productos e ON b.nombre=e.nombre
                left join categorias_ubicacion f ON e.id_ubicacion=f.id_ubicacion
                left join categorias_productos c on c.id=b.id_categoria where a.id_pedido='" 
$nroPedido "' order by 8,1 asc");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesPedidoByIdSinStock($nroPedido)
    {

        
$query $this->db->query("select b.nombre as nombre,c.ordenamiento as orden,b.descripcion as descripcion,
                a.cantidad as cantidad ,a.precio as precio, a.id as id,d.estado as estado from detalle_pedido a
                left join productos b ON b.nombre=a.nombre_producto
                left join estado_productos d ON d.id=b.id_estado
                left join categorias_productos c on c.id=b.id_categoria where a.id_pedido='" 
$nroPedido "' and d.estado='PEND INGRESO'order by 2,1 asc");
        if (
$query->num_rows() > 0) {
            
$i   0;
            
$arr = array();
            foreach (
$query->result() as $r) {
                
$arr[$i]['nombre']      = $r->nombre;
                
$arr[$i]['descripcion'] = $r->descripcion;
                
$arr[$i]['precio']      = $r->precio;
                
$arr[$i]['estado']      = $r->estado;
                
$arr[$i]['cantidad']    = $r->cantidad;
                
$arr[$i]['id']          = $r->id;
                
$i++;
            }
            
# JSON-encode the response
            
$json_response json_encode($arr);

            
// # Return the response
            
echo $json_response;
        }
    }
    public function 
getDetallesPedidoByIdConStock($nroPedido)
    {

        
$query $this->db->query("select a.id as id,b.nombre as nombre,c.ordenamiento as orden,b.descripcion as descripcion,
                a.cantidad as cantidad ,a.precio as precio, a.id as id,d.estado as estado from detalle_pedido a
                left join productos b ON b.nombre=a.nombre_producto
                left join estado_productos d ON d.id=b.id_estado
                left join categorias_productos c on c.id=b.id_categoria where a.id_pedido='" 
$nroPedido "' and d.estado!='PEND INGRESO' order by 2,1 asc");
        if (
$query->num_rows() > 0) {
            
$i   0;
            
$arr = array();
            foreach (
$query->result() as $r) {
                
$arr[$i]['nombre']      = $r->nombre;
                
$arr[$i]['descripcion'] = $r->descripcion;
                
$arr[$i]['precio']      = $r->precio;
                
$arr[$i]['estado']      = $r->estado;
                
$arr[$i]['cantidad']    = $r->cantidad;
                
$arr[$i]['id']          = $r->id;
                
$i++;
            }
            
# JSON-encode the response
            
$json_response json_encode($arr);

            
// # Return the response
            
echo $json_response;
        }
    }

    public function 
getDetallesPedidoById($nroPedido)
    {

        
$query $this->db->query("select b.nombre as nombre,c.ordenamiento as orden,b.descripcion as descripcion,
                a.cantidad as cantidad ,a.precio as precio, a.id as id,d.estado as estado from detalle_pedido a
                left join productos b ON b.nombre=a.nombre_producto
                left join estado_productos d ON d.id=b.id_estado
                left join categorias_productos c on c.id=b.id_categoria where a.id_pedido='" 
$nroPedido "' order by 2,1 asc");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getNextPedido()
    {
        
$query $this->db->query("SELECT MAX(id_pedido)+1 as cant FROM pedidos");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByIdB($id)
    {
        
$query $this->db->query("select * from detalle_pedido a left join productos b ON b.nombre=a.nombre_producto where a.id_pedido='" $id "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByIdOT($nroOT$idCliente)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad,b.precio as precio from detalle_orden_trabajo a left join productos b ON b.id=a.id_producto where a.id_ot='" $nroOT "' and a.id_cliente='" $idCliente "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesRemito($remito)
    {
        
$query $this->db->query("select a.id_detalle as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad,b.precio as precio from detalle_remito a left join productos b ON b.id=a.id_producto where a.id_remito='" $remito "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
consulta_OtByEstadoCant($estado)
    {
        
$query $this->db->query("select count(nro_ot) as cant from ordentrabajo  where id_estado='" $estado "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cant;
        }

    }

    public function 
getDetallesByIdOC($nroOC$idCliente)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad,b.precio as precio,a.cant_disponible from detalle_OC a left join productos b ON b.id=a.id_producto where a.id_OC='" $nroOC "' and a.id_cliente='" $idCliente "'");

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesRemitoById($nroRemito$idCliente)
    {
        
$query $this->db->query("select a.id_detalle as id,b.id as idProducto,b.nombre as nombre,b.precio as precio,a.descuento as descuento,b.descripcion as descripcion,a.cantidad as cantidad from detalle_remito a left join productos b ON b.id=a.id_producto where a.id_remito='" $nroRemito "' and a.id_cliente='" $idCliente "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByFra($nroFactura)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad,b.precio as precio from detalle_factura a left join productos b ON b.id=a.id_producto where a.id_factura='" $nroFactura "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByFraB($nroFactura)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad,b.precio as precio from detalle_factura_b a left join productos b ON b.id=a.id_producto where a.id_factura='" $nroFactura "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByOC($nroFactura)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad from detalle_oc a left join productos b ON b.id=a.id_producto where a.id_oc='" $nroFactura "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDetallesByOT($nroOT)
    {
        
$query $this->db->query("select b.id as id,b.nombre as nombre,b.descripcion as descripcion,a.cantidad as cantidad from detalle_orden_trabajo a left join productos b ON b.id=a.id_producto where a.id_ot='" $nroOT "'");
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosByPrecio($producto)
    {
        
$this->db->like('nombre'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->precio;
        }
        return 
$respuesta;
    }

    public function 
getProductos($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('nombre'$buscador);
        }
        
$this->db->join('stock_productos''stock_productos.nombre_producto = productos.nombre''left');
        
$this->db->join('estado_productos''estado_productos.id = productos.id_estado''left');
        
$query $this->db->get('productos'$num$offset);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosPunt($id)
    {

        
$sql "select a.nombre as nombre_a,a.descripcion,a.numero as numero,a.precio as precio,
                b.stock as stock,c.categoria as categoria,a.id_categoria as catId,a.imagen as imagen,
                a.id_estado as id_estado,d.estado as estado
                from productos a left join stock_productos b ON b.nombre_producto=a.nombre
                left join categorias_productos c on c.id=a.id_categoria
                left join estado_productos d on d.id=a.id_estado where a.nombre='" 
$id "'";

        
$query $this->db->query($sql);

        
$i   0;
        
$arr = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre_producto'] = $r->nombre_a;
            
$arr[$i]['descripcion']     = $r->descripcion;
            
$arr[$i]['numero']          = $r->numero;
            
$arr[$i]['precio']          = $r->precio;
            
$arr[$i]['id_estado']       = $r->id_estado;
            
$arr[$i]['estado']          = $r->estado;
            
$arr[$i]['categoria']       = $r->categoria;
            
$arr[$i]['id_categoria']    = $r->catId;
            
$arr[$i]['stock']           = $r->stock;
            
$file                       RUTA $r->nombre_a ".jpg";
            if (
file_exists($file)) {
                
$archFoto $r->nombre_a ".jpg";
            } else {
                
$archFoto "nodisp.jpg";
            }
            
$arr[$i]['imagen'] = $archFoto;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;

    }

    public function 
chequeoItemRepetido($nroPedido$nombreProducto$cant)
    {
        
$consulta "select * from detalle_pedido where id_pedido='" $nroPedido "' and nombre_producto='" $nombreProducto "' and cantidad='" $cant "'";
        
$query    $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0];
        }
    }

    public function 
getProductosLogAjax()
    {
        
$this->db->order_by("productos_log.fecha""desc");
        
$this->db->join('categorias_productos''categorias_productos.id = productos_log.id_categoria''left');
        
$this->db->join('estado_productos''estado_productos.id = productos_log.id_estado''left');
        
$query $this->db->get('productos_log'$num$offset);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']       = $r->nombre;
            
$arr[$i]['descripcion']  = $r->descripcion;
            
$arr[$i]['precio_venta'] = $r->precio_venta;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['cotizador']    = $r->usuario;
            
$arr[$i]['numero']       = $r->numero;
            
$arr[$i]['categoria']    = $r->categoria;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;

            
$arr[$i]['stock'] = $r->stock;
            
$file             RUTA $r->nombre ".jpg";
            if (
file_exists($file)) {
                
$archFoto $r->nombre ".jpg";
            } else {
                
$archFoto "nodisp.jpg";
            }
            
$arr[$i]['imagen'] = $archFoto;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getOrdenesAajax()
    {

        
$this->db->order_by("id_impresion""desc");
        
$this->db->where('id_estado'"1");
        
$query $this->db->get('impresiones'$num$offset);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['id_impresion'] = $r->id_impresion;
            
$arr[$i]['usuario']      = $r->usuario;
            
$fechaReal               explode(" "$r->fecha);
            
$fecha                   $fechaReal[0];
            
$fecha                   date('d/m/Y'strtotime($fecha));
            
$arr[$i]['fecha']        = $fecha;
            
$arr[$i]['estado']       = $r->estado;

            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getProductosAjax()
    {

        
$this->db->join('categorias_productos''categorias_productos.id = productos.id_categoria''left');
        
$this->db->join('stock_productos''stock_productos.nombre_producto = productos.nombre''left');
        
$this->db->join('estado_productos''estado_productos.id = productos.id_estado''left');
        
$query $this->db->get('productos'$num$offset);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']       = $r->nombre;
            
$arr[$i]['descripcion']  = $r->descripcion;
            
$arr[$i]['precio_venta'] = $r->precio_venta;
            
$arr[$i]['precio']       = $r->precio;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['numero']       = $r->numero;
            
$arr[$i]['categoria']    = $r->categoria;
            
$arr[$i]['stock']        = $r->stock;
            
$file                    RUTA $r->nombre ".jpg";
            if (
file_exists($file)) {
                
$archFoto $r->nombre ".jpg";
            } else {
                
$archFoto "nodisp.jpg";
            }
            
$arr[$i]['imagen'] = $archFoto;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getProductosAjaxClientes()
    {

        
$this->db->join('stock_productos''stock_productos.nombre_producto = productos.nombre''left');
        
$this->db->join('estado_productos''estado_productos.id = productos.id_estado''left');
        
$query $this->db->get('productos'$num$offset);
        
$i     0;
        
$arr   = array();
        foreach (
$query->result() as $r) {
            
$arr[$i]['nombre']       = $r->nombre;
            
$arr[$i]['descripcion']  = $r->descripcion;
            
$arr[$i]['precio_venta'] = $r->precio_venta;
            
$arr[$i]['estado']       = $r->estado;
            
$arr[$i]['stock']        = $r->stock;
            
$file                    RUTA $r->nombre ".jpg";
            if (
file_exists($file)) {
                
$archFoto $r->nombre ".jpg";
            } else {
                
$archFoto "nodisp.jpg";
            }
            
$arr[$i]['imagen'] = $archFoto;
            
$i++;
        }
        
# JSON-encode the response
        
$json_response json_encode($arr);

        
// # Return the response
        
echo $json_response;
    }

    public function 
getProductosCategoriaImpresionGeneral()
    {
        
$consulta "select * from productos a left join detalle_impresion b on b.nombre_producto=a.nombre
left join categorias_productos c ON c.id=a.id_categoria where a.id_estado!='1' order by c.ordenamiento asc ;"
;
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
getProductosCategoriaImpresion($categoria)
    {
        
$consulta "select * from productos a left join detalle_impresion b on b.nombre_producto=a.nombre
left join categorias_productos c ON c.id=a.id_categoria where c.categoria='" 
$categoria "' and a.id_estado!='1' order by c.ordenamiento asc ;";
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }

    }
    public function 
getProductosCategorias()
    {

        
$this->db->order_by("categorias_productos.ordenamiento""desc");
        
$this->db->join('categorias_productos''categorias_productos.id = productos.id_categoria''left');
        
$query $this->db->get('productos');
        
$this->db->group_by('categorias_productos.categoria');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosCodigos()
    {
        
$this->db->order_by("categorias_productos.ordenamiento""asc");
        
$this->db->where('productos.id_estado !=''1');
        
$this->db->join('categorias_productos''categorias_productos.id = productos.id_categoria''left');
        
$query $this->db->get('productos');

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosCodigosOrdenes($nroOrden)
    {

        
$consulta "select * from productos a left join detalle_impresion b on b.nombre_producto=a.nombre
left join categorias_productos c ON c.id=a.id_categoria where b.id_impresion='" 
$nroOrden "' order by c.ordenamiento asc ;";
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosCatalogoExpoMarzo2018()
    {
        
$consulta "select a.nombre as NOMBRE,IFNULL(b.cantidad, 0) as VENDIDOS,a.precio_venta as precio,a.descripcion as DESCRIPCION,
c.stock as STOCK,d.estado as ESTADO
 from productos a
 left join (
SELECT nombre_producto as nombre_producto,sum(detalle_pedido.cantidad) as cantidad FROM detalle_pedido
LEFT JOIN pedidos ON detalle_pedido.id_pedido = pedidos.id_pedido
where pedidos.id_estado !='3' and detalle_pedido.nombre_producto !=''  and pedidos.fecha>='2018-03-14' and pedidos.fecha<'2018-03-18'
and  pedidos.id_cliente not in (3364,3365,3366,3514)
group by 1
) b ON b.nombre_producto=a.nombre
left join stock_productos c ON c.nombre_producto=a.nombre
left join estado_productos d ON d.id=a.id_estado
left join categorias_productos e ON e.id=a.id_categoria
 group by a.nombre,e.id  order by e.ordenamiento desc;"
;
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosCatalogo()
    {
        
$consulta "select a.nombre as NOMBRE,IFNULL(b.cantidad, 0) as VENDIDOS,a.precio_venta as precio,a.descripcion as DESCRIPCION,
c.stock as STOCK,d.estado as ESTADO
 from productos a
 left join (
SELECT nombre_producto as nombre_producto,sum(detalle_pedido.cantidad) as cantidad FROM detalle_pedido
LEFT JOIN pedidos ON detalle_pedido.id_pedido = pedidos.id_pedido
where pedidos.id_estado !='3' and detalle_pedido.nombre_producto !=''  and pedidos.fecha>=DATE_SUB(NOW(),INTERVAL 1 YEAR)
and  pedidos.id_cliente not in (3364,3365,3366,3514)
group by 1
) b ON b.nombre_producto=a.nombre
left join stock_productos c ON c.nombre_producto=a.nombre
left join estado_productos d ON d.id=a.id_estado
left join categorias_productos e ON e.id=a.id_categoria
 group by a.nombre,e.id  order by e.ordenamiento desc;"
;

        
//revisar esta consulta tarda dos minutos:
        /*    $consulta =" select d.nombre as NOMBRE, f.categoria as categoria,j.estado as ESTADO,d.precio as precio,IFNULL(sum(c.cantidad), 0) as VENDIDOS,e.stock as STOCK from pedidos a
        left join detalle_pedido c on c.id_pedido=a.id_pedido left join productos d on d.nombre=c.nombre_producto
        left join stock_productos e on e.nombre_producto=d.nombre left join categorias_productos f on f.id=d.id_categoria
        left join estado_productos j on j.id=d.id_estado
        where a.id_pedido!='3' and a.fecha>=DATE_SUB(NOW(),INTERVAL 1 YEAR) and a.id_cliente not in (3364,3365,3366,3514,3058)
        group by 1 order by f.ordenamiento desc;";
         */
        
$query $this->db->query($consulta);

        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosEspeciales()
    {
        
/*    $array=array('019721','021121','1921100','020651','021100','1378a','1517801b','306-8013','306-8040','306-776001','306-783216','306-783219','306-786186',
        '150895-1A',
        '017300A',
        '0017500B',
        '9022200',
        '9022300',
        '9022102B',
        '9022400',
        '9022802',
        '1969700B',
        '1973900',
        '1529500B',
        '1539300A',
        '1539202A',
        '1446822A',
        '1472523A',
        '1369653C',
        '1472900A',
        '17617000',
        '17614400A',
        '150855B',
        '9073100A',
        '9073300A',
        '9073401',
        '1305102B',
        '1326902C',
        '472526C',
        '1613303C',
        '1612304A',
        '9072600A',
        '9072600B',
        '1722401',
        '77298',
        '1529501B',
        '150622-3D',
        '160064-1A',
        '150626-3D',
        '160611-B',
        '160065-1D',
        '160060-1A',
        '160757',
        '160611',
        '1378A');

        $array=array('501041D',
        '1103W',
        '905337',
        '501050M',
        '99657W',
        '1472601',
        '1669800C',
        '150897',
        '150788-5B',
        '150789-3',
        '150783-2B',
        '1326901A',
        '160061-1B',
        '1529501B',
        '1500820',
        '1500720',
        '1969700B',
        '1378A',
        '7729B',
        '43900',
        '1600602',
        '158773F',
        '306-81113',
        '306-1133639L',
        '306-317261B',
        '306-91430332',
        '306-1123541L',
        '306-109707L',
        '306-3143721',
        '306-160168',
        '306-1201231',
        );
        $array=array(
        '021100',
        '000200',
        '026900',
        '028800',
        '020751',
        '024851',
        '1395K-2',
        '1692751',
        '306.80870',
        '306.80882',
        '306-8143001',
        '306-3150005',
        '306-3130001C',
        '306-12019-1',
        '306-12019G',
        '306-12298',
        '306-10028',
        '1103W',
        '905337W',
        '99604W',
        '99657-1W',
        '1378A',
        '1762400B',
        '306-1148668L',
        '306-1158041L',
        '306-7141781',
        '306-1148066L',
        '306-1110632',
        '306-12335',
        '306-9142141',
        '306-9144010',
        '306-416242',
        '1564400',
        '1398G',
        '306-13041-R1',
        '1702300A',
        '306-10050-1'
        );
         */
        
$array = array(
            
'024851',
            
'1692751',
            
'000200',
            
'006851',
            
'100307',
        );
        
$this->db->where_in('nombre'$array);

        
$query $this->db->get('productos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getDatosProducto($nombre)
    {

        
$this->db->where_in('nombre'$nombre);
        
$query $this->db->get('productos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }
    public function 
getProductosCodigosNuevos()
    {
        
$this->db->where_in('id_estado'"3");
        
$query $this->db->get('productos');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getIdEstado($estado)
    {

        
$this->db->like('estado'$estado);
        
$query     $this->db->get('estado_pedidos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }
    public function 
getIdEstadoProductos($estado)
    {

        
$this->db->where('estado'$estado);
        
$query     $this->db->get('estado_productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }

    public function 
getIdCategoria($estado)
    {

        
$this->db->where('categoria'$estado);
        
$query     $this->db->get('categorias_productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }

    public function 
getIdClienteDePedido($pedido)
    {
        if (
$pedido != null) {
            
$this->db->where('id_pedido'$pedido);
        }
        
$query $this->db->get('pedidos');
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->id_cliente;
        }
    }

    public function 
getClientePedido($buscador)
    {
        if (
$buscador != null) {
            
$this->db->like('razon_social'$buscador);
        }
        
$query $this->db->get('clientes');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getCotizadorPedido($pedido)
    {
        
$consulta "select cotizador from pedidos where id_pedido='" $pedido "';";
        
$query    $this->db->query($consulta);
        if (
$query->num_rows() > 0) {
            return 
$query->result()[0]->cotizador;
        }
    }
    public function 
getClientes()
    {
        
$this->db->order_by("razon_social""asc");
        
$query $this->db->get('clientes');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getVendedoresFiltro()
    {
        
$this->db->order_by("nombre""asc");
        
$query $this->db->get('vendedores');
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getClientesExistentes($buscador$num$offset)
    {
        if (
$buscador != null) {
            
$this->db->like('razon_social'$buscador);
        }
        
$query $this->db->get('clientes'$num$offset);
        if (
$query->num_rows() > 0) {
            return 
$query->result();
        }
    }

    public function 
getProductosBuscador($buscador)
    {

        
$this->db->select('nombre');
        
$this->db->like('nombre'$buscador'after');
        
$resultados $this->db->get('productos'12);
        
//si existe algún resultado lo devolvemos
        
if ($resultados->num_rows() > 0) {
            foreach (
$resultados->result_array() as $row) {
                
$row_set[] = $row['nombre']; //build an array
            
}
            echo 
json_encode($row_set);

            
//en otro caso devolvemos false
        
} else {

            echo 
"No encontrado";

        }
    }

    public function 
consulta_clientesASinPag($buscador)
    {

        
$this->db->select('razon_social');
        
$this->db->like('razon_social'$buscador'after');
        
$resultados $this->db->get('clientes'10);
        
//si existe algún resultado lo devolvemos
        
if ($resultados->num_rows() > 0) {
            foreach (
$resultados->result_array() as $row) {
                
$row_set[] = $row['razon_social']; //build an array
            
}
            echo 
json_encode($row_set);

            
//en otro caso devolvemos false
        
} else {

            echo 
"No encontrado";

        }
    }

    public function 
getNameByID($producto)
    {
        
$this->db->where('id'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->nombre;
        }
        return 
$respuesta;
    }

    public function 
getDescripcionByPrecio($producto)
    {
        
$this->db->where('id'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            return 
$respuesta $query->row()->descripcion;
        }
    }

    public function 
getProductosByName()
    {

        
$data  = array();
        
$query $this->db->get('productos');
        if (
$query->num_rows() > 0) {
            
$i 1;
            foreach (
$query->result() as $fila) {
                
$data[$i] = $fila->nombre;
                
$i++;
            }
        }
        return 
$data;
    }

    public function 
get_id_cliente($usuario)
    {
        
$this->db->where('cuit'$usuario);
        
$query $this->db->get('clientes');

        if (
$query->num_rows() > 0) {
            return 
$query->row();
        }

    }

    public function 
getItemByID($id)
    {
        
$this->db->where('id'$id);
        
$query     $this->db->get('detalle_pedido');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row();
        }
        return 
$respuesta;
    }

    public function 
getDescripcionProductosByName($nombre)
    {
        
$this->db->like('nombre'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->descripcion;
        }
        return 
$respuesta;
    }

    public function 
getIdProductosByName($nombre)
    {
        
$this->db->like('nombre'$producto);
        
$query     $this->db->get('productos');
        
$respuesta "";
        if (
$query->num_rows() > 0) {
            
$respuesta $query->row()->id;
        }
        return 
$respuesta;
    }

    
//contamos todos los resultados de la tabla
    //que pasemos como argumento
    
public function count_results($table)
    {
        return 
$this->db->count_all_results($table);
    }

    
//obtenemos un usuario dependiendo del id que le pasemos
    
public function consulta_get_where($id)
    {
        
$query $this->db->get_where('users', array('id' => $id));
        if (
$query->num_rows() > 0) {
            
//veamos que sólo retornamos una fila con row(), no result()
            
return $query->row();
        }
    }

    
//insertamos un nuevo usuario en la tabla users
    
public function insert_user()
    {
        
$data = array(
            
'username'      => 'Juan68',
            
'fname'         => 'Juan',
            
'lname'         => 'Pérez',
            
'register_date' => '2013-01-19 10:00:00',
        );
        
$this->db->insert('users'$data);
    }

    
//eliminamos al usuario con id = 1
    
public function delete_user()
    {
        
$this->db->delete('users', array('id' => 1));
    }

    public function 
eliminarDetalle($id)
    {
        
$this->db->delete('detalle_pedido', array('id' => $id));
    }

    
//actualizamos los datos del usuario con id = 3
    
public function update_user()
    {
        
$data = array(
            
'username' => 'silvia',
            
'fname'    => 'madrejo',
            
'lname'    => 'sánchez',
        );
        
$this->db->where('id'3);
        
$this->db->update('users'$data);
    }
}
/*
 * end of application/models/consultas_model.php
 */

:: Command execute ::

Enter:
 
Select:
 

:: Search ::
  - regexp 

:: Upload ::
 
[ Read-Only ]

:: Make Dir ::
 
[ Read-Only ]
:: Make File ::
 
[ Read-Only ]

:: Go Dir ::
 
:: Go File ::
 

--[ c99shell v. 2.0 [PHP 7 Update] [25.02.2019] maintained by KaizenLouie | C99Shell Github | Generation time: 0.0301 ]--