<?
/*
Autor: Lic. Carlos Alberto Vaca Coronado
Version: 3.2.0
*/
include ("libs/backOffice.class.php");
$backOffice=new backOffice();
?>
<script type="text/javascript">
function abrirU(url,b,mensaje)
{
	//window.open(url,"Location=1");
	if(b != 'elimina')
	{
		if(b == 'b3')
		{
			window.top.location.href = url;
		}
		else if(b == 'regresa')
		{
			window.top.location.href = url;
		}
		else if(b == 'reporte')
		{
			if(arch=prompt("De el Nombre del Archivo",mensaje))
			window.top.location.href = url+"?archivo="+arch+"&tipo=txt";
		}
	
	}
	else if(confirm(mensaje))
		{
			window.top.location.href = url;
		}
		else
		return false;
}
</script>
<? if(empty($_FILES) && !isset($_POST['insertarExcel'])){?>
<form method="post" enctype="multipart/form-data" action="" onsubmit="return validar('fileInput','','','','','','','','','','','','','','');">
  <table width="598" border="0" align="center" cellpadding="3" cellspacing="3" class="td_general">
    <tr>
      <td width="59" align="center" class="num_noticia">&nbsp;</td>
      <td colspan="3" align="left" class="txt_titulos">Cargar lista</td>
    </tr>
    <tr>
      <td align="center" class="num_noticia">&nbsp;</td>
      <td width="78" align="left" class="tx_menu">Archivo *:</td>
      <td colspan="2" align="left"><input name="fileInput" type="file"  id="fileInput" size="30" />
		<a href="" class="tt"><img src="Imagenes/Help.png" width="20" height="18"><span class="tooltip_sinImagen" align="left"><span class="top_sinImagen"></span><span class="middle_sinImagen">
		<font color="#999999" size="-1">Los datos deberan estar en la primer hoja e iniciando con la primer columna.<br>Ejemplo:<br><br><img src="Imagenes/UsuarioXLS.jpg" width="355" height="213"/></font>
		</span><span class="bottom_sinImagen"></span></span></a>
	  </td>
    </tr>
    <tr>
      <td colspan="4" align="center" class="num_noticia">&nbsp;</td>
    </tr>
    <tr>
      <td align="center" class="num_noticia">&nbsp;</td>
      <td align="left" class="txt_menu">&nbsp;</td>
      <td width="54" align="right"></td>
      <td width="383" align="left">
		<input type="submit" name="cargarArchivo" id="cargarArchivo" value="CARGAR" class="estilo_btn"/>
		<input type="Button" onClick="abrirU('admin.php?seccion=6&menu=2','b3','')" name="REGRESAR" value="REGRESAR" class="estilo_btn"/>
	  </td>
    </tr>
  </table>
</form>
<? }
elseif(isset($_FILES['fileInput']))
{
	$targetFile = "upload/fileUsuarios.xls";
	if (file_exists($targetFile)){
		unlink($targetFile);	
	}
	$tempFile = $_FILES['fileInput']['tmp_name'];
	$targetPath = 'upload/';
	$targetFile =  str_replace('//','/',$targetPath) . "fileUsuarios.xls";;
	move_uploaded_file($_FILES['fileInput']['tmp_name'],$targetFile);
	
	
	require_once 'libs/ExcelReader/reader.php';
	$data = new Spreadsheet_Excel_Reader();
	
	$data->setOutputEncoding('CP1251');
	
	$data->read($targetFile);
	
	
?>
<form name="forma" id="forma" method="post" action="admin.php?seccion=13&menu=2">
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="td_general">
  <tr>
    <td align="left" valign="top"><table width="590" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td colspan="3" height="7"></td>
      </tr>
      <tr>
        <td width="45" align="center" class="num_noticia">&nbsp;</td>
        <td width="545" colspan="2" align="left" class="txt_titulos">Cargar Usuarios</td>
      </tr>
      <tr>
        <td colspan="3" align="center" class="num_noticia">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="3" align="left"><table width="590" border="0" cellpadding="0" cellspacing="0" class="none">
          <tr>
            <td align="right" class="td_vineta">&nbsp;</td>
            <td align="left" class="texto_cebra1">Dato</td>
            <td align="left" class="texto_cebra1">Campo</td>
            </tr>
		  <? 
            foreach($data->sheets[0]['cells'][1] as $filas)
            {
          ?>             
          <tr>
            <td width="46" align="right" class="td_vineta">&nbsp;</td>
            <td align="left" class="texto_cebra1"><?=$filas?></td>
            <td align="left" class="texto_cebra1">
            <select name="datos[]" id="datos[]" class="selectDatos">
              <option value="username">Usuario</option>
			  <option value="nombre">Nombre</option>
              <option value="puesto">Puesto</option>
			  <option value="rfc_cliente">RFC</option>
			  <option value="telefono">Telefono</option>
            </select></td>
          </tr>
          <? }?>
        </table></td>
      </tr>
      <tr>
        <td colspan="3" align="left"><table width="503" border="0" cellpadding="0" cellspacing="0" class="none">
          <tr>
            <td width="62" align="right" class="td_vineta">&nbsp;</td>
            <td width="441" align="left" class="texto_cebra1">
			<input type="submit" name="CONTINUAR" value="CONTINUAR" class="estilo_btn"/>
			<input name="insertarExcel" type="hidden" id="insertarExcel" value="1" />
			<input type="Button" onClick="abrirU('admin.php?seccion=6&menu=2','b3','')" name="REGRESAR" value="REGRESAR" class="estilo_btn"/>
			</td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td colspan="3" align="left" class="num_noticia">&nbsp;</td>
      </tr>
    </table></td>
  </tr>
</table>
</form>
<script type="text/javascript"> 
  $(document).ready(function() 
  {
	  $("#CONTINUAR").click(function()
	  {
		  var bandera=true;
		  $(".selectDatos").each(function(i)
		  {
			  var value=this.value;
			  var contador=i;
			  $(".selectDatos").each(function(j)
			  {
				  bandera=true;
				  if(j!=contador)
				  {
					if(value==this.value)
					{
						alert("Ha asignado un mismo campo para 2 columnas distintas");
						bandera=false;
						return false;
					}
				  }
			  });
			  if(bandera==false)
			  	return false;
		  });
		  if(bandera==true)
		  	$("#forma").submit();
		  	
	  });
	   
  })
</script>
<? }elseif(isset($_POST['insertarExcel']))
{
	require_once 'libs/ExcelReader/reader.php';
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');	
	$data->read("upload/fileUsuarios.xls");
	
	$exito=0;
	$erroneo=0;
	$exitoUpC=0;
	$erroneoUpC=0;
	$renglon=0;
	//print_r($_POST);
	//mysql_query("TRUNCATE TABLE clientes");
	foreach($data->sheets[0]['cells'] as $filas)
	{
		$renglon++;
		if($renglon >=2)
		{
		$i=0;
		$query="";
		$cadena="";
		for($i=1;$i<=5;$i++)
		{
			$cadena.=(empty($query))?$filas[$i]:",".$filas[$i];
			$query.=(empty($query))?$_POST['datos'][$i-1]."='".mysql_real_escape_string($filas[$i])."'":",".$_POST['datos'][$i-1]."='".mysql_real_escape_string($filas[$i])."'";
			
			if($i == 1)
			{
				$codigoC=$filas[$i];
					
			}
		}
		$queryDuplicate="Select username from usuariosweb where username='".$codigoC."' LIMIT 1";
		
			if(mysql_num_rows(mysql_query($queryDuplicate)) >= 1)
			{
				
				$query="Update usuariosweb set ".$query.", esProv='SI', activado='2' 
								  where username='$codigoC'";
				if(mysql_query($query))
				$exitoUpC++;
				else
				{
					$erroneoUpC++;
					$errores.=$erroneoUpC.".- ".$cadena."<br/>";
				}
			}
			else
			{
				$query="INSERT INTO usuariosweb SET ".$query.", pass=md5('temporal'), esAdmin='NO', esCliente='NO', esProv='SI', fechaCreacion=now(), todoRFC='NO', activado='2'";
				if(mysql_query($query))
				$exito++;
				else
				{
					
					$erroneo++;
					$errores.=$erroneo.".- ".$cadena."<br/>";
				}
			}
		}
	}
?>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="td_general">
  <tr>
    <td align="left" valign="top"><table width="590" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td colspan="3" height="7"></td>
      </tr>
      <tr>
        <td width="45" align="center" class="num_noticia">&nbsp;</td>
        <td width="545" colspan="2" align="left" class="txt_titulos">La carga se ha completado</td>
      </tr>
      <tr>
        <td colspan="3" align="center" class="num_noticia">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="3" align="left"><table width="590" border="0" cellpadding="0" cellspacing="0" class="none">
          <tr>
            <td class="HeaderMenuBck"><?=$exito?><br><?=$exitoUpC?></td>
            <td class="HeaderMenuBck">Usuarios se han insertado correctamente.<br>Usuarios se han actualizado correctamente</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
          </tr>
          <tr>
            <td class="HeaderMenuBck"><?=$erroneo?><br><?=$erroneoUpC?></td>
            <td class="HeaderMenuBck">Usuarios NO se han insertado correctamente.<br>Usuarios NO se pudieron actualizar</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
            <td align="center">&nbsp;</td>
          </tr>
          <tr>
            <td class="HeaderMenuBck">&nbsp;</td>
            <td class="HeaderMenuBck"><?=$errores?></td>
            <td width="22" align="center">&nbsp;</td>
            <td width="22" align="center">&nbsp;</td>
            <td width="22" align="center">&nbsp;</td>
            <td width="30" align="center">&nbsp;</td>
          </tr>
        </table></td>
      </tr>
	  <tr>
		<td colspan="3" align="left"><table width="503" border="0" cellpadding="0" cellspacing="0" class="none">
			<input type="Button" onClick="abrirU('admin.php?seccion=6&menu=2','b3','')" name="REGRESAR" value="REGRESAR" class="estilo_btn"/>
		</td>
	  </tr>
      <tr>
        <td colspan="3" align="left"><table width="503" border="0" cellpadding="0" cellspacing="0" class="none">
          <tr>
            <td width="62" align="right" class="td_vineta">&nbsp;</td>
            <td width="441" align="left" class="texto_cebra1">&nbsp;</td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td colspan="3" align="left" class="num_noticia">&nbsp;</td>
      </tr>
    </table></td>
  </tr>
</table>
<? }?>