<?php
$bDir_Consult = CondPrivilegio(@$s_DireitosLst, $sNomeAcesso, 'V');
$bDir_Alterar = CondPrivilegio(@$s_DireitosLst, $sNomeAcesso, 'A');
$nTmpFrmEnv = 300;
$sNomeIdJPrin = "iJan_Envia_Sms";
$sCorBarraInf = '#E8E3CE';
// Capturar matriz de trabalho
$sErroHtml = '';


//  ** PRINCIPAL **
If ( EMPTY($sSubModulo) ) {
   // Criar objeto Janela
   $oJan = New R_Janela();
   $oJan->sIdObj  = $sNomeIdJPrin;
   $oJan->nWidth  = 1200;   // Largura
   $oJan->nHeight = 0;     // Altura
   $oJan->nTop    = 10;
   $oJan->nLeft   = 0;
   $oJan->nLeft  += ($nTela_W/2)-($oJan->nWidth/2);
   $oJan->sTitulo = 'Envia Sms para Clientes';
   $oJan->sJavKeyDown = "return Car_".$sNomeAcesso."1.Teclas_F(this,event);";
   //
   $sJavaTravarJ = "parent.document.getElementById('".$oJan->sIdObj."_Travar').style.visibility='visible'; parent.Disabled_In_Elems('".$oJan->sIdObj."',true);";
   $oJan->sJavOnClickF = 
       $sJavaTravarJ.
   	   "parent.document.forms.fmPEnv_Sms.acao.value='FECHAR'; ".
   	   "parent.document.forms.fmPEnv_Sms.submod.value=''; ".
   	   "parent.document.forms.fmPEnv_Sms.submit();".
   	   "";
   //
   // >> Inicial
   If ( EMPTY($sAcao) ) {
	   
	   
	   // Montagem bairro para a combobox
      $sHTML_Combo_CadBai = '<option value="0">* Bairro/Todos *</option>';
      $Rows = MYSQL_QUERY("SELECT BAI_CODIGOI, BAI_DESCRI FROM cad_bairro ORDER BY BAI_DESCRI ASC;") or die(MYSQL_ERROR());
      While ($Row = MYSQL_FETCH_OBJECT($Rows)) {
         $sHTML_Combo_CadBai .=
	        '<option value="'.$Row->BAI_CODIGOI.'">'.$Row->BAI_DESCRI.'</option>';
      }	
		
	  
	  
      //
      
	  //
      $sRet_TelaJ_HTML =
         $oJan->MontaJanHTML(True).
         '<form name="fmPEnv_Sms" accept-charset="utf-8" method="post" action="./car_js.php" target="car_'.$sNomeAcesso.'2">'.
            '<input name="mod" type="hidden" value="'.$sModulo.'">'.
            '<input name="submod" type="hidden" value="'.$sSubModulo.'">'.
            '<input name="acao" type="hidden" value="">'.
            '<input name="nomeacs" type="hidden" value="'.$sNomeAcesso.'">'.
            
         //'</form>'.
		    '<table width="100%">'.
		        '<tr>'.
   	               '<td align="right" width="160px">'.
   	                  'Bairro:&nbsp;&nbsp;'.
   	               '</td>'.
   	               '<td align="left">'.
   	                  '<select id="i_Cli_Bairro" name="Cli_Bairro" style="width:400px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms();">'.
		 	             $sHTML_Combo_CadBai.
		              '</select>'.
		           '</td>'.
   	            '</tr>'.
		    '</table>'.
            '<table border="0">'.
	           '<tr>'.
                  '<td width="160px" height="26px" valign="middle" align="right">'.
		             //'Período que não comprou:'.
		    		  'Dias que não comprou:'.
		    		  '&nbsp;&nbsp;'.
		          '</td>'.				   
		          '<td width="100px" valign="middle" align="left">'.
		             '<input id="i_Cli_QdtDnc" name="Cli_QdtDnc" value="0" type="number" maxlength="10" style="width:100px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms(1);">'.
		    		  //'<input id="i_Cli_DtNCp" name="Cli_DtNCp" value="" type="text" maxlength="10" style="width:100px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms(1);">'.
		             '&nbsp;&nbsp;'.
		    		  //'<img src="images/bimg_calendario.png" border="0" id="bt_Cli_DtNCp" style="cursor:pointer;">'.					   
			      //'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.
				  //'<input id="i_Cli_DtNCpF" name="Cli_DtNCpF" value="" type="text" maxlength="10" style="width:100px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms(1);">'.
		          //'&nbsp;&nbsp;'.
				  //'<img src="images/bimg_calendario.png" border="0" id="bt_Cli_DtNCpF" style="cursor:pointer;">'.					   
			      '</td>'.
			   '</tr>'.
			   '<tr>'.
                  '<td  width="160px" height="26px" valign="middle" align="right">'.
		             'Período que comprou:'.
				     '&nbsp;&nbsp;'.
		          '</td>'.				   
		          '<td valign="middle" align="left">'.
		             '<input id="i_Cli_DtCop"  name="Cli_DtCop" value="" type="text" maxlength="10" style="width:100px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms(2);">'.
		             '&nbsp;&nbsp;'.
					 '<img src="images/bimg_calendario.png" border="0" id="bt_Cli_DtCop" style="cursor:pointer;">'.					   
				     '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.
					 '<input id="i_Cli_DtCopF"  name="Cli_DtCopF" value="" type="text" maxlength="10" style="width:100px;" onchange="Car_'.$sNomeAcesso.'1.P_AtuSms(2);">'.
		             '&nbsp;&nbsp;'.
					 '<img src="images/bimg_calendario.png" border="0" id="bt_Cli_DtCopF" style="cursor:pointer;">'.					   
				  '</td>'.
			   '</tr>'.
			   '<tr>'.
			      '<td>'.
				     '&nbsp;&nbsp;'.
				  '</td>'.
			   '</tr>'.
			   '<tr>'.
                  '<td width="160px" height="25px" align="right" style="font-size: 12px;">'.
		             'Mensagem:'.
				     '&nbsp;&nbsp;'.
				     '<br>'.
					 '<span style="color:#FF0000;">'.
					    'Máximo 150 caracteres'.
					    '&nbsp;&nbsp;'.
				 	 '</span>'.
                  '</td>'.
				  '<td height="" align="left" style="font-size: 12px;">'.
				     '<textarea id="SMS_Mensagem" name="SMS_Mensagem" cols="110" rows="10" style="width:100%; height:60px; background:#FFFBEC; border-width:1px; border-style:solid; border-color:#0099FF; ">'.
					 '</textarea>'.
		             '<br>'.
					 '<br>'.
				  '</td>'.
			   '</tr>'.
			   '<tr>'.
                  '<td>'.
					  //'<div id="dvQdrLis_SMS">'.
				      //'</div>'.
				  '</td>'.
       	       '</tr>'.
			   '<tr>'.
		          '<td height="38px" width="4px">'.
		             '&nbsp;&nbsp;'.
				  '</td>'.
                  '<td>'.
				     //'<input type="checkbox" name="Lst_Clientes[]" onclick="car_'.$sNomeAcesso.'2.marcarTodos(this.checked);">'.
                     //'<span id="SMS_CheckBox_Acao">Marcar Todos</span>'.
				  '</td>'.
	           '</tr>'.
			   '<tr>'.
		          '<td align="right" width="160px">'.
		             'Retorno:'.
                     '&nbsp;&nbsp;'.
				  '</td>'.	 
                  '<td>'.			       
				     '<div id="Exib_Retorno"  align="left" style="width:100%; height:60px; background:#FFFFFF;">'.
				        '<textarea  name="SMS_Retorno" cols="110" rows="10" style="width:100%; height:60px; background:#FFFBEC; border-width:1px; border-style:solid; border-color:#0099FF;">'.
			            //$sErroHtml.
				        '</textarea>'.
		                '<br>'.
			            '<br>'.
			         '</div>'.
				  '</td>'.
               '</tr>'.
		 
            '</table>'.
		    // Lista
            '<div style="height:5px;"></div>'.
		    '<div id="dv_QtdCli" height:40px; style="font-size:20px"></div>'.      
	        //'<div id="dv_ListaCli" align="left" style="width:100%; height:380px; background:#FFFFFF; overflow:auto;">'.
		    //   '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">'.
            //      '<tr>'.
			//         '<td align="center" valign="middle" style="color:#555555;">'.
            //            'Aguarde um momento...<br>'.
            //            '<img src="images/img_load1.gif" border="0">'.
            //         '</td>'.
			//      '</tr>'.
            //   '</table>'.
		    //'</div>'.
			//'<div id="dv_AppListaRod" align="left" style="width:100%; height:50px; background:#FFFFFF;"></div>'.
            '<div style="height:5px;"></div>'.
		 '</form>'.
		    // Barra inferior
       	 '<table width="100%" style="background-color:'.$sCorBarraInf.';">'.
		    '<tr>'.
               '<td width="8px"></td>'.
               '<td width="134px" align="right" valign="center">'.
       	          HTML_Botao( 3, 'o_LisAtualiza', "parent.JanEspera(false); ".				    
	                                              "parent.document.forms.fmPEnv_Sms.acao.value='PUXAR_TAB';".
	                                              "parent.document.forms.fmPEnv_Sms.submod.value='';".
                                                  "parent.document.forms.fmPEnv_Sms.submit(); "
			 			       , 'Atualizar'     ,'images/btimg_ativar_1.png'   , 112).      
		       '</td>'.
               '<td width="134px" align="right" valign="center">'.
                  
                 
		       '</td>'.
			   '<td width="134px" align="right" valign="center">'.
       	             HTML_Botao( 3, 'o_EnviaLis', "parent.JanEspera(false); ".				    
	                                              "parent.document.forms.fmPEnv_Sms.acao.value='ENVIAR_SMS';".
	                                              "parent.document.forms.fmPEnv_Sms.submod.value='';".
                                                  "parent.document.forms.fmPEnv_Sms.submit(); "
			 		              , 'Enviar'     ,'images/btimg_sms_ativo.png'   , 142).      
		       '</td>'.
		       '<td align="left"></td>'.
               '<td align="left">'.
                   HTML_Botao( 3, 'objTxt_BT',  'Car_'.$sNomeAcesso.'1.SalvarTexto();'
                                , 'Gerar Txt'   ,'images/btimg_baixar_texto.png',100).		    
		       '</td>'.
               '<td width="124px" align="right" valign="center">'.
       	          HTML_Botao( 3, 'oSms_LisSair', $oJan->sJavOnClickF
			                   , 'Sair'     ,'images/btimg_fechar.png'   , 102).
		       '</td>'.
               '<td width="4px"></td>'.
		    '</tr>'.
		 '</table>'.
         $oJan->MontaJanHTML(False);
      //
      // Java inicial
      $sRet_Javs .=
	    'parent.document.getElementById("dv_MenuL_Barra").style.visibility="hidden";'.
 	    "function P_AtuSms(_opcao) {".		  
		   "var cli_dtacop=parent.document.getElementById('i_Cli_DtCop').value;".
		   "var cli_dtacopf=parent.document.getElementById('i_Cli_DtCopF').value;".
		   "if ( _opcao==1 ) {".
		      "if (parent.document.getElementById('i_Cli_QdtDnc').value > 0) {".
		         "if ( parent.document.getElementById('i_Cli_DtCop').style.display != 'none') {".
			        "parent.document.getElementById('i_Cli_DtCop').style.display='none';".
		            "parent.document.getElementById('bt_Cli_DtCop').style.display='none';".
				 "}".
			     "if ( parent.document.getElementById('i_Cli_DtCopF').style.display != 'none') {".
			        "parent.document.getElementById('i_Cli_DtCopF').style.display='none';".
					"parent.document.getElementById('bt_Cli_DtCopF').style.display='none';".
			     "}".
		      "} else {".
			     "if ( parent.document.getElementById('i_Cli_DtCop').style.display == 'none') {".
			        "parent.document.getElementById('i_Cli_DtCop').style.display='inline';".
					"parent.document.getElementById('bt_Cli_DtCop').style.display='inline';".
					
		         "}".
			     "if ( parent.document.getElementById('i_Cli_DtCopF').style.display == 'none') {".
			        "parent.document.getElementById('i_Cli_DtCopF').style.display='inline';".
					"parent.document.getElementById('bt_Cli_DtCopF').style.display='inline';".
			     "}".
			  "}".
		   "} else if ( _opcao==2 ) {".
		      "if (parseInt(cli_dtacop)>0) {".
		         "if ( parent.document.getElementById('i_Cli_QdtDnc').style.display != 'none') {".
			        "parent.document.getElementById('i_Cli_QdtDnc').style.display='none';".
		         "}".   
			  "} else {".
			     "if ( parent.document.getElementById('i_Cli_QdtDnc').style.display == 'none') {".
			         "parent.document.getElementById('i_Cli_QdtDnc').style.display='inline';".
			     "}".
              "}". 		   
		     	
		   "}".
		   //
		   "parent.document.getElementById('o_EnviaLis').style.display='none';".
		   "parent.document.getElementById('objTxt_BT').style.display='none';".
		   
		   
		"}".
		"function SalvarTexto() {".
	        "parent.document.forms.fmPEnv_Sms.acao.value='GERAR_TEXTO';".
            "parent.document.forms.fmPEnv_Sms.submit();".
		  "}".
		
		"";
		
		// 
		   
		
        
      // Java posterior
      $sRet_JavsPos .=
	    "var FmH = parent.document.forms['fmPEnv_Sms'];".
		// teclas da janela
		"function Teclas_F( Objeto, Evento ) {".
           "vNumTecla = parent.Tecla_Apertada(Evento);".
		   "if ( vNumTecla==116) { ".           //  ** [F5] **       Não atualizar
		       //
		   "} else if ( vNumTecla==27) { ".     //  ** [ESC] **      (SAIR)
			   "setTimeout( parent.document.getElementById('oSms_LisSair').onclick , 100);".
              //"setTimeout( function () { ".$oJan->sJavOnClickF." } , 1);".
		   "} else {".
	           "P_TeclasPress_fm(Evento);".
		       "return true;".
		   "}".
		   "return false;".
		"}".
		//
		"Puxar_Tabelas();".
		"function Puxar_Tabelas() {".
           "FmH.acao.value='PUXAR_TAB';".
           "FmH.submit();".
		"}".
		//'parent.Calendar.setup({ '.
        //    'inputField : "i_Cli_DtNCp", '.
        //    'trigger    : "bt_Cli_DtNCp", '.
        //    'onSelect   : function() { this.hide();  }, '.
        //    'showTime   : 0, '.
        //    'dateFormat : "%d/%m/%Y" '.
        //'});'.
	    'parent.Calendar.setup({ '.
            'inputField : "i_Cli_DtCop", '.
            'trigger    : "bt_Cli_DtCop", '.
            'onSelect   : function() { this.hide(); P_AtuSms(2); }, '.
            'showTime   : 0, '.
            'dateFormat : "%d/%m/%Y" '.
        '});'.
        //'parent.Calendar.setup({ '.
        //    'inputField : "i_Cli_DtNCpF", '.
        //    'trigger    : "bt_Cli_DtNCpF", '.
        //    'onSelect   : function() { this.hide();  }, '.
        //    'showTime   : 0, '.
        //    'dateFormat : "%d/%m/%Y" '.
        //'});'.
	    'parent.Calendar.setup({ '.
            'inputField : "i_Cli_DtCopF", '.
            'trigger    : "bt_Cli_DtCopF", '.
            'onSelect   : function() { this.hide(); P_AtuSms(2); }, '.
            'showTime   : 0, '.
            'dateFormat : "%d/%m/%Y" '.
        '});'.
		"";
		
		
   } ElseIf ( $sAcao=="ENVIAR_SMS" ) {
	 $aCli_FatGeral = $aSessao['SMS_CADCLI'];
	 $sMensagem = @$_REQUEST['SMS_Mensagem'];
     
	 $nQtde_Reg = count($aCli_FatGeral);
	 If (STRLEN($sMensagem)>0 && $nQtde_Reg > 0 ){
	 	$aDestinos = ARRAY();
        $sErroHtml  = '';
	 	
	 	//ECHO VAR_EXPORT($aCli_FatGeral,True);
	 	//
        ForEach ( $aCli_FatGeral as $nCli_CodigoI => $aCad_Cliente ) {
	 	   $aCad_Telefones = @$aCad_Cliente['CAD_TELEFONES'];
	 	   If ( ! EMPTY($aCad_Telefones) ) {
	 	      $aRetorno  = C_Sicore_EnviarSMS( $aCad_Telefones, $sMensagem, $nCli_CodigoI.'-'.$aCad_Cliente['CLI_NOMECP'] );
	 		  $aResposta = $aRetorno[0];
	 		  $sMsg_Erro = $aRetorno[1];
	 	       
	 		  //echo "<script>alert(".JAVA_CharCode(VAR_EXPORT($aResposta,True)).");</script>";   
	 		  //echo "<script>alert(".JAVA_CharCode(VAR_EXPORT($sMsg_Erro,True)).");</script>";   
	 			
	 		  $sCOD_SEQ = '';
	 		  $sDST_NUM = '';
	 		  $sErro    = '';
	 		  $sSMS_DtaEnt = DATE("Y-m-d H:i:s");
	 		  $sSMS_OpeAtu = $R_CadFuncionario->FUN_CODIGO;
	 		  ForEach( $aResposta As $nIndice=>$sResposta ) {
	 		     $sCOD_SEQ = @$sResposta['SMS_CODIGO_SEQ'];
	 			 $sDST_NUM = @$sResposta['DST_NUMERO_SIM'];
	 		      
	 			 //echo "<script>alert('".$sCOD_SEQ."');</script>";
	 			 If ( ! EMPTY($sResposta['ERRO'][0])){
	 			    $sErro = $sResposta['ERRO'][0].'-'.$sResposta['ERRO'][1];
	 			 }
                  
	 			  
	 			 If (STRLEN($sCOD_SEQ)>0 && STRLEN($sDST_NUM)>0 ){
	 			    $sSQLRequest = 
	 				   "INSERT INTO sms_movimento(".
                          "SMS_CODCLI, SMS_CODREF, SMS_CRIADO, SMS_CODOPE, SMS_MENSAGEM, SMS_CELDESTI )".
	 		           "VALUE(".
          	              " ".$nCli_CodigoI.",".         
                          "'".$sCOD_SEQ."',".      	   
	 		              "'".$sSMS_DtaEnt."',".
	 		              "'".$sSMS_OpeAtu."',".
	 		           SQL_Bin($sMensagem).",".
	 		           "'".$sDST_NUM."'".
	 				   ");";
                    MYSQL_QUERY($sSQLRequest) or die('<br>' .$sSQLRequest . '<br>' . MYSQL_ERROR()); // Executar comando SQL
             
                 
				 
				 
				 }			
	 		     
	 		  }
	 		  //echo "<script>alert('".$sErro."');</script>";
	 		  If(! EMPTY($sMsg_Erro)){
	 		     $aTmp_Erro = EXPLODE(';',$sMsg_Erro);
                 $sId_Num = 'Destino: ';			   
	 			 ForEach( $aTmp_Erro As $sTmp_Erro ) {
	 	    	    If (! EMPTY($sTmp_Erro)){ 
	 				   $sId_Num .= @$sTmp_Erro.','; 	
	 			         //echo "<script>alert('".$sId_Num."');</script>";
	 				}
	 			 }
	 			   
	 			   
	 			 $sErroHtml .=
	 			    $sErro. 
                       ' Cliente: '.
                       $nCli_CodigoI.'-'.$aCad_Cliente['CLI_NOMECP'].						  
	 				   ' '.$sId_Num.
                       CHR(13).CHR(10).
	 				   '';				 
	 			
	 		  } Else {
	 		     $sRet_Javs .=
                    "parent.document.getElementById('Exib_Retorno').innerHTML = ".JAVA_CharCode('Mensagem enviada com sucesso.').";".
	 	            "";
	 			  
	 			  //$sErroHtml = 'Mensagem enviada com sucesso.'.CHR(13).CHR(10);	
	 	 	  }	
	 			
	 	   } 
	 		
	 	}
	 	   
	 	If ( STRLEN($sErroHtml)> 0 ) {
	 	   $sRet_Javs .=
              "parent.document.getElementById('Exib_Retorno').innerHTML = ".JAVA_CharCode($sErroHtml).";".
	 	      "";
	 	}	
	 } Else {
		 
		
	    $sRet_Javs .=
           ( STRLEN($sMensagem)==0 ?
		      "parent.Alerta_Simples('Mensagem vazia !',0);"
		   :
		      (  $nQtde_Reg==0 ?
			    "parent.Alerta_Simples('Nenhum Registro encontrado !',0);"
			   :
			    ""
			   )
		   ).
	 	   "";

	
	 }	 


   
   //
   // >> Puxar tabelas
   } ElseIf ( $sAcao=="PUXAR_TAB" ) {
      $sSQLRequest2 = '';
	  $sSQLParm     = '';
	  $nCli_Bairro  = @$_REQUEST['Cli_Bairro'];
	  //$sCli_DtNCp   = @$_REQUEST['Cli_DtNCp'];
	  //$sCli_DtNCpF  = @$_REQUEST['Cli_DtNCpF'];
	  $nCli_QdtDnc   = @$_REQUEST['Cli_QdtDnc'];
	  $sCli_DtCop   = ConvertDataBRUS(@$_REQUEST['Cli_DtCop'] );
	  $sCli_DtCopF  = ConvertDataBRUS(@$_REQUEST['Cli_DtCopF']);
	  //$sSMS_Mensagem = @$_REQUEST['SMS_Mensagem'];
	   
	  //echo "<script>alert('".'1 '.$sCli_Bairro."');</script>";
	  //echo "<script>alert('".'2 '.$sCli_DtCop."');</script>";
	  
	  /*If ( STRLEN($sCli_DtNCp)> 0 AND STRLEN($sCli_DtNCpF)> 0 ) {
		 $sUFil_DtaNcp = ConvertDataBRUS($sCli_DtNCp);
         If ( ConvertDataSTR($sUFil_DtaNcp)>0 ) {
            //If (STRLEN($sSQLParm)>0) { $sSQLParm .= ' AND '; }
			$sSQLParm .= " AND FAT_DATAINI<'".$sUFil_DtaNcp."' ";
         }
	     
		 $sUFil_DtaNcpF = ConvertDataBRUS($sCli_DtNCpF);
         If ( ConvertDataSTR($sUFil_DtaNcpF)>0 ) {
            //If (STRLEN($sSQLParm)>0) { $sSQLParm .= ' AND '; }
			$sSQLParm .= " AND FAT_DATAINI>'".$sUFil_DtaNcpF."' ";
         }
	  }*/
	  
	  If ( $nCli_QdtDnc> 0  ) {
		  
		  $dDta_Tra = Date("Y-m-d");
          $_Par = explode("-", $dDta_Tra);
          $dDta_Tra = $_Par[0].'/'.$_Par[1].'/'.$_Par[2];
 		  $dDta_Tra = Date('Y-m-d', STRTOTIME("-".(string)$nCli_QdtDnc." days",STRTOTIME($dDta_Tra)));
		  
		  $sUFil_DtaNcp = $dDta_Tra;
          If ( ConvertDataSTR($sUFil_DtaNcp)>0 ) {
            //If (STRLEN($sSQLParm)>0) { $sSQLParm .= ' AND '; }
			$sSQLParm .= " AND FAT_DATAINI>='".$sUFil_DtaNcp."' ";
          }
		  
	  }
	  
	  
	  If ( ConvertDataSTR($sCli_DtCop)> 0 AND ConvertDataSTR($sCli_DtCopF)> 0) {
         If ( ConvertDataSTR($sCli_DtCop)>0 ) {
            //If (STRLEN($sSQLParm)>0) { $sSQLParm .= ' AND '; }
			$sSQLParm .= " AND FAT_DATAINI>='".$sCli_DtCop."' ";
         }  
	     
         If ( ConvertDataSTR($sCli_DtCopF)>0 ) {
            //If (STRLEN($sSQLParm)>0) { $sSQLParm .= ' AND '; }
			$sSQLParm .= " AND FAT_DATAINI<='".$sCli_DtCopF."' ";
         }  
	  }
	  
	  
	  //echo "<script>alert('".$sSQLParm."');</script>";
	  //
	  $aCli_FatGeral = ARRAY();
	  //
	  $sSQLReqFTG = 
	     "SELECT FAT_CLIENTE, MAX(FAT_DATAINI) AS DATULC ".
		 //( $nCli_Bairro > 0 ?
		 //   ",CLI_CODBAI "
	     //:
		 //   ""
		 //).
		 "FROM fat_geral ".
         //( $nCli_Bairro > 0 ?
		 //   "LEFT JOIN cad_cliente   AS cli ON cli.CLI_CODIGOI = FAT_CLIENTE "
		 //:
		 //  ""
		 //).
		 'WHERE FAT_TIP_LOC=2 AND FAT_CLIENTE > 0 AND FAT_CANCELA=0 '.
		 $sSQLParm.
		 " GROUP BY FAT_CLIENTE ".
		 " ORDER BY FAT_CLIENTE ASC".
		 '';
		 
		 
		//ECHO ($sSQLReqFTG);
      //
	  $Rows_Regs = MYSQL_QUERY($sSQLReqFTG) or die(MYSQL_ERROR());
	  While ( $Row_Regs = MYSQL_FETCH_ARRAY($Rows_Regs,MYSQL_ASSOC) ) {
		 
		 //If( $nCli_Bairro > 0){
         //    If ($Row_Regs['CLI_CODBAI']== $nCli_Bairro ){
         //       $aCli_FatGeral[$Row_Regs['FAT_CLIENTE']] =
		 //          ARRAY( "DATA_ULTCOMPRA" => $Row_Regs['DATULC'] );
		//	 }				 
         //} Else {		 
		    $aCli_FatGeral[($Row_Regs['FAT_CLIENTE']+0)] =
		    ARRAY( "DATA_ULTCOMPRA" => $Row_Regs['DATULC'] );
		 //}  
	  }
	  
	  
	  If ($nCli_Bairro > 0  ) {
         $sSQLRequest2 .= " AND CLI_CODBAI= ".$nCli_Bairro." ";
      }
	  //
	  $sSQLQuery =
	    "SELECT ".
		   "cli.CLI_CODIGOI, cli.CLI_NOMECP, cli.CLI_ENDLOG, cli.CLI_CODBAI,cli.CLI_ENDBAI, tel.TEL_NUMERO ".
		"FROM cad_cliente AS cli ".
		"LEFT JOIN cad_telefones AS tel ON tel.TEL_CODCAD= cli.CLI_CODIGOI ".
        "WHERE ".
		  " TEL_TRAREG=0 ".
		  $sSQLRequest2.
        "ORDER BY CLI_CODIGOI ".
	    ";";
	  //DIE($sSQLQuery);
	  $Rows_Regs = MYSQL_QUERY($sSQLQuery) or die(MYSQL_ERROR());
	  $nQtd_Cli = 0;
	  $sQtd_Reg = '';
	  $bTem_Cli = True;
	  $nContador = 0;
	  
	  If ( ConvertDataSTR($sCli_DtCop)> 0 AND ConvertDataSTR($sCli_DtCopF)> 0) {
	  //If (STRLEN($sCli_DtCop)> 0 AND STRLEN($sCli_DtCopF)> 0) {
			If ( EMPTY($aCli_FatGeral) ) {
               	$bTem_Cli = False;        
			}			
	  }
	  If ($bTem_Cli) {
	     While ( $Row_Regs = MYSQL_FETCH_ARRAY($Rows_Regs,MYSQL_ASSOC) ) {
		   //
		    $aCad_Cliente = @$aCli_FatGeral[($Row_Regs['CLI_CODIGOI']+0)];
			 
		    If ( EMPTY($aCad_Cliente) ) {
		       $aCad_Cliente = ARRAY();
	  	    }
			$bRemover_Cli = False;
			//
			If ( $nCli_QdtDnc==0 ) {  // Clientes que compraram
			    $bRemover_Cli = ( EMPTY($aCad_Cliente['DATA_ULTCOMPRA']) );
			} Else {                  // Clientes que não compraram
			    $bRemover_Cli = ( ! EMPTY($aCad_Cliente['DATA_ULTCOMPRA']) );
			}
			//
			If ( $bRemover_Cli ) {
			   UNSET( $aCli_FatGeral[($Row_Regs['CLI_CODIGOI']+0)] );
			   CONTINUE;
			}
			 
		    $nContador++;
		    $aCad_Cliente['CLI_NOMECP'] = $Row_Regs['CLI_NOMECP'];
		    //$aCad_Cliente['CLI_NOMECP'] = $Row_Regs['CLI_CODIGOI'].' -  '.$Row_Regs['CLI_NOMECP'];
		    $aCad_Cliente['CLI_ENDLOG'] = $Row_Regs['CLI_ENDLOG'];
		    $aCad_Cliente['CLI_ENDBAI'] = $Row_Regs['CLI_ENDBAI'];
		    //
			 
		    If ( ! EMPTY($Row_Regs['TEL_NUMERO']) ) {
		       $aCad_Telefones = @$aCad_Cliente['CAD_TELEFONES'];
			   //
			   $sNumero = $Row_Regs['TEL_NUMERO'];
			   IF   ( STRLEN($sNumero)==8 ) {
                   $sDigCel = SUBSTR($sNumero,0,1);
                   $sNumero = "9".$sNumero;
               } ElseIf ( STRLEN($sNumero)==9 ) {
                   $sDigCel = SUBSTR($sNumero,1,1);
               } ElseIf ( STRLEN($sNumero)==10 ) {
                   $sDigCel = SUBSTR($sNumero,2,1);
                   $sNumero = "9".SUBSTR($sNumero,2);
               } ElseIf ( STRLEN($sNumero)==11 ) {
                   $sDigCel = SUBSTR($sNumero,3,1);
                   $sNumero = SUBSTR($sNumero,2);
               } Else {
                   $sDigCel = SUBSTR($sNumero,2,1);
                   $sNumero = SUBSTR($sNumero,2);
               }
               If ( $sDigCel=="9" OR $sDigCel=="8" OR $sDigCel=="7" ) {
			      $aCad_Telefones[] = $Row_Regs['TEL_NUMERO'];
			      $aCad_Cliente['CAD_TELEFONES'] = $aCad_Telefones;
			   
			   }
			   //
	  	    }
		    //
		    $aCli_FatGeral[($Row_Regs['CLI_CODIGOI']+0)] = $aCad_Cliente;
		    $nQtd_Cli++;
		 }
	  }
      //
	  $a_Cli_Tmp = $aCli_FatGeral;
	  ForEach ( $aCli_FatGeral as $nCli_CodigoI => $aCad_Cliente ) {
		If ( EMPTY($aCad_Cliente['CAD_TELEFONES']) ) {
		   UNSET( $a_Cli_Tmp[$nCli_CodigoI+0] );
	    }
	  }
	  $aCli_FatGeral = $a_Cli_Tmp;
	  //
	  $nCli_Tela = COUNT($aCli_FatGeral);
      //ECHO $nCli_Tela;
	  
	  
	  $sQtd_Reg = 
	     '<span font-size:20px;>'.
		    '&nbsp;&nbsp;&nbsp;Foram encontrado(s) '.$nCli_Tela.' registro(s)'.
		 '</span>'.
		 '<img src="images/linha_rel.bmp" width="100%" height="1px"><br>&nbsp;';
	  
	  
	  $aSessao['SMS_CADCLI'] = $aCli_FatGeral;
	  
	  
	  //ECHO VAR_EXPORT($aCli_FatGeral,True);
	  $sCoresLinh = Array( 1=> '#FFFF99', 2=> '#FFDD99');
      $sCorLinh = '';
	  $sHTML_Lista = '';
      $b_CheckBox = False;
	  
	  ForEach ( $aCli_FatGeral as $nCli_CodigoI => $aCad_Cliente ) {
	    
		
		If ( $sCorLinh <> $sCoresLinh[1] ) {
           $sCorLinh = $sCoresLinh[1];
        } Else {
           $sCorLinh = $sCoresLinh[2];
        }
	    //ECHO VAR_EXPORT($aCad_Cliente,True)."<br>";
		//if ($nCli_CodigoI==696) {
		//ECHO VAR_EXPORT($aCad_Cliente['CAD_TELEFONES'],true)."<br>";
		//}
		$aCad_Telefones = @$aCad_Cliente['CAD_TELEFONES'];
		$sNumTel = '';
		If ( ! EMPTY($aCad_Telefones) ) {
	       
		   ForEach ( $aCad_Telefones as $nTel_Numero ) {
              
			  $sNumero = $nTel_Numero;
			  $sDigCel = '';
			  
			  $sNumTel .= FormataTelefone($nTel_Numero).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			  
			  //echo "<script>alert('".$sNumTel."');</script>";
			  
			  //IF   ( STRLEN($sNumero)==8 ) {
              //    $sDigCel = SUBSTR($sNumero,0,1);
              //    $sNumero = "9".$sNumero;
              //} ElseIf ( STRLEN($sNumero)==9 ) {
              //    $sDigCel = SUBSTR($sNumero,1,1);
              //} ElseIf ( STRLEN($sNumero)==10 ) {
              //    $sDigCel = SUBSTR($sNumero,2,1);
              //    $sNumero = "9".SUBSTR($sNumero,2);
              //} ElseIf ( STRLEN($sNumero)==11 ) {
              //    $sDigCel = SUBSTR($sNumero,3,1);
              //    $sNumero = SUBSTR($sNumero,2);
              //} Else {
              //    $sDigCel = SUBSTR($sNumero,2,1);
              //    $sNumero = SUBSTR($sNumero,2);
              //}
              //If ( $sDigCel=="9" OR $sDigCel=="8" OR $sDigCel=="7" ) {
	          //    $b_CheckBox = True;
		      //    BREAK;
			  //}
		   }
		   // If ( $nCli_Tela <= 500) {
				$sHTML_Lista .= 
					'<tr style="background-color:'.$sCorLinh.';">'.
	                    '<td width="40px"  valign="bottom" style="font-size: 12px;font-family: Courier New, Courier, mono;">'.
						   ( $b_CheckBox ?
	                       '<input name="Lst_Clientes[]" type="checkbox" value="'.$nCli_CodigoI.'" >'
						   : "").
	 	 	 	 	    '</td>'.
					    '<td colspan="4"  width="140px" valign="middle" style="font-size: 14px;"><strong><br>'.@$aCad_Cliente['CLI_NOMECP'].'</strong></td>'.                  
					    '<td colspan="4"  width="200px" valign="middle" style="font-size: 14px;"><strong><br>'.@$aCad_Cliente['CLI_ENDLOG'].'</strong></td>'.                  
						'<td colspan="4"  width="100px" valign="middle" style="font-size: 14px;"><strong><br>'.@$aCad_Cliente['CLI_ENDBAI'].'</strong></td>'.                  
					    '<td colspan="4"  width="100px" valign="middle" style="font-size: 14px;"><strong><br>'.ConvertDataUSBR(@$aCad_Cliente['DATA_ULTCOMPRA']).'</strong></td>'.                  
					'</tr>'.
					'<tr style="background-color:'.$sCorLinh.';">'.	
						'<td width="10px" valign="middle" style="font-size: 12px;"></td>'.  
						'<td colspan="4" width="200px" valign="middle" style="font-size: 12px;"><strong>'.@$sNumTel.'</strong></td>'.  
	                    '<td colspan="4" width="200px" valign="middle" style="font-size: 14px;"></td>'.                  
					    '<td colspan="4" width="100px" valign="middle" style="font-size: 14px;"></td>'.                  
					    '<td colspan="4" width="100px" valign="middle" style="font-size: 14px;"></td>'.                  
					'</tr>'.
					 '';
			//}
		}
		
	  }
	  
	 
     
      If (STRLEN($sHTML_Lista)>0) {
         $sHTML_Lista = ''.
	       '<table width="100%" border="0" cellspacing="0">'.
		      //$sHTML_Lista.
           '</table>';
   } Else {
      //$sMensagem_Pg = '1Nenhum registro encontrado.';
   }
   $sRet_Javs .=
      "parent.document.getElementById('dv_QtdCli').innerHTML = ".JAVA_CharCode($sQtd_Reg).";".
	  //"parent.document.getElementById('dv_ListaCli').innerHTML = ".JAVA_CharCode($sHTML_Lista).";".
      'function marcarTodos(marcar){'.
         'var itens = parent.document.getElementsByName("Lst_Clientes[]");'.
         'if(marcar){'.
            //'parent.document.getElementById("SMS_CheckBox_Acao").innerHTML = "Desmarcar Todos";'.
         '}else{'.
            //'parent.document.getElementById("SMS_CheckBox_Acao").innerHTML = "Marcar Todos";'.
         '}'.
         'var i = 0;'.
         'for(i=0; i<itens.length;i++){'.
            'itens[i].checked = marcar;'.
         '}'.
      '}'.
	   "parent.document.getElementById('o_EnviaLis').style.display='inline-block';".
	   "parent.document.getElementById('objTxt_BT').style.display='inline-block';".
	   '';	
	   

//
   } ElseIf ( $sAcao=="GERAR_TEXTO" ) {
      $sArquivo = "Sms_".DATE("d-m-Y_H-i-s").".txt";
      $nCli_Bairro  = @$_REQUEST['Cli_Bairro'];
	  $nCli_QdtDnc   = @$_REQUEST['Cli_QdtDnc'];
	  $sCli_DtCop   = @$_REQUEST['Cli_DtCop'] ;
	  $sCli_DtCopF  = @$_REQUEST['Cli_DtCopF'];
      $aCli_FatGeral = $aSessao['SMS_CADCLI'];
	  $sTXT_SMS = '';
      $sCli_NomBai = '*** Todos ***';	
	  $nQtde_Reg = Count($aCli_FatGeral);
	
	  If ($nCli_Bairro>0 ) {
	     $Rows = MYSQL_QUERY("SELECT BAI_CODIGOI, BAI_DESCRI FROM cad_bairro WHERE BAI_CODIGOI=".$nCli_Bairro.";") or die(MYSQL_ERROR());
         If ($Row = MYSQL_FETCH_OBJECT($Rows)) {
            $sCli_NomBai = $Row->BAI_CODIGOI.'-'.$Row->BAI_DESCRI;
         }
	  }
	
	  $sTXT_SMS = 
	     'Bairro : '.$sCli_NomBai.CHR(13).CHR(10).
	     'Dias   : '.$nCli_QdtDnc.CHR(13).CHR(10).
	     'Periodo: '.$sCli_DtCop.' a '.$sCli_DtCopF.CHR(13).CHR(10).
		 '____________________________________________________'.CHR(13).CHR(10).
	     '';
	   
	
	  If ( $nQtde_Reg > 0 ) {
	     
	     ForEach ( $aCli_FatGeral as $nCli_CodigoI => $aCad_Cliente ) {
	        $aCad_Telefones = @$aCad_Cliente['CAD_TELEFONES'];
	 	    $sNumTel = '';	
			If ( ! EMPTY($aCad_Telefones) ) {	   
               ForEach ( $aCad_Telefones as $nTel_Numero ) {
                  $sNumTel .= 
				     FormataTelefone($nTel_Numero).' '.
				     '';
			   } 
			 
			   $sTXT_SMS .= 
    		      $nCli_CodigoI.'-'.$aCad_Cliente['CLI_NOMECP'].','.
				  $aCad_Cliente['CLI_ENDBAI'].','.
				  $sNumTel.
				  CHR(13).CHR(10).
    			  '';
		    }
	     }  
	   
	     $sTxt_SmsA = $sTXT_SMS;
	     HEADER("Content-Type: text/plain");
	     HEADER("Content-Length: ".STRLEN($sTxt_SmsA));
	     HEADER("Content-Disposition: attachment; filename=".$sArquivo);
	     ECHO $sTxt_SmsA;
	     EXIT;
	 
	  }  Else {
	     $sRet_Javs .=
	        "parent.Alerta_Simples('Nenhum Registro encontrado !',0);".
	        '';
		 
	  }	 
	  
   // >> Fechar janela
   } ElseIf ( $sAcao=="FECHAR" ) {
      //
      $sRet_Javs .=
         "parent.document.getElementById('dv_MenuL_Barra').style.visibility='visible';".
         "parent.RmElem('".$oJan->sIdObj."');";
 	  
	  UNSET( $aSessao['SMS_CADCLI']);
   }
   
}
//
?>