<?php
//
// ** Classe de variáveis e funções globais de trabalho do sistema **
//
CLASS Global_do_Sistema {
  public  $sRetornoMod_TipM = 'text/plain';     // Tipo mime da retorno (Ex: 'text/html', 'image/png', 'text/plain', 'application/x-compressed', ...)
  public  $aSim_Cad_Empresa = [];               // Cadastro da empresa no Simdesk da Simsoft
  public  $nSim_Emp_CodigoI = 0;                // Código da empresa no simdesk da Simsoft
  public  $nCaptura_Emp_Err = 0;                // Código do erro ao capturar dados da empresa
  public  $nQtd_Terminais_S = 0;                // Quantidade de terminais com aplicativo autorizado no Simdesk da Simsoft
  public  $aSessao_Terminal = [];               // Dados da sessão do terminal
  public  $bRetornoMod_Down = False;            // Forçar download com o retorno?
  public  $sRetornoMod_Bina = '';               // Resposta de retorno no formato binário
  public  $aRetornoMod_JSon = Null;             // Resposta de retorno no formato JSon
  public  $sMsg_Erro_Geral_ = '';               // Mensagem de retorno de erro no módulo
  public  $aDados_Recebidos = Null;             // Dados recebidos na requisição da chamada
  public  $aDados_Receb_RAW = Null;             // Dados recebidos na requisição modo puro
  public  $bDados_Recb_JSon = False;            // Dados recebidos em JSon
  public  $bMetodo_Req_POST = False;            // Foi pelo método de requisição POST da estação ?
  public  $bRequisicao_Segs = False;            // A requisição da estação foi com segurança HTTPS ?
  public  $sNumeroIP_Remoto = '';               // IP da estação que requisitou a conexão
  public  $sCaminho_Origina = '';               // Caminho original do script PHP
  public  $sModulo_Pri      = '';               // Chamado do módulo principal
  public  $sModulo_Act      = '';               // Chamado da ação no módulo
  public  $nDtHr_Cronometro = Null;             // Marcação de tempo para calculo de tempo consumido
  public  $sLogInfo_Arquivo = '';               // Caminho do arquivo para gravar loginfo
  public  $nLogInfo_Qtd_Rmv = 0;                // Quantidade de arquivos removidos
  public  $nLogInfo_DiasMax = 15;               // Quantidade máxima em dias que os arquivos do log permanecem
  //
  private $n_Codigo_do_Erro = 0;                // Código do erro de retorno
  public  $aLista_de_Erros =                    // Lista de erros
    // Código do erro  |  Mensagem do erro                                          | Código de retorno HTTP 
    [        1      => [ 'Erro desconhecido'                                                            , 501 ],
           100      => [ 'Módulo nao encontrado'                                                        , 0   ],
           101      => [ 'Acao desconhecida'                                                            , 0   ],
           138      => [ 'Empresa do token diferente da empresa informada'                              , 0   ],
           139      => [ 'Token desconhecido'                                                           , 0   ],
           140      => [ 'Empresa sem o Aplicativo (eEntregas) no Cad.de Clientes-Simdesk'              , 0   ],
           145      => [ 'Chave de sessao invalida'                                                     , 0   ],
           146      => [ 'Terminal nao autorizado'                                                      , 0   ],
           147      => [ 'Terminal nao encontrado'                                                      , 0   ],
           148      => [ 'E necessario que um operador esteja logado neste terminal'                    , 0   ],
           149      => [ 'Quantidade de terminais á autorizar acima do que está cadastrado no Simdesk'  , 0   ],
           150      => [ 'Faltando dados Obrigatorios: Token ou ID Celular ou Identificação do Celular' , 0   ],
           151      => [ 'O tipo do terminal é incompatível com a operação'                             , 0   ],
           200      => [ 'Lista de itens esta ausente no pedido'                                        , 0   ],
           201      => [ 'Pedido com codigo de referencia ausente'                                      , 0   ]
    ];
  //
  function __construct() {
    //
  }
  function __destruct() {
    //
  }
  // -- Reportar erro ao sistema --
  function Reportar_Erro( $nPm_Codigo_do_Erro = -1 ) {
     if ( $nPm_Codigo_do_Erro >= 0 ) {
        if ( ISSET( $this->aLista_de_Erros[$nPm_Codigo_do_Erro] ) ) {
          $this->n_Codigo_do_Erro = $nPm_Codigo_do_Erro;
        } else {
          $this->n_Codigo_do_Erro = 1;
        }
     }
     return $this->n_Codigo_do_Erro;
  }
  // -- Capturar dados recebidos do terminal e informações sobre a requisição --
  function Capturar_Dados_Recebidos() {
     //
     $this->aDados_Receb_RAW = @FILE_GET_CONTENTS('php://input');
     $aJson = @JSON_DECODE( $this->aDados_Receb_RAW, True);
     $this->bDados_Recb_JSon = False;
     $this->aDados_Recebidos = $_POST;            // Conteúdo no post sendo capturado para a variável padronizada
     If ( COUNT($aJson)>0 ) {
        $this->aDados_Recebidos = $aJson;         // Conteúdo do formato JSon já convertido em matriz
        $this->bDados_Recb_JSon = True;
     }
     //
     $sRcb_Comando = @$this->aDados_Recebidos['Cmd'];
     $aRcb_Comando = explode('.',$sRcb_Comando);
     $this->sModulo_Pri = @$aRcb_Comando[0];
     $this->sModulo_Act = @$aRcb_Comando[1];
     //
     if ( ISSET( $this->aDados_Recebidos['Cmd'] ) ) {  UNSET($this->aDados_Recebidos['Cmd']);  }
     //
     $this->bMetodo_Req_POST = (strtoupper(@$_SERVER['REQUEST_METHOD'])=='POST');
     $this->bRequisicao_Segs = (strtoupper(@$_SERVER['HTTPS'])=='ON');
     $this->sNumeroIP_Remoto = ObterIPdoCliente();
     $this->sCaminho_Origina = (@$_SERVER['PHP_SELF']);
     //
  }
  // -- Capturar dados da empresa e conferir se a empresa possui o aplicativo no seu cadastro no Simdesk --
  function Capturar_Dados_Empresa_Simdesk( $nCli_CodigoInt = 0, $sChave_Empresa = '' ) {
    If ( $nCli_CodigoInt>0 ) {
      $this->nSim_Emp_CodigoI = $nCli_CodigoInt;
    } Else {
      $this->nSim_Emp_CodigoI = 0;
      If ( ! empty( $this->aDados_Recebidos['CODIGO_EMPRESA'] ) ) {
        $this->nSim_Emp_CodigoI = Somente_Numeros( $this->aDados_Recebidos['CODIGO_EMPRESA'] )+0;
      }
    }
    //
    $aCad_Empresa_Cod = [];
    If ( $nCli_CodigoInt>0 && (! EMPTY($sChave_Empresa) ) ) {
      $aCad_Empresa_Cod = P_SQL_Simdesk_CadCli( $this->nSim_Emp_CodigoI );
      $aCad_Empresa_Chv = P_SQL_Simdesk_CadCli( 0, $sChave_Empresa );
      If ( EMPTY($aCad_Empresa_Cod) ) {         // Não encontrou a empresa pelo código
        $this->nCaptura_Emp_Err = 139;
        return false;
        //
      } ElseIf ( EMPTY($aCad_Empresa_Chv) ) {   // Não encontrou a empresa pelo token
        $this->nCaptura_Emp_Err = 139;
        return false;
        //
      } Else {
        If ( (@$aCad_Empresa_Cod['CLI_CODIGO']+0) != (@$aCad_Empresa_Chv['CLI_CODIGO']+0) ) {
          $this->nCaptura_Emp_Err = 138;        // Empresa do token diferente da empresa informada
          return false;
        }
      }
    }
    //
    If ( EMPTY($aCad_Empresa_Cod) ) {
      $aCad_Empresa = P_SQL_Simdesk_CadCli( $this->nSim_Emp_CodigoI, $sChave_Empresa );
    } Else {
      $aCad_Empresa = $aCad_Empresa_Cod;
    }
    //
    If ( EMPTY($aCad_Empresa) ) {
      $this->aSim_Cad_Empresa = [];
      $this->nSim_Emp_CodigoI = 0;
      If ( EMPTY($sChave_Empresa) ) {
        $this->nCaptura_Emp_Err = 140;
      } Else {
        $this->nCaptura_Emp_Err = 139;
      }
      return false;
    }
    $nPos_Apl_Lst = strpos( ' |'.@$aCad_Empresa['CLI_APLLST'] , '|'.CodigoAppSimsoft.':' );
    If (   (@$aCad_Empresa['CLI_ATIVO_']+0) < 1                                                  // Se a empresa estiver ativa
        OR (@$aCad_Empresa['CLI_BLOQUEADO']+0) > 0                                               // Se a empresa estiver como bloqueada
        OR $nPos_Apl_Lst == 0                                                                    // Se o aplicativo estiver no cadastro
       ) {
      $this->aSim_Cad_Empresa = [];
      $this->nSim_Emp_CodigoI = 0;
      $this->nCaptura_Emp_Err = 140;
      return false;
    }
    $this->aSim_Cad_Empresa = $aCad_Empresa;
    $this->nSim_Emp_CodigoI = $aCad_Empresa['CLI_CODIGO']+0;
    $this->Registrar_LogInfo( 1 );
    //
    $sQtd_Terminais_S = substr( @$aCad_Empresa['CLI_APLLST'], $nPos_Apl_Lst, 25);
    $nPos_Apl_Lst = strpos( $sQtd_Terminais_S, ':' )+1;
    $sQtd_Terminais_S = substr( $sQtd_Terminais_S, $nPos_Apl_Lst );
    $nPos_Apl_Lst = strpos( $sQtd_Terminais_S, '|' );
    $sQtd_Terminais_S = substr( $sQtd_Terminais_S, 0, $nPos_Apl_Lst );
    $this->nQtd_Terminais_S = $sQtd_Terminais_S+0;
    //
    return true;
  }
  // -- Capturar dados da sessão do terminal móvel --
  function Capturar_Dados_Sessao_Terminal( $nTrm_Num_Tipo_ = 0 ) {
    $sChv_Sessao_Empresa = @$this->aDados_Recebidos['CHAVE_EMP_SESSAO'];
    $aChv_Sessao_Empresa = explode('.',$sChv_Sessao_Empresa);
    $sChave_Empresa = @$aChv_Sessao_Empresa[0];
    $sChave_Sessao  = @$aChv_Sessao_Empresa[1];
    //
    If (   EMPTY($sChv_Sessao_Empresa)
        OR EMPTY($sChave_Empresa)
        OR EMPTY($sChave_Sessao)
       ) {
      return 150;   // Campos obrigatório faltando
    }
    //
    If ( ! $this->Capturar_Dados_Empresa_Simdesk( 0, $sChave_Empresa ) ) {
      return $this->nCaptura_Emp_Err;
    }
    //
    $aReg_Terminal = P_SQL_Reg_Terminais( $this->nSim_Emp_CodigoI, 0, '', $sChave_Sessao );
    If ( empty($aReg_Terminal) ) {
      return 145;  // Chave de sessão inválida
    }
    $aReg_Terminal = $aReg_Terminal[0];
    //
    If ( $nTrm_Num_Tipo_ != (@$aReg_Terminal['TRM_NUM_TIPO_']+0) ) {
      return 151;  // O tipo do terminal é incompatível com a operação
    }
    //
    if ( ConvertDtHrSTR($aReg_Terminal['TRM_DTHR_ATRZ']) < mktime(0,0,0,1,1,2017) ) {
      return 146;  // Terminal não autorizado
    }
    //
    $sSQLQuery =
      'UPDATE '.
        'reg_terminal '.
      'SET '.
        'TRM_ACESSO_DH = NOW(),'.
        'TRM_ACESSO_IP = '.SQL_Bin( Converter_IPv4($this->sNumeroIP_Remoto,0) ).' '.
      'WHERE TRM_CODIGOINT='.$aReg_Terminal['TRM_CODIGOINT'].' '.
      ';';
    SQL_Query( $sSQLQuery );
    //
    $bOperador_Logado =
      (    (@$aReg_Terminal['TRM_IOPE_LOGN']+0) > 0
        && ConvertDtHrSTR($aReg_Terminal['TRM_ACESSO_DH']) > 0
        && ConvertDtHrSTR($aReg_Terminal['TRM_DTHR_LOGN']) > 0
        && ConvertDtHrSTR($aReg_Terminal['TRM_FIMACS_DH']) == 0
      );
    $this->aSessao_Terminal =
      [ 'Trm_Id_Device'   =>  @$aReg_Terminal['TRM_ID_INDICE'],
        'Trm_Nome_Rotulo' =>  @$aReg_Terminal['TRM_DC_ROTULO'],
        'Trm_CodigoInt'   =>  @$aReg_Terminal['TRM_CODIGOINT'],
        'Trm_CodigoAtv'   => (@$aReg_Terminal['TRM_CODIGOATV']+0),
        'Operador_Indice' => (@$aReg_Terminal['TRM_IOPE_LOGN']+0),
        'Operador_Logado' => $bOperador_Logado
      ];
    //
    $this->Registrar_LogInfo( 2 );
    //
    return 0;
  }
  //
  // -- Registrar informações de comunicação Log --
  function Registrar_LogInfo( $nFase_Com = 0 ) {
    If ( ! defined('Diretorio_LogInfo') ) { return false; }
    $sPularLinha = CHR(13).CHR(10);
    //
    // -- Fase inicial : requisição --
    If ( $nFase_Com == 0 ) {
      If ( defined('Q_DiasMax_InfoLog') ) {
        $this->nLogInfo_DiasMax = Q_DiasMax_InfoLog;
      }
      $this->Limpar_LogInfo( '', $this->nLogInfo_DiasMax );
      //
      $this->nDtHr_Cronometro = microtime(true);
      $dData_Hora_Real = TIME();
      $sDir_Trabalho = Diretorio_LogInfo;
      if ( ! is_dir( $sDir_Trabalho ) ) {  mkdir( $sDir_Trabalho );  }
      //
      If ( ! EMPTY($this->sModulo_Pri.$this->sModulo_Act) ) {
        //
        $sDir_Trabalho .= '/'.strtoupper($this->sModulo_Pri).'.'.strtoupper($this->sModulo_Act);
        if ( ! is_dir( $sDir_Trabalho ) ) {  mkdir( $sDir_Trabalho );  }
        //
      } else {
        $sDir_Trabalho .= '/Sem_Comando';
        if ( ! is_dir( $sDir_Trabalho ) ) {  mkdir( $sDir_Trabalho );  }
      }
      //
      $sDir_Trabalho .= '/'.DATE("Y-m-d");
      if ( ! is_dir( $sDir_Trabalho ) ) {  mkdir( $sDir_Trabalho );  }
      //
      if ( ! is_dir( $sDir_Trabalho ) ) {
        return false;
      }
      //
      for ( $nContador=0; $nContador <= 100 ; $nContador++ ) { 
        $this->sLogInfo_Arquivo = $sDir_Trabalho.'/'.DATE("H-i-s",$dData_Hora_Real).'_'.Str_Zero($nContador,3).'.txt';
        If ( ! file_exists($this->sLogInfo_Arquivo) ) {  break;  }
      }
      //
      $sLog_Texto =
        '--- REQUISICAO ----'.$sPularLinha.
        'Data e hora........: '.DATE( "d/m/Y H:i:s", $dData_Hora_Real ).$sPularLinha.
        'Versão API ........: v'.Aplicativo_Versao_Major.' - '.Aplicativo_Versao.$sPularLinha.
        ( $this->nLogInfo_Qtd_Rmv > 0 ?
        'Qtd log removidos..: '.$this->nLogInfo_Qtd_Rmv.$sPularLinha
        : '' ).
        'IP.................: '.$this->sNumeroIP_Remoto.$sPularLinha.
        'Metodo POST........: '.( $this->bMetodo_Req_POST ? 'Sim' : 'Não' ).$sPularLinha.
        ( $this->bDados_Recb_JSon ?
        'Recebidos em JSon..: '.VAR_EXPORT( $this->aDados_Recebidos, True )
        :
        'Dados recebidos ...: '.$this->aDados_Receb_RAW
        ).$sPularLinha.
        '';
      //
      $hLogInfoArq = FOPEN( $this->sLogInfo_Arquivo, 'a+' );
      FWRITE( $hLogInfoArq, $sLog_Texto );
      FCLOSE( $hLogInfoArq );
      //
      set_error_handler( "Registrar_LogInfo_Tratar_Erros" );
      error_reporting( E_ALL );
      //
    }
    //
    // -- Fase: Empresa identificada --
    If ( $nFase_Com == 1 ) {
      //
      $sLog_Texto =
        '------ DADOS ------'.$sPularLinha.
        'Empresa na Simsoft.: '.$this->aSim_Cad_Empresa['CLI_CODIGO'].' - '.$this->aSim_Cad_Empresa['CLI_FANTAS'].
        $sPularLinha;
      //
      $hLogInfoArq = FOPEN( $this->sLogInfo_Arquivo, 'a+' );
      FWRITE( $hLogInfoArq, $sLog_Texto );
      FCLOSE( $hLogInfoArq );
    }
    //
    // -- Fase: Sessão válida e identificada --
    If ( $nFase_Com == 2 ) {
      //
      $sLog_Texto =
        'Sessão do terminal.: '.VAR_EXPORT( $this->aSessao_Terminal, True).
        $sPularLinha;
      //
      $hLogInfoArq = FOPEN( $this->sLogInfo_Arquivo, 'a+' );
      FWRITE( $hLogInfoArq, $sLog_Texto );
      FCLOSE( $hLogInfoArq );
    }
    //
    // -- Fase final : retorno --
    If ( $nFase_Com == 100 ) {
      //
      $nTempo_Consumido_MSec = round( (microtime(true) - $this->nDtHr_Cronometro) * 1000 , 0 );
      //
      $sLog_Texto =
        '----- RETORNO -----'.$sPularLinha.
        'Tempo de consumido.: '.number_format( $nTempo_Consumido_MSec, 0, '','').' microsegundos'.$sPularLinha.
        'Codigo HTTP retorno: '.HTTP_RESPONSE_CODE().$sPularLinha.
        'Formato do retorno.: '.$this->sRetornoMod_TipM.$sPularLinha.
        'Tamanho do retorno.: '.strlen($this->sRetornoMod_Bina).' bytes'.$sPularLinha.
        ( empty( $this->aRetornoMod_JSon ) ? '' :
        'Dados de retorno...: '.VAR_EXPORT( $this->aRetornoMod_JSon, True ).$sPularLinha
        ).
        '------- FIM -------'.$sPularLinha.
        $sPularLinha;
      //
      $hLogInfoArq = FOPEN( $this->sLogInfo_Arquivo, 'a+' );
      FWRITE( $hLogInfoArq, $sLog_Texto );
      FCLOSE( $hLogInfoArq );
    }
    //
  }
  //
  // -- Limpar arquivos de informações de comunicação Log --
  function Limpar_LogInfo( $sDir_Trabalho = '', $nMaxDiasManter = 15 ) {
    $bDir_Trabalho_Limpo = False;
    If ( empty($sDir_Trabalho) ) {
      If ( ! defined('Diretorio_LogInfo') ) {  return false;  }
      $sDir_Trabalho = Diretorio_LogInfo;
      $bDir_Trabalho_Limpo = True;
    }
    //
    if ( ! is_dir( $sDir_Trabalho ) )       {  return false;  }
    //
    If ( $bDir_Trabalho_Limpo ) {
      $sCaminho_Trb = $sDir_Trabalho.'/ultima_limpeza.txt';
      If ( file_exists($sCaminho_Trb) ) {
        $n_DtHr_Arq = FILEMTIME( $sCaminho_Trb );
        If ( $n_DtHr_Arq + (24*60*60) > TIME() ) {  // Efetuar a limpeza no diretório info_log uma vez por dia
          return false;
        }
      }
      $hLogInfoArq = FOPEN( $sCaminho_Trb, 'a' );
      FWRITE( $hLogInfoArq, "Ultima Limpeza : ".DATE("d/m/Y H:i:s") );
      FCLOSE( $hLogInfoArq );
    }
    //
    $aArquivos = scandir( $sDir_Trabalho );
    ForEach ( $aArquivos As $s_Arquivo ) {
      If ( $s_Arquivo=="." OR $s_Arquivo==".." OR $s_Arquivo=='ultima_limpeza.txt' ) {
       continue;
      }
      //
      $sCaminho_Trb = $sDir_Trabalho.'/'.$s_Arquivo;
      $bDiretorio = is_dir( $sCaminho_Trb );
      // -- Se for diretório
      If ( $bDiretorio ) {
        $this->Limpar_LogInfo( $sCaminho_Trb, $nMaxDiasManter );
        $aArquivos_Dir = scandir( $sCaminho_Trb );
        If ( count($aArquivos_Dir) < 3 ) {
          rmdir( $sCaminho_Trb );
        }
        continue;
      }
      // -- Se for arquivo
      $n_DtHr_Arq = FILEMTIME( $sCaminho_Trb );
      If ( $n_DtHr_Arq + ($nMaxDiasManter*24*60*60) < TIME() ) {
        unlink( $sCaminho_Trb );
        $this->nLogInfo_Qtd_Rmv++;
      }
    }
    return true;
    //
  }
//
}
// ** Fim **
//
//
//
//
//
Function Registrar_LogInfo_Tratar_Erros( $errno, $errstr, $errfile, $errline ) {
  Global $aGlobal;
  $sPularLinha = CHR(13).CHR(10);
  //
  If ( error_reporting()==0 ) {
    return true;
  }
  //
  $bEncerrar_PHP = False;
  $sLog_Texto = '';
  switch ($errno) {
    case E_USER_ERROR:
      $sLog_Texto =
        '* ERRO fatal no PHP..: ['.$errno.']'.' arquivo: "'.$errfile.'", linha '.$errline.', PHP '.PHP_VERSION.', OS '.PHP_OS.$sPularLinha.
        '* Dados do Erro PHP..: '.$errstr.$sPularLinha.
        $sPularLinha;
      $bEncerrar_PHP = True;
    break;
    //
    case E_USER_WARNING:
      $sLog_Texto =
        '* Alerta erro no PHP.: ['.$errno.']'.' arquivo: "'.$errfile.'", linha '.$errline.', PHP '.PHP_VERSION.', OS '.PHP_OS.$sPularLinha.
        '* Dados do Erro PHP..: '.$errstr.$sPularLinha;
    break;
    //
    case E_USER_NOTICE:
      $sLog_Texto =
        '* Aviso erro no PHP..: ['.$errno.']'.' arquivo: "'.$errfile.'", linha '.$errline.', PHP '.PHP_VERSION.', OS '.PHP_OS.$sPularLinha.
        '* Dados do Erro PHP..: '.$errstr.$sPularLinha;
    break;
    //
    default:
      $sLog_Texto =
        '* Erro no PHP........: ['.$errno.']'.' arquivo: "'.$errfile.'", linha '.$errline.', PHP '.PHP_VERSION.', OS '.PHP_OS.$sPularLinha.
        '* Dados do Erro PHP..: '.$errstr.$sPularLinha;
    break;
  }
  $hLogInfoArq = FOPEN( $aGlobal->sLogInfo_Arquivo, 'a+' );
  FWRITE( $hLogInfoArq, $sLog_Texto );
  FCLOSE( $hLogInfoArq );
  If ( $bEncerrar_PHP ) {  exit(1);  }
  /* Don't execute PHP internal error handler */
  return true;
}
//
// Retorna o status do pedido
Function Capturar_Status_Pedido( $aFtg, $bStatus_Capturado = False ) {
  $sStatus_Pedido = 'DISPONIVEL';
  $nFat_Mz_CodSim = @$aFtg['FAT_MZ_CODSIM']+0;
  $dFat_Dh_FilAct = ConvertDtHrSTR( @$aFtg['FAT_DH_FILACT'] );
  $dFat_Dh_HabEnt = ConvertDtHrSTR( @$aFtg['FAT_DH_HABENT'] );
  $dFat_Dh_Captur = ConvertDtHrSTR( @$aFtg['FAT_DH_CAPTUR'] );
  $dFat_Dh_Aceito = ConvertDtHrSTR( @$aFtg['FAT_DH_ACEITO'] );
  $dFat_Dh_Retira = ConvertDtHrSTR( @$aFtg['FAT_DH_RETIRA'] );
  $dFat_Dh_Entreg = ConvertDtHrSTR( @$aFtg['FAT_DH_ENTREG'] );
  $dFat_Dh_Recusa = ConvertDtHrSTR( @$aFtg['FAT_DH_RECUSA'] );
  $dFat_Dh_Finali = ConvertDtHrSTR( @$aFtg['FAT_DH_FINALI'] );
  If ( $bStatus_Capturado && $nFat_Mz_CodSim>0 ) {
    $sStatus_Pedido = 'NAO_IMPORTADO';
    If ( $dFat_Dh_Captur > 0 ) {
      $sStatus_Pedido = 'IMPORTADO';
    }
    If ( $dFat_Dh_FilAct > 0 ) {
      $sStatus_Pedido = 'FILIAL_ACEITOU';
    }
    If ( $dFat_Dh_HabEnt > 0 ) {
      $sStatus_Pedido = 'DISPONIVEL';
    }
  }
  If ( $dFat_Dh_Aceito > 0 ) {
    $sStatus_Pedido = 'ACEITO';
   //If ( $dFat_Dh_Retira > 0 ) {
      //$sStatus_Pedido = 'COLETADO';
      If ( $dFat_Dh_Entreg > 0 ) {
        $sStatus_Pedido = 'ENTREGUE';
      }
   //}
  }
  If ( $dFat_Dh_Recusa > 0 ) {
    $sStatus_Pedido = 'RECUSADO';
  }
  If ( $dFat_Dh_Finali > 0 ) {
    $sStatus_Pedido = 'FINALIZADO';
  }
  return $sStatus_Pedido;
}
//
//
// Deixa todas as palavras do em texto com a primeira letra maiuscula
Function StrMaiusculas($sTexto) {
   $aTexto = EXPLODE(' ',$sTexto);
   $sRetorna = '';
   ForEach ( $aTexto as $sPalavra ) {
     $s_Palavra = STRTOUPPER($sPalavra);
     If ( $s_Palavra=="DOS" OR $s_Palavra=="DAS" OR $s_Palavra=="DE" OR
	     $s_Palavra=="DO"  OR $s_Palavra=="DA"  OR $s_Palavra=="E"     ) {
        $s_Palavra = STRTOLOWER($s_Palavra);
	  } Else {
        $s_Palavra = STRTOUPPER(SUBSTR($s_Palavra,0,1)).STRTOLOWER(SUBSTR($s_Palavra,1));
	  }
	  $sRetorna .= (STRLEN($sRetorna)>0 ? ' ' : '').$s_Palavra;
   }
   Return $sRetorna;
}
//
// Pegar string por pausas
Function PegarPorPausa($sPegarP_Str,$nPegarQtd=1,$sPorPausaStr=' ') {
   $aPegar_Temp1 = EXPLODE($sPorPausaStr,$sPegarP_Str);
   $sPegar_Retorna = '';
   For ($nPegar_Cont = 1; $nPegar_Cont<=$nPegarQtd; $nPegar_Cont++) {
       If (! ISSET( $aPegar_Temp1[$nPegar_Cont-1] ) ) { BREAK; }
       If (STRLEN($sPegar_Retorna)>0) { $sPegar_Retorna .= $sPorPausaStr; }
       $sPegar_Retorna .= $aPegar_Temp1[$nPegar_Cont-1];
   }
   Return $sPegar_Retorna;
}
//
Function ExtrTextoEm($strEXTTexto,$strEXTIn1,$strEXTIn2) {
  $strEXTTextoTmp = '  '.$strEXTTexto;
  If (STRPOS($strEXTTextoTmp,$strEXTIn1) == 0 OR STRPOS($strEXTTextoTmp,$strEXTIn2) == 0) {
     Return '';
  }
  $intEXTPosIni = STRPOS($strEXTTextoTmp,$strEXTIn1);
  $intEXTPosIni = $intEXTPosIni + STRLEN($strEXTIn1);
  $strEXTTextoTmp = SUBSTR($strEXTTextoTmp,$intEXTPosIni);
  $intEXTPosFim = STRPOS($strEXTTextoTmp,$strEXTIn2);
  $strEXTTextoTmp = SUBSTR($strEXTTextoTmp,0,$intEXTPosFim);
  Return $strEXTTextoTmp;

}
//
Function Somente_Numeros($sStrTexto,$sStrLstChar='') {
  $nCont_Pos = 0;
  $sStr_Retorno = '';
  While (True) {
     $sCharCond = SUBSTR($sStrTexto,$nCont_Pos,1);
	 If (STRLEN($sCharCond)==0) { BREAK; }
	 If (STRPOS( ' 0123456789'.$sStrLstChar, $sCharCond )>0) {
	    $sStr_Retorno .= $sCharCond;
	 }
	 $nCont_Pos++;
  }
  Return $sStr_Retorno;
}
// Esta funcao completa com zero da esquerda para a direita
// Ex: Str_Zero( 15, 5 ) -> '00015'
Function Str_Zero($nStZ_Numero, $nStZ_Digitos, $sChar_Repeat='0') {
  //$sStz_Ret = SUBSTR($nStZ_Numero.'',0,$nStZ_Digitos);
  $sStz_Ret = $nStZ_Numero.'';
  If (STRLEN($sStz_Ret)<$nStZ_Digitos) {
     $sStz_Ret = STR_REPEAT($sChar_Repeat,$nStZ_Digitos-STRLEN($sStz_Ret)).$sStz_Ret;
  }
  Return $sStz_Ret;
}
// Esta funcao alinha o texto. (0=Esquerda, 1=Centralizado, 2=Direita)
// Ex: AlinhaStr( 'AZUL', 2, 10 ) -> '      AZUL'
Function AlinhaStr($sStrP,$nOpc=1, $nComp=40, $sRepetido=' ') {
   $sRet = SUBSTR($sStrP, 0, $nComp);
   //
   If ($nOpc==0) {            // Alinhado a esquerda
      $sRet = $sRet.STR_REPEAT($sRepetido, $nComp-STRLEN($sRet));
	  //
   } ElseIf ($nOpc==1) {      // Alinhado ao centro
      $sRet = STR_REPEAT($sRepetido, ($nComp/2)-(STRLEN($sRet)/2)).$sRet;
	  //
   } ElseIf ($nOpc==2) {      // Alinhado a direita
      $sRet = STR_REPEAT($sRepetido, $nComp-STRLEN($sRet)).$sRet;
	  //
   } ElseIf ($nOpc==3) {      // Alinhado ao centro completo
      $nQtdSp = ROUND(($nComp/2)-(STRLEN($sRet)/2));
      $sRet = STR_REPEAT($sRepetido, $nQtdSp).$sRet.STR_REPEAT($sRepetido, $nComp-(STRLEN($sRet)+$nQtdSp));
	  //
   }
   Return $sRet;
}
//
Function FormatoMoeda($nExibNumero) {
  Return NUMBER_FORMAT($nExibNumero, 2, ',','.');
}
//
Function FormatoMoedaParaReal($sJaNoFormatoMoeda) {
  $nValorReal = Somente_Numeros($sJaNoFormatoMoeda,',');
  $nValorReal = STR_REPLACE(',','.',$nValorReal)+0;
  Return $nValorReal;
}
// Funcoes de conversao de data e hora
Function ConvertDataBRUS($strDataBR) { // Converte uma data em string no formato BR para US
  //              0123456789
  //$strDatabr = '15/01/2002';
  $strDataUS = '0000-00-00';
  If (0+SUBSTR($strDataBR,3,2)>0 AND 0+SUBSTR($strDataBR,0,2)>0 AND 0+SUBSTR($strDataBR,6,4)>1800 ) {
     $strDataUS = DATE("Y-m-d", MKTIME(0, 0, 0, 0+SUBSTR($strDataBR,3,2), 0+SUBSTR($strDataBR,0,2), 0+SUBSTR($strDataBR,6,4)));
  }
  Return $strDataUS;
}
//
Function ConvertDataUSBR($strDataUS) { // Converte uma data em string no formato US para BR
  //              0123456789
  //$strDatabr = '2002-01-15';
  $strDataBR = '00/00/0000';
  If (0+SUBSTR($strDataUS,5,2)>0 AND 0+SUBSTR($strDataUS,8,2)>0 AND 0+SUBSTR($strDataUS,0,4)>1800 ) {
     $strDataBR = DATE("d/m/Y", MKTIME(0, 0, 0, 0+SUBSTR($strDataUS,5,2), 0+SUBSTR($strDataUS,8,2), 0+SUBSTR($strDataUS,0,4)));
  }
  Return $strDataBR;
}
//
Function ConvertDataSTR($strDataSTR) { // Converte uma string no formato Data (US) para Timestamp
  //              0123456789
  //$strDatabr = '2002-01-15';
  $strDataLNG = 0;
  If (0+SUBSTR($strDataSTR,5,2)>0 AND 0+SUBSTR($strDataSTR,8,2)>0 AND 0+SUBSTR($strDataSTR,0,4)>1800 ) {
     $strDataLNG = MKTIME(0, 0, 0, 0+SUBSTR($strDataSTR,5,2), 0+SUBSTR($strDataSTR,8,2), 0+SUBSTR($strDataSTR,0,4));
  }
  Return $strDataLNG;
}
//
Function ConvertDtHrSTR($strDataSTR) { // Converte uma string no formato Data (US) e hora para Timestamp
  //              0123456789012345678
  //$strDatabr = '2002-01-15 01:12:25';
  $strDataLNG = 0;
  If (0+SUBSTR($strDataSTR,5,2)>0 AND 0+SUBSTR($strDataSTR,8,2)>0 AND 0+SUBSTR($strDataSTR,0,4)>1800 ) {
     $strDataLNG = MKTIME(0+SUBSTR($strDataSTR,11,2), 0+SUBSTR($strDataSTR,14,2), 0+SUBSTR($strDataSTR,17,2), 0+SUBSTR($strDataSTR,5,2), 0+SUBSTR($strDataSTR,8,2), 0+SUBSTR($strDataSTR,0,4));
  }
  Return $strDataLNG;
}
//
Function C_TimeSt_StrDtHr_US( $nData_Hora ) { // Converte o valor Timestamp de data e hora em uma string no formato Data (US)
  $sData_Hora = '';
  If ( $nData_Hora > mktime(0,0,0,1,1,1971) ) {
    $sData_Hora = date( "Y-m-d H:i:s", $nData_Hora );
  }
  Return $sData_Hora;
}
//
Function FormataTelefone( $sForTelefone ) {
  $sForTelRet = $sForTelefone;
  $sForTelRet = STR_REPLACE( ' ' , '', $sForTelRet );
  $sForTelRet = STR_REPLACE( '-' , '', $sForTelRet );
  $sForTelRet = STR_REPLACE( '.' , '', $sForTelRet );
  $sForTelRet = STR_REPLACE( '(' , '', $sForTelRet );
  $sForTelRet = STR_REPLACE( ')' , '', $sForTelRet );
  If (SUBSTR($sForTelRet,0,1)=="0") { $sForTelRet = SUBSTR($sForTelRet,1); }
  If (STRLEN($sForTelRet) == 8) {
	 $sForTelRet = SUBSTR($sForTelRet,0,4).'-'.SUBSTR($sForTelRet,4,4);
  } ElseIf (STRLEN($sForTelRet) == 9) {
	 $sForTelRet = SUBSTR($sForTelRet,0,5).'-'.SUBSTR($sForTelRet,5,4);
  } ElseIf (STRLEN($sForTelRet) == 10) {
	 $sForTelRet = SUBSTR($sForTelRet,0,2).' '.SUBSTR($sForTelRet,2,4).'-'.SUBSTR($sForTelRet,6,4);
  } ElseIf (STRLEN($sForTelRet) == 11) {
	 $sForTelRet = SUBSTR($sForTelRet,0,2).' '.SUBSTR($sForTelRet,2,5).'-'.SUBSTR($sForTelRet,7,4);
  }
  Return $sForTelRet;
}
//
Function ExtrairTextoEm($strEXTTexto,$strEXTIn1,$strEXTIn2) {
  If (STRPOS(' '.$strEXTTexto,$strEXTIn1) == 0 OR STRPOS(' '.$strEXTTexto,$strEXTIn2) == 0) {
     Return '';
  }
  $intEXTPosIni = STRPOS($strEXTTexto,$strEXTIn1);
  $intEXTPosFim = STRPOS($strEXTTexto,$strEXTIn2,$intEXTPosIni);
  $intEXTPosIni = $intEXTPosIni + STRLEN($strEXTIn1);
  $intEXTPosFim = ($intEXTPosFim) - $intEXTPosIni;
  $strEXTRetTxt = SUBSTR($strEXTTexto,$intEXTPosIni,$intEXTPosFim);
  Return $strEXTRetTxt;
}
// Função que separa por índice somente os que vai na matriz de retorno
Function MatrizSeperaSomente( $aIndices=ARRAY(), $aOrigem=ARRAY() ) {
   $aRetorno = ARRAY();
   ForEach ( $aIndices As $vIndice ) {
	  If ( ISSET($aOrigem[$vIndice]) ) {
		 $aRetorno[$vIndice] = $aOrigem[$vIndice];
	  }
   }
   RETURN $aRetorno;
}
//
Function ObterIPdoCliente() {
  If (!EMPTY($_SERVER['HTTP_CLIENT_IP'])) {
     $ip=$_SERVER['HTTP_CLIENT_IP'];
  } ElseIf (!EMPTY($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  } Else {
     $ip=$_SERVER['REMOTE_ADDR'];
  }
  Return $ip;
}
//
Function GeraChave($nCompChave=30, $sMaisCaracteres='', $nCompChaveMin=0 ) {     // Gera chave aleatorio em string
  $CaracteresAceitos = 'abcdefghijlkmnopqurtvxyzwABCDEFGHIJLKMNOPQURTVXYZW0123456789'.$sMaisCaracteres;
  $TamanhoAcMax = STRLEN($CaracteresAceitos)-1;
  $strChaveGerada = '';
  If ( $nCompChaveMin > 0 ) {
     $nCompChave = MT_RAND( $nCompChaveMin, $nCompChave );
  }
  for($i=0; $i < $nCompChave; $i++) {
    $strChaveGerada .= $CaracteresAceitos{MT_RAND(0, $TamanhoAcMax)};
  }
  Return $strChaveGerada;
}
//
//
// Converter IPv4 de duas formas, ex: 127.0.0.1 > (Binário 32bits) ou (Binário 32bits) > 127.0.0.1
Function Converter_IPv4($s_Entrada_IP, $n_Opcao=0) {
  $s_Saida_IP = "";
  // Converter IP em forma explicita para formato binário
  If ( $n_Opcao==0 ) {
	 $a_Entrada_IP = EXPLODE(".",$s_Entrada_IP);
	 For ( $nContador=0; $nContador<4; $nContador++ ) {
	  If ( STRLEN(@$a_Entrada_IP[$nContador])==0 AND (@$a_Entrada_IP[$nContador]+0)<256 ) {
		 $s_Saida_IP = "";
		 BREAK;
	  }
	  $s_Saida_IP .= CHR($a_Entrada_IP[$nContador]+0);
	 }
  }
  // Converter IP em formato binário para forma explicita
  If ( $n_Opcao==1 ) {
   $nTamanho = STRLEN($s_Entrada_IP);
	 If ( $nTamanho==4 ) {
	    For ( $nContador=0; $nContador<4; $nContador++ ) {
            $s_Saida_IP .= ( EMPTY($s_Saida_IP) ? "" : "." ).ORD(SUBSTR($s_Entrada_IP,$nContador,1));
	    }
	 }
  }
  //
  Return $s_Saida_IP;
}
Function Conv_IP_Binario( $sIP="" ) {
  $aIP = EXPLODE(".",$sIP);
  $sBin = "";
  ForEach ( $aIP As $sNum ) {
    $sBin .= CHR($sNum+0);
  }
  Return $sBin;
}
//
//
//
?>