<?php

namespace App\Models;
use App\Http\Controllers\Libreria;
use Illuminate\Support\Facades\DB;

class Facturacion
{   
    public function getFormasPagoFB(){
        $result = DB::connection('firebird')
                    ->table('CFG_VALORCAMPOSGENERICOS')
                    ->select(DB::raw("VALOR"))
                    ->where('NOMBRECAMPO','like','%PARA FORMAS DE PAGO EN VENTAS-PEDIDOS AL EMITIR UN TICKET%')
                    ->get();
        return $result;
    }

    public function getAlmacenesFB($conexion){
        $nombreConexion = 'firebird_temp';
        
        config([
            "database.connections.$nombreConexion" => [
                'driver'   => 'firebird',
                'host'     => 'localhost',
                'database' => $conexion,
                'username' => 'SYSDBA',
                'password' => '@+-KwpT040213022008-+@',
                'charset'  => 'UTF8',
            ]
        ]);
        $result = DB::connection($nombreConexion)
                    ->table('CFG_ALMACENES')
                    ->select(DB::raw("ID,DESCRIPCION"))
                    ->where('ACTIVO','=','S')
                    ->get();
        return $result;
    }

    public function getEstados(){
        $result = DB::table('sat_estado')
                    ->where('id_sat_pais','MEX')
                    ->where('status','=',1)
                    ->orderBy('descripcion')
                    ->get();
        return $result;
    }

    public function getLocalidades($request){
        $result = DB::table('sat_localidad')
                    ->where('id_sat_estado',$request->estado)
                    ->where('status','=',1)
                    ->orderBy('descripcion')
                    ->get();
        return $result;
    }

    public function getMunicipios($request){
        $result = DB::table('sat_municipio')
                    ->where('id_sat_estado',$request->estado)
                    ->where('status','=',1)
                    ->orderBy('descripcion')
                    ->get();
        return $result;
    }

    public function getColonias($request){
        //dd($request->cp,$request->estado);
        if(isset($request->estado)){
            $existe = DB::table('sat_codigopostal')
                        ->where('id',$request->cp)
                        ->where('estado',$request->estado)
                        ->exists();
        }else{
            $existe = true;
        }
        if($existe){
            $result = DB::table('sat_colonia')
                        ->where('codigopostal',$request->cp)
                        ->where('status','=',1)
                        ->orderBy('descripcion')
                        ->get();
        }else{
            $result = 0;
        }
        //dd($result);
        return $result;
    }

    public function getAlmacenes(){
        $result = DB::table('tpv_almacen')
                    ->where('status','=',1)
                    ->orderBy('descripcion')
                    ->get();
        return $result;
    }

    public function getDescripcion($tabla,$id){
        $result = DB::table($tabla)
                    ->where('id',$id)
                    ->first();
        
        return utf8_decode(substr($result->descripcion,0,69));
    }

    public function getDescripcionMunLoc($tabla,$id,$estado){
        $result = DB::table($tabla)
                    ->where('id',$id)
                    ->where('id_sat_estado',$estado)
                    ->first();
        //dd($result->descripcion);
        if(isset($result->descripcion)){
            return utf8_decode($result->descripcion);
        }else{
            return '';
        }
    }

    public function getDescripcionCol($tabla,$id,$cp){
        $result = DB::table($tabla)
                    ->where('id',$id)
                    ->where('codigopostal',$cp)
                    ->first();
        
        return utf8_decode($result->descripcion);
    }

    public function getAlmacenesCP($conexion){
        $result = DB::table('tpv_almacen')
                    ->select(DB::raw("tpv_almacen.*,
                                      tpv_almacen.descripcion as almacen,
                                      sat_pais.descripcion as pais,
                                      sat_estado.descripcion as estado,
                                      sat_municipio.descripcion as municipio,
                                      sat_localidad.descripcion as localidad,
                                      sat_colonia.descripcion as colonia,
                                      sys_direccion.calle as calle,
                                      sys_direccion.cp as cp,
                                      sys_direccion.numexterior as numext"))
                    ->leftjoin('sys_direccion','tpv_almacen.id_sys_direccion','sys_direccion.id')
                    ->leftjoin('sat_pais','sys_direccion.pais','sat_pais.id')
                    ->leftjoin('sat_estado', function($join){
                        $join->on('sys_direccion.estado', '=', 'sat_estado.id');
                        $join->on('sat_estado.id_sat_pais', '=', 'sys_direccion.pais');
                    })
                    ->leftjoin('sat_municipio', function($join){
                        $join->on('sys_direccion.municipio', '=', 'sat_municipio.id');
                        $join->on('sat_municipio.id_sat_estado', '=', 'sys_direccion.estado');
                    })
                    ->leftjoin('sat_localidad', function($join){
                        $join->on('sys_direccion.localidad', '=', 'sat_localidad.id');
                        $join->on('sat_localidad.id_sat_estado', '=', 'sys_direccion.estado');
                    })
                    ->leftjoin('sat_colonia', function($join){
                        $join->on('sys_direccion.colonia', '=', 'sat_colonia.id');
                        $join->on('sat_colonia.codigopostal', '=', 'sys_direccion.cp');
                    })
                    ->where('tpv_almacen.status','=',1)
                    ->where('tpv_almacen.conexion',$conexion)
                    ->get();
        return $result;
    }  
    
    public function saveAlmacenCP($request,$conexion){
        DB::beginTransaction();
        
        $result1 = DB::table('sys_direccion')
                    ->insertGetId([
                        'calle'=>$request->calle,
                        'numexterior'=>$request->numext,
                        'cp'=>$request->cp,
                        'pais'=>$request->pais,
                        'estado'=>$request->estado,
                        'municipio'=>$request->municipio,
                        'localidad'=>$request->localidad,
                        'colonia'=>$request->colonia
                    ]);
        if($result1>0){
            $result2 = DB::table('tpv_almacen')
                        ->insert([
                            'id_almacenprediction'=>$request->idalmacen,
                            'descripcion'=>$request->almacen,
                            'id_sys_empresa'=>1,
                            'id_sys_direccion'=>$result1,
                            'conexion'=>$conexion
                        ]);
            if($result2>0){
                DB::commit();
                return $result2;
            }else{
                DB::rollBack();
                return 'Problemas al crear el almacen. Contacte con el administrador del sistema.';
            }
        }else{
            DB::rollBack();
            return 'Problemas al crear la direccion del almacen. Contacte con el administrador del sistema.';
        }
    }

    public function getTipoFigura(){
        $result = DB::table('sat_tipofigura')
                    ->where('status','=',1)
                    ->get();
        return $result;
    }

    public function getOperadores($conexion){
        $result = DB::table('cat_operador')
                    ->select(DB::raw("cat_operador.*,sat_tipofigura.descripcion as tipofigura"))
                    ->join('sat_tipofigura','cat_operador.id_sat_tipofigura','sat_tipofigura.id')
                    ->where('cat_operador.status','=',1)
                    ->where('cat_operador.conexion',$conexion)
                    ->get();
        return $result;
    }

    public function saveOperadorCP($request,$conexion){
        DB::beginTransaction();
        
        $result1 = DB::table('cat_operador')
                    ->insertGetId([
                        'nombre'=>$request->nombre,
                        'licencia'=>$request->licencia,
                        'rfc'=>$request->rfc,
                        'id_sat_tipofigura'=>$request->tipofigura,
                        'conexion'=>$conexion
                    ]);
        if($result1>0){
            DB::commit();
            return $result1;
        }else{
            DB::rollBack();
            return 'Problemas al crear el operador. Contacte con el administrador del sistema.';
        }
    }
    

    public function getTipoVehiculo(){
        $result = DB::table('sat_configvehicular')
                    ->where('status','=',1)
                    ->orderBy('orden')
                    ->get();
        return $result;
    }

    public function getVehiculos($conexion){
        $result = DB::table('cat_vehiculo')
                    ->select(DB::raw("cat_vehiculo.*,sat_configvehicular.id as tipo"))
                    ->join('sat_configvehicular','cat_vehiculo.id_sat_configvehicular','sat_configvehicular.id')
                    ->where('cat_vehiculo.status','=',1)
                    ->where('cat_vehiculo.conexion',$conexion)
                    ->get();
        return $result;
    }

    public function saveVehiculoCP($request,$conexion){
        DB::beginTransaction();
        
        $result1 = DB::table('cat_vehiculo')
                    ->insertGetId([
                        'descripcion'=>$request->descripcion,
                        'modelo'=>$request->modelo,
                        'placa'=>$request->placa,
                        'peso'=>$request->peso,
                        'aseguradora'=>$request->aseguradora,
                        'poliza'=>$request->poliza,
                        'id_sat_configvehicular'=>$request->tipo,
                        'conexion'=>$conexion
                    ]);
        if($result1>0){
            DB::commit();
            return $result1;
        }else{
            DB::rollBack();
            return 'Problemas al crear el operador. Contacte con el administrador del sistema.';
        }
    }

    public function getTipoPermiso(){
        $result = DB::table('sat_tipopermisosct')
                    ->where('status','=',1)
                    ->get();
        return $result;
    }

    public function getPermiso($id){
        $result = DB::table('sys_empresa')
                    ->where('id','=',$id)
                    ->first();
        return $result;
    }

    public function getInfoVehiculo($id){
        $result = DB::table('cat_vehiculo')
                    ->where('id',$id)
                    ->first();
        return $result;
    }

    public function getInfoOperador($id){
        $result = DB::table('cat_operador')
                    ->where('id',$id)
                    ->first();
        return $result;
    }

    public function saveCartaPorte($request,$conexion){
        $lib = new Libreria;
        DB::beginTransaction();
        $result = DB::table('tpv_cartaporte')
                    ->where('uuid',$request->uuid)
                    ->count();
        if($result>0){
            DB::rollBack();
            return $result;
        }else{
            $result1 = DB::table('tpv_cartaporte')
                        ->insertGetId([
                            'idprediction'=>$request->id,
                            'serie'=>$request->serie,
                            'folio'=>$request->folio,
                            'id_cat_vehiculo'=>$request->vehiculo,
                            'id_tpv_almacen_origen'=>$request->almacenorigen,
                            'id_tpv_almacen_destino'=>$request->almacendestino,
                            'fecha_envio'=>$lib->fechaFormat($request->fechasalida,'H2M'),
                            'fecha_llegada'=>$lib->fechaFormat($request->fechallegada,'H2M'),
                            'id_cat_operador'=>$request->operador,
                            'distancia'=>$request->distancia,
                            'pesobruto'=>$request->pesobruto,
                            'tipopermisosct'=>$request->tipopermiso,
                            'permisosct'=>$request->numpermiso,
                            'fecha'=>date('Y-m-d'),
                            'hora'=>date('H:i:s'),
                            'uuid'=>$request->uuid,
                            'conexion'=>$conexion
                        ]);
            if($result1>0){
                //$result2 = DB::table('sys_empresa')->where('rfc',$conexion)->increment('folio');
                DB::commit();
                return $result1;
            }else{
                DB::rollBack();
                return 'Problemas al guardar la Carta Porte. Contacte con el administrador del sistema.';
            }
        }
    }

    public function checkMatRiesSAT($clavesat){
        $result = DB::table('sat_productos')
                    ->where('id','=',$clavesat)
                    ->first();
        if(isset($result->materialpeligroso)){
            if(trim($result->materialpeligroso)=='1'){
                return 1;
            }else{
                if(trim($result->materialpeligroso)=='0,1'){
                    return .5;
                }else{
                    return 0;
                }
            }
        }else{
            return -1;
        }
    }


    public function getAllUsoCfdi() {
        $result = DB::table('sat_usocfdi')
                    ->where('status', 1)
                    ->get();
        if(count($result)>0) 
            return $result;
        else 
            return 0;
    }

    public function getRegimenFiscal(){
        $result = DB::table('sat_regimenfiscal')
                    ->select(DB::raw("clave,descripcion"))
                    ->where('status','=',1)
                    ->get();
        return $result;
    }

    

    public function getRegimenFiscalClave($clave){
        $result = DB::table('sat_regimenfiscal')
                    ->select(DB::raw("clave,descripcion"))
                    ->where('clave','=',$clave)
                    ->first();
        return $result;
    }

    public function datosEmisor($rfc) {
        $result = DB::table('sys_empresa')
                    ->where('rfc',$rfc)
                    ->first();
        return $result;
    }

    public function getFolioCAP($conexion){
        $result = DB::table('tpv_cartaporte')
                    ->where('conexion',$conexion)
                    ->max('folio');
        //dd($result,$conexion);
        if($result===null){
            return 1;
        }else{
            $newfolio = $result + 1;
            return $newfolio;
        }
    }

    public function folioFG(){
        $result = DB::table('tpv_factura')
                    ->where('serie','FG')
                    ->max('folio');
        $newfolio = $result + 1;
        return $newfolio;
    }

    public function folioFP(){
        $result = DB::table('tpv_factura')
                    ->where('serie','FP')
                    ->max('folio');
        $newfolio = $result + 1;
        return $newfolio;
    }

    public function getRemisionesPrediction($fecini,$fecfin,$folio,$cliente,$tipo,$almacen,$facturaindividual,$montode,$montohasta){
        $cliente>0?$ifcliente='=':$ifcliente='like';
        $almacen>0?$ifalmacen='=':$ifalmacen='like';
       if($facturaindividual==1){
            $folio = $folio;
            $iffolio = '=';
        }else{
            $folio = '%'.$folio.'%';
            $iffolio = 'like';
        }
        if($montode>0){
            if($montohasta>0){
                $cantidades = "REF_PEDIDOSPRESUP.TOTAL>=".$montode." AND REF_PEDIDOSPRESUP.TOTAL<=".$montohasta;
            }else{
                $cantidades = "REF_PEDIDOSPRESUP.TOTAL>=".$montode;
            }
        }else{
            if($montohasta>0){
                $cantidades = "REF_PEDIDOSPRESUP.TOTAL<=".$montohasta;
            }else{
                $cantidades = "1=1";
            }
        }
        $result = DB::connection('firebird')
                    ->table('REF_PEDIDOSPRESUP')
                    ->join('CRM_PROSPECTOS','REF_PEDIDOSPRESUP.FK1MCRM_PROSPECTOS','=','CRM_PROSPECTOS.ID_PROSPECTO')
                    ->join('CFG_ALMACENES','REF_PEDIDOSPRESUP.FK1MCFG_ALMACENES','=','CFG_ALMACENES.ID')
                    ->select(DB::raw("REF_PEDIDOSPRESUP.ID as ID,
                                 REF_PEDIDOSPRESUP.FECHA as FECHA,
                                 REF_PEDIDOSPRESUP.NUMDOCTO as FOLIO,
                                 CRM_PROSPECTOS.ID_PROSPECTO as IDCLIENTE,
                                 CRM_PROSPECTOS.PYM_NOMBRE as CLIENTE,
                                 CRM_PROSPECTOS.PYM_RFC as RFC,
                                 CRM_PROSPECTOS.CPCOM as CP,
                                 CRM_PROSPECTOS.EMAILCFDIS as EMAIL,
                                 CFG_ALMACENES.DESCRIPCION as ALMACEN,
                                 CASE REF_PEDIDOSPRESUP.SECCION 
                                    WHEN 'CLIENTES MOST. PUB. CONTADO' THEN 'CONTADO'
                                    WHEN 'CLIENTES MOST. PUB. CREDITO' THEN 'CREDITO'
                                 END as TIPO,
                                 REF_PEDIDOSPRESUP.SUBTOTAL as SUBTOTAL,
                                 REF_PEDIDOSPRESUP.IMPIVA as IMPIVA,
                                 REF_PEDIDOSPRESUP.TOTAL as TOTAL,
                                 REF_PEDIDOSPRESUP.STATUS as STATUS,
                                 (SELECT FIRST 1 FORMAPAGO FROM REF_PEDIDOSPRESUPFORMSPAGS WHERE FK1MREF_PEDIDOSPRESUP=REF_PEDIDOSPRESUP.ID ORDER BY IMPORTE ASC) as FORMAPAGO,
                                 (SELECT FIRST 1 REFERENCIA FROM REF_PEDIDOSPRESUPFORMSPAGS WHERE FK1MREF_PEDIDOSPRESUP=REF_PEDIDOSPRESUP.ID ORDER BY IMPORTE ASC) as REFERENCIA"))
                    ->whereIn('REF_PEDIDOSPRESUP.SECCION',['CLIENTES MOST. PUB. CONTADO','CLIENTES MOST. PUB. CREDITO'])
                    ->whereIn('REF_PEDIDOSPRESUP.STATUS',['PEDIDO EMITIDO','PEDIDO FACTURADO','PEDIDO DEVUELTO'])
                    ->whereRaw("REF_PEDIDOSPRESUP.FECHA between '$fecini' and '$fecfin'")
                    ->where('REF_PEDIDOSPRESUP.FK1MCRM_PROSPECTOS',$ifcliente,$cliente)
                    ->where('REF_PEDIDOSPRESUP.NUMDOCTO',$iffolio,$folio)
                    ->where('REF_PEDIDOSPRESUP.SECCION','=',$tipo)
                    ->where('REF_PEDIDOSPRESUP.FK1MCFG_ALMACENES',$ifalmacen,$almacen)
                    ->whereRaw($cantidades)
                    ->where('REF_PEDIDOSPRESUP.ESPEDLIQAPARTADO', '')
                    ->get();
        return $result;
    }
      
    public function getSerieFolio($id) {
        $result = DB::connection('firebird')
                    ->table('REF_PEDIDOSPRESUP')
                    ->select(DB::raw("NUMDOCTO as FOLIO"))
                    ->where('REF_PEDIDOSPRESUP.ID',$id)
                    ->first();
        return $result;
    }
      
    public function getPeriodicidad() {
        $result = DB::table('sat_periodicidad')
                    ->where('status',1)
                    ->get();
        return $result;
    }
      
    // public function getSerieFolio($id) {
    //     $result = DB::connection('firebird')
    //                 ->table('REF_PEDIDOSPRESUP')
    //                 ->select(DB::raw("(SELECT VALOR FROM CFG_VALORCAMPOSGENERICOS WHERE FK1MCFG_USUARIOS=REF_PEDIDOSPRESUP.FK1MCFG_USUARIOS AND NOMBRECAMPO='SERIEFACTURAMOSTPUBNORMAL') as SERIE,
    //                                   (SELECT VALORNUMERICO FROM CFG_VALORCAMPOSGENERICOS WHERE FK1MCFG_USUARIOS=REF_PEDIDOSPRESUP.FK1MCFG_USUARIOS AND NOMBRECAMPO='CONSECUTIVOFACTURAMOSTPUBNORMAL') as FOLIO"))
    //                 ->where('REF_PEDIDOSPRESUP.ID',$id)
    //                 ->first();
    //     return $result;
    // }

    public function lugarExpedicion($id){
        $result = DB::table('tpv_almacen')
                    ->select('sys_direccion.cp as cp')
                    ->join('sys_direccion','tpv_almacen.id_sys_direccion','=','sys_direccion.id')
                    ->where('tpv_almacen.id_almacenprediction',$id)
                    ->first();
        return $result;
    }
    
    public function seriePedido($id){
        $result = DB::connection('firebird')
                    ->table('CFG_VALORCAMPOSGENERICOS')
                    ->select('SERIE')
                    ->where('NOMBRECAMPO','CONSECUTIVOPEDIDOMOSTPUB')
                    ->where('FK1MCFG_ALMACENES',$id)
                    ->first();
        return $result;
    }
    
    public function getRemision($id){
        $result = DB::connection('firebird')
                    ->table('REF_PEDIDOSPRESUP')
                    ->join('REF_DETPEDIDOSPRESUP','REF_PEDIDOSPRESUP.ID','=','REF_DETPEDIDOSPRESUP.FKPADREF_PEDIDOSPRESUP')
                    ->join('CFG_ARTICULOS','REF_DETPEDIDOSPRESUP.CODIGO','=','CFG_ARTICULOS.CODIGOARTICULO')
                    ->join('CRM_PROSPECTOS','REF_PEDIDOSPRESUP.FK1MCRM_PROSPECTOS','=','CRM_PROSPECTOS.ID_PROSPECTO')
                    ->select(DB::raw("REF_PEDIDOSPRESUP.ID as ID,
                                REF_PEDIDOSPRESUP.FECHA as FECHA,
                                REF_PEDIDOSPRESUP.NUMDOCTO as FOLIO,
                                REF_PEDIDOSPRESUP.FK1MCFG_ALMACENES as IDALMACEN,
                                CRM_PROSPECTOS.ID_PROSPECTO as IDCLIENTE,
                                CRM_PROSPECTOS.PYM_NOMBRE as CLIENTE,
                                CRM_PROSPECTOS.CPCOM as CP,
                                CRM_PROSPECTOS.PYM_RFC as RFC,
                                CASE REF_PEDIDOSPRESUP.SECCION 
                                    WHEN 'CLIENTES MOST. PUB. CONTADO' THEN 'CONTADO'
                                    WHEN 'CLIENTES MOST. PUB. CREDITO' THEN 'CREDITO'
                                END as TIPO,
                                REF_PEDIDOSPRESUP.SUBTOTAL as SUBTOTAL,
                                REF_PEDIDOSPRESUP.IMPIVA as IMPIVA,
                                REF_PEDIDOSPRESUP.TOTAL as TOTAL,
                                (SELECT FIRST 1 FORMAPAGO FROM REF_PEDIDOSPRESUPFORMSPAGS WHERE FK1MREF_PEDIDOSPRESUP=REF_PEDIDOSPRESUP.ID ORDER BY IMPORTE ASC) as FORMAPAGO,                                
                                CASE REF_PEDIDOSPRESUP.SECCION 
                                    WHEN 'CLIENTES MOST. PUB. CONTADO' THEN 'PUE'
                                    WHEN 'CLIENTES MOST. PUB. CREDITO' THEN 'PPD'
                                END as METODOPAGO,
                                REF_DETPEDIDOSPRESUP.CODIGO as CODIGO,
                                REF_DETPEDIDOSPRESUP.CODIGOSAT as CODIGOSAT,
                                REF_DETPEDIDOSPRESUP.UNIDADMEDIDA as UNIDADMEDIDA,
                                REF_DETPEDIDOSPRESUP.CANTIDAD as CANTIDAD,
                                REF_DETPEDIDOSPRESUP.PRECIO as PRECIO,
                                REF_DETPEDIDOSPRESUP.IMPIVA as IMPIVA,
                                REF_DETPEDIDOSPRESUP.IMPORTELINEA as IMPORTE,
                                REF_DETPEDIDOSPRESUP.IMPIVA+REF_DETPEDIDOSPRESUP.IMPORTELINEA as LINEATOTAL,
                                REF_DETPEDIDOSPRESUP.DESCRIPCION as DESCRIPCION"))
                    ->where('REF_PEDIDOSPRESUP.ID',$id)
                    ->get();
                    
        return $result;
    }    

    public function getUsoCFDI($id) {
        $result = DB::table('sat_usocfdi')
                    ->where('id',$id)
                    ->first();
        return $result;
    }   

    public function checaFacturado($folio,$serie,$id){
        $fact = DB::table('tpv_factura')
                ->where('folio',$folio)
                ->where('serie',$serie)
                ->get();
                
        if(isset($fact[0]->folio)){
            foreach($fact as $f){
                $s = DB::connection('firebird')
                        ->table('REF_PEDIDOSPRESUP')
                        ->where('ID', $id)
                        ->first();
                if(isset($s->STATUS)){
                    if($s->STATUS=='PEDIDO EMITIDO'){
                        $updPedido = DB::connection('firebird')
                                        ->table('REF_PEDIDOSPRESUP')
                                        ->where('ID', $id)
                                        ->update(['STATUS' => 'PEDIDO FACTURADO']);
                        if($updPedido>0){
                            return 'Pedido facturado previamente. Actualice la página y busque de nuevo el pedido. Si el problema continúa comuníqueselo al administrador del sistema.';
                        }else{
                            return 'No pudo cambiarse el status del pedido en Prediction. Comuniquelo al administrador del sistema.';
                        }
                    }else{
                        if($s->STATUS=='PEDIDO FACTURADO'){
                            return 'Pedido facturado previamente. Actualice la página y busque de nuevo el pedido. Si el problema continúa comuníqueselo al administrador del sistema.';
                        }else{
                            return 'El status del pedido en prediction no puede actualizarse porque es: '.$s->STATUS.'. Comuniquelo al administrador del sistema.';
                        }
                    }
                }else{
                    return 'No se encontró el pedido en Prediction. Comuniquelo al administrador del sistema.';
                }
            }
        }else{
            return 1;
        }
    }
    
    public function updateFB($id,$seriefolio,$params){
        $exp = explode('T',$params['comprobante']['Fecha']);
        if(!is_array($id)){
            if($id!=0){
                $updPedido = DB::connection('firebird')
                                ->table('REF_PEDIDOSPRESUP')
                                ->where('ID', $id)
                                ->update(['STATUS' => 'PEDIDO FACTURADO']);
                if($updPedido>0){
                    $result3 = DB::table('tpv_factura')
                                ->insert([
                                    'folio'=>$params['comprobante']['Folio'],
                                    'serie'=>$params['comprobante']['Serie'],
                                    'sello'=>$params['comprobante']['Sello'],
                                    'formaDePago'=>$params['comprobante']['FormaPago'],
                                    'noCertificado'=>$params['comprobante']['NoCertificado'],
                                    'certificado'=>$params['comprobante']['Certificado'],
                                    'subtotal'=>$params['comprobante']['SubTotal'],
                                    'descuento'=>$params['comprobante']['Descuento'],
                                    'total'=>$params['comprobante']['Total'],
                                    'tipoDeComprobante'=>$params['comprobante']['TipoDeComprobante'],
                                    'metodoDePago'=>$params['comprobante']['MetodoPago'],
                                    'LugarExpedicion'=>$params['comprobante']['LugarExpedicion'],
                                    'Moneda'=>$params['comprobante']['Moneda'],
                                    'emisorrfc'=>$params['emisor']['Rfc'],
                                    'emisornombre'=>$params['emisor']['Nombre'],
                                    'emisorregimen'=>$params['emisor']['RegimenFiscal'],
                                    'cliente'=>$params['receptor']['Nombre'],
                                    'regimencliente'=>$params['receptor']['RegimenFiscalReceptor'],
                                    'usocfdi'=>$params['receptor']['UsoCFDI'],
                                    'cpcliente'=>$params['receptor']['DomicilioFiscalReceptor'],
                                    'rfccliente'=>$params['receptor']['Rfc'],
                                    'id_tpv_pedido'=>$id,
                                    'fecha'=>$exp[0],
                                    'hora'=>$exp[1],
                                    'UUID'=>$params['timbrado']['UUID'],
                                    'NoCertificadoSAT'=>$params['timbrado']['NoCertificadoSAT'],
                                    'FechaSAT'=>$params['timbrado']['FechaSAT'],
                                    'SelloSAT'=>$params['timbrado']['SelloSAT'],
                                    'SelloCFD'=>$params['timbrado']['SelloCFD'],
                                    'sistema'=>'fb'
                                ]);
                    if($result3>0){
                        return $result3;
                    }else{
                        return 'problemas al crear registro de la factura. Contacte con el administrador del sistema.';
                    }
                }
            }else{
                $result3 = DB::table('tpv_factura')
                            ->insert([
                                'folio'=>$params['comprobante']['Folio'],
                                'serie'=>$params['comprobante']['Serie'],
                                'sello'=>$params['comprobante']['Sello'],
                                'formaDePago'=>$params['comprobante']['FormaPago'],
                                'noCertificado'=>$params['comprobante']['NoCertificado'],
                                'certificado'=>$params['comprobante']['Certificado'],
                                'subtotal'=>$params['comprobante']['SubTotal'],
                                'descuento'=>$params['comprobante']['Descuento'],
                                'total'=>$params['comprobante']['Total'],
                                'tipoDeComprobante'=>$params['comprobante']['TipoDeComprobante'],
                                'metodoDePago'=>$params['comprobante']['MetodoPago'],
                                'LugarExpedicion'=>$params['comprobante']['LugarExpedicion'],
                                'Moneda'=>$params['comprobante']['Moneda'],
                                'emisorrfc'=>$params['emisor']['Rfc'],
                                'emisornombre'=>$params['emisor']['Nombre'],
                                'emisorregimen'=>$params['emisor']['RegimenFiscal'],
                                'cliente'=>$params['receptor']['Nombre'],
                                'regimencliente'=>$params['receptor']['RegimenFiscalReceptor'],
                                'usocfdi'=>$params['receptor']['UsoCFDI'],
                                'cpcliente'=>$params['receptor']['DomicilioFiscalReceptor'],
                                'rfccliente'=>$params['receptor']['Rfc'],
                                'id_tpv_pedido'=>$id,
                                'fecha'=>$exp[0],
                                'hora'=>$exp[1],
                                'UUID'=>$params['timbrado']['UUID'],
                                'NoCertificadoSAT'=>$params['timbrado']['NoCertificadoSAT'],
                                'FechaSAT'=>$params['timbrado']['FechaSAT'],
                                'SelloSAT'=>$params['timbrado']['SelloSAT'],
                                'SelloCFD'=>$params['timbrado']['SelloCFD'],
                                'sistema'=>'erp'
                            ]);
                if($result3>0){
                    return $result3;
                }else{
                    return 'problemas al crear registro de la factura. Contacte con el administrador del sistema.';
                }
            }
        }else{
            $foliosError = '';
            $foliosOk = '';
            foreach($id as $ticket){
                $updPedido = DB::connection('firebird')
                                ->table('REF_PEDIDOSPRESUP')
                                ->where('ID', $ticket['ID'])
                                ->update(['STATUS' => 'PEDIDO FACTURADO','DESCRIPCIONARTTPV'=>$seriefolio]);
                if($updPedido>0){
                    $foliosOk.= $ticket['FOLIO'].',';
                }else{
                    $foliosError.= $ticket['FOLIO'].', ';
                }
            }            
            $foliosOk = substr($foliosOk,0,-1);
            $foliosError = substr($foliosError,0,-2);
            if($foliosError==''){
                $result3 = DB::table('tpv_factura')
                            ->insert([
                                'folio'=>$params['comprobante']['Folio'],
                                'serie'=>$params['comprobante']['Serie'],
                                'sello'=>$params['comprobante']['Sello'],
                                'formaDePago'=>$params['comprobante']['FormaPago'],
                                'noCertificado'=>$params['comprobante']['NoCertificado'],
                                'certificado'=>$params['comprobante']['Certificado'],
                                'subtotal'=>$params['comprobante']['SubTotal'],
                                'descuento'=>$params['comprobante']['Descuento'],
                                'total'=>$params['comprobante']['Total'],
                                'tipoDeComprobante'=>$params['comprobante']['TipoDeComprobante'],
                                'metodoDePago'=>$params['comprobante']['MetodoPago'],
                                'LugarExpedicion'=>$params['comprobante']['LugarExpedicion'],
                                'Moneda'=>$params['comprobante']['Moneda'],
                                'emisorrfc'=>$params['emisor']['Rfc'],
                                'emisornombre'=>$params['emisor']['Nombre'],
                                'emisorregimen'=>$params['emisor']['RegimenFiscal'],
                                'cliente'=>$params['receptor']['Nombre'],
                                'regimencliente'=>$params['receptor']['RegimenFiscalReceptor'],
                                'usocfdi'=>$params['receptor']['UsoCFDI'],
                                'cpcliente'=>$params['receptor']['DomicilioFiscalReceptor'],
                                'rfccliente'=>$params['receptor']['Rfc'],
                                'idsprediction'=>$foliosOk,
                                'fecha'=>$exp[0],
                                'hora'=>$exp[1],
                                'UUID'=>$params['timbrado']['UUID'],
                                'NoCertificadoSAT'=>$params['timbrado']['NoCertificadoSAT'],
                                'FechaSAT'=>$params['timbrado']['FechaSAT'],
                                'SelloSAT'=>$params['timbrado']['SelloSAT'],
                                'SelloCFD'=>$params['timbrado']['SelloCFD'],
                                'sistema'=>'fb'
                            ]);
                if($result3>0){                    
                    return 1;
                }else{
                    return 'Problemas al insertar registro en tpv_factura.';
                }
            }else{
                return 'Problemas al actualizar la información de los folios: '.$foliosError;
            }
        }
    }
    
    public function getCartaPorte($id){
        $result = DB::table('tpv_cartaporte')
                    ->where('idprediction',$id)
                    ->first();
                    
        return $result;
    }   
    
    public function getAlmacenDireccion($id){
        $result = DB::table('tpv_almacen')
                        ->select(DB::raw("sys_direccion.*"))
                        ->join('sys_direccion','tpv_almacen.id_sys_direccion','sys_direccion.id')
                        ->where('tpv_almacen.id_almacenprediction','=',$id)
                        ->where('tpv_almacen.status',1)
                        ->first();
        //dd($result);           
        return $result;
    }   
    
    public function updateCartaPorte($id,$seriefolio,$params,$usuario){
        DB::beginTransaction();
        $exp = explode('T',$params['comprobante']['Fecha']);
        $result3 = DB::table('tpv_factura')
                    ->insert([
                        'folio'=>$params['comprobante']['Folio'],
                        'serie'=>$params['comprobante']['Serie'],
                        'sello'=>$params['comprobante']['Sello'],
                        'formaDePago'=>$params['comprobante']['FormaPago'],
                        'noCertificado'=>$params['comprobante']['NoCertificado'],
                        'certificado'=>$params['comprobante']['Certificado'],
                        'subtotal'=>$params['comprobante']['SubTotal'],
                        'descuento'=>$params['comprobante']['Descuento'],
                        'total'=>$params['comprobante']['Total'],
                        'tipoDeComprobante'=>$params['comprobante']['TipoDeComprobante'],
                        'metodoDePago'=>$params['comprobante']['MetodoPago'],
                        'LugarExpedicion'=>$params['comprobante']['LugarExpedicion'],
                        'Moneda'=>$params['comprobante']['Moneda'],
                        'emisorrfc'=>$params['emisor']['Rfc'],
                        'emisornombre'=>$params['emisor']['Nombre'],
                        'emisorregimen'=>$params['emisor']['RegimenFiscal'],
                        'cliente'=>$params['receptor']['Nombre'],
                        'regimencliente'=>$params['receptor']['RegimenFiscalReceptor'],
                        'usocfdi'=>$params['receptor']['UsoCFDI'],
                        'cpcliente'=>$params['receptor']['DomicilioFiscalReceptor'],
                        'rfccliente'=>$params['receptor']['Rfc'],
                        'id_tpv_traspaso'=>$id,
                        'fecha'=>$exp[0],
                        'hora'=>$exp[1],
                        'UUID'=>$params['timbrado']['UUID'],
                        'NoCertificadoSAT'=>$params['timbrado']['NoCertificadoSAT'],
                        'FechaSAT'=>$params['timbrado']['FechaSAT'],
                        'SelloSAT'=>$params['timbrado']['SelloSAT'],
                        'SelloCFD'=>$params['timbrado']['SelloCFD'],
                        'sistema'=>'erp'
                    ]);
        if($result3>0){
            DB::commit();
            return $result3;
        }else{
            DB::rollBack();
            return 'problemas al crear registro de la factura. Contacte con el administrador del sistema.';
        }
    }

    public function getRemisionPrediction($folio) {
        $result = DB::connection('firebird')
                    ->table('REF_PEDIDOSPRESUP')
                    ->join('CRM_PROSPECTOS','REF_PEDIDOSPRESUP.FK1MCRM_PROSPECTOS','=','CRM_PROSPECTOS.ID_PROSPECTO')
                    ->join('CFG_ALMACENES','REF_PEDIDOSPRESUP.FK1MCFG_ALMACENES','=','CFG_ALMACENES.ID')
                    ->select(DB::raw("REF_PEDIDOSPRESUP.ID as ID,
                                 REF_PEDIDOSPRESUP.FECHA as FECHA,
                                 REF_PEDIDOSPRESUP.NUMDOCTO as FOLIO,
                                 CRM_PROSPECTOS.ID_PROSPECTO as IDCLIENTE,
                                 CRM_PROSPECTOS.PYM_NOMBRE as CLIENTE,
                                 CRM_PROSPECTOS.EMAILCFDIS as EMAIL,
                                 CFG_ALMACENES.DESCRIPCION as ALMACEN,
                                 CASE REF_PEDIDOSPRESUP.SECCION 
                                    WHEN 'CLIENTES MOST. PUB. CONTADO' THEN 'CONTADO'
                                    WHEN 'CLIENTES MOST. PUB. CREDITO' THEN 'CREDITO'
                                 END as TIPO,
                                 REF_PEDIDOSPRESUP.SUBTOTAL as SUBTOTAL,
                                 REF_PEDIDOSPRESUP.IMPIVA as IMPIVA,
                                 REF_PEDIDOSPRESUP.TOTAL as TOTAL,
                                 REF_PEDIDOSPRESUP.STATUS as STATUS,
                                 (SELECT FIRST 1 FORMAPAGO FROM REF_PEDIDOSPRESUPFORMSPAGS WHERE FK1MREF_PEDIDOSPRESUP=REF_PEDIDOSPRESUP.ID ORDER BY IMPORTE DESC) as FORMAPAGO"))
                    ->whereIn('REF_PEDIDOSPRESUP.SECCION',['CLIENTES MOST. PUB. CONTADO','CLIENTES MOST. PUB. CREDITO'])
                    ->whereIn('REF_PEDIDOSPRESUP.STATUS',['PEDIDO EMITIDO','PEDIDO FACTURADO','PEDIDO DEVUELTO'])
                    ->where('REF_PEDIDOSPRESUP.NUMDOCTO', $folio)
                    //->where('REF_PEDIDOSPRESUP.ID', 193839)
                    ->get();
        
        return $result;
    }
    
    public function cancelaFacturaPrediction($folio){
        $chckGlobal = DB::connection('firebird')
                        ->table('REF_PEDIDOSPRESUP')
                        ->where('NUMDOCTO', $folio)
                        ->where('DESCRIPCIONARTTPV','')
                        ->first();
        if(isset($chckGlobal->ID)){
            $updPedido = DB::connection('firebird')
                            ->table('REF_PEDIDOSPRESUP')
                            ->where('NUMDOCTO', $folio)
                            ->update(['STATUS' => 'PEDIDO EMITIDO']);
            if($updPedido>0)
                return $updPedido;
            else
                return 'Problemas al actualizar el status en Prediction. Comuníquelo con el administrador del sistema.';
        }else{
            return 'Venta facturada en la Global';
        }
    }
    
    public function quitaItem($request){
        $update = DB::table($request->tabla)
                        ->where('id', $request->id)
                        ->update([
                            'status'=>99
                        ]);
        if($update>0){
            return 1;
        }else{
            return 'No se encontro el registro o ya fue quitado previamente.';
        }
    }
    
    public function editaItem($request){
        $data = array();
        if($request->tabla=='cat_vehiculo'){
            $data['descripcion'] = $request->descripcion;
            $data['modelo'] = $request->modelo;
            $data['placa'] = $request->placa;
            $data['peso'] = $request->peso;
            $data['aseguradora'] = $request->aseguradora;
            $data['poliza'] = $request->poliza;
            $data['id_sat_configvehicular'] = $request->id_sat_configvehicular;
            $update = DB::table($request->tabla)
                            ->where('id', $request->id)
                            ->update($data);
        }
        if($request->tabla=='cat_operador'){
            $data['nombre'] = $request->nombre;
            $data['licencia'] = $request->licencia;
            $data['rfc'] = $request->rfc;
            $data['id_sat_tipofigura'] = $request->id_sat_tipofigura;
            $update = DB::table($request->tabla)
                            ->where('id', $request->id)
                            ->update($data);
        }
        if($request->tabla=='tpv_almacen'){
            //obtenemos el id de la direccion
            $iddir = DB::table('tpv_almacen')
                    ->where('id',$request->id)
                    ->first();
            $update = DB::table('sys_direccion')
                        ->where('id',$iddir->id_sys_direccion)
                        ->update([
                            'calle'=>$request->calle,
                            'numexterior'=>$request->numexterior,
                            'cp'=>$request->cp,
                            'pais'=>$request->pais,
                            'estado'=>$request->estado,
                            'municipio'=>$request->municipio,
                            'localidad'=>$request->localidad,
                            'colonia'=>$request->colonia
                        ]);
            
        }
        if($update>=0){
            return 1;
        }else{
            return 'Ocurrio un problema al editar el registro.';
        }
    }
    
    public function getItem($request){
        if($request->tabla=='tpv_almacen'){
            $result = DB::table('tpv_almacen')
                        ->select(DB::raw("sys_direccion.*,
                                        tpv_almacen.id_almacenprediction as id_almacenprediction,
                                        tpv_almacen.id as id"))
                        ->join('sys_direccion','tpv_almacen.id_sys_direccion','sys_direccion.id')
                        ->where('tpv_almacen.id','=',$request->id)
                        ->first();
        }else{
            $result = DB::table($request->tabla)
                            ->where('id', $request->id)
                            ->first();
        }
        return $result;
    }
}

?>