<?
/*
Copyright (c) 2009 Ronnie Garcia, Travis Nickels

This file is part of Uploadify v1.6.2

Permission is hereby granted, free of charge, to any person obtaining a copy
of Uploadify and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

UPLOADIFY IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

if (!empty($_FILES)) 
{
    require("../../conectar.php"); 
	$url="admin.php?seccion=2&accion=listar";
	$tabla="destinatario";
	$indice="id_destinatario";
	
	$tempFile = $_FILES['Filedata']['tmp_name'];
	
	/*////////////////////////////////////////////////////////////////////////
	/La variable $folder me permite recibir el valor que por alguna razón no /
	/puedo recibir desde $_SESSION['id_uduario']. Hice una pequeña trampa    /
	/al llamar a JqUploader; cuando envío el folder, es decir, la            /
	/carpeta en la que voy a almacenar el xls que cargue, le envío, separado /
	/por un punto el valor de $_SESSION['id_uduario']. Ya en este archivo ha-/
	/go un explode y obtengo tanto el folder (posición $folder[0]) como el   /
	/id_usuario(posición $folder[1]).                                        /
	////////////////////////////////////////////////////////////////////////*/
	  
	$folder=explode(".",$_REQUEST['folder']);
	$targetPath = $_SERVER['DOCUMENT_ROOT'] . $folder[0]. '/';
	$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
	
	move_uploaded_file($_FILES['Filedata']['tmp_name'],$targetFile);
	


	include ("../../backOffice.class.php");
	$backOffice=new backOffice();
    $backOffice->redirecciona($url);
   
    //Llama a ExcelReader...  
	require_once '../../ExcelReader/reader.php';
	$data = new Spreadsheet_Excel_Reader();
	
	$data->setOutputEncoding('CP1251');
	
	$data->read("../../../upload/".$_FILES['Filedata']['name']."");
	
	//Obtiene el id correspondiente a esta nueva carga de lista...
	$qMaxIdList="SELECT MAX(id_lista) as id_lista FROM destinatario WHERE 1";
	$rMaxIdList=mysql_query($qMaxIdList);
	$dMaxIdList=mysql_fetch_assoc($rMaxIdList);
	$nMaxIdList=mysql_num_rows($rMaxIdList);
	
	//Si no encontró nada en la consulta anterior el id_lista será 1 por default...
	if ($nMaxIdList<1)
	   $IdLista=1;
	if ($nMaxIdList>0)
	   $IdLista=$dMaxIdList['id_lista']+1;
		
	for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) 
	    {
		  $ArrayDatos="";
		  for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) 
		  {
			$ArrayDatos.="".$data->sheets[0]['cells'][$i][$j].",";
		  }
		  	$Datos=explode(",",$ArrayDatos);
			
			if($Datos[0]!="" && $Datos[1]!="" && $Datos[2]!="")
			{
				if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$Datos[1])) 
				{
					$_POST['nombre']=$Datos[0];
					$_POST['email']=$Datos[1];
					$_POST['idioma']=$Datos[2];
					//$_POST['desarrollo']=$Datos[3];
					$_POST['id_usuario']=$folder[1];
					$_POST['fecha']=date("Y-m-d");
					$_POST['hash']=sha1($i.date("Ymdhis").$Datos[1].$folder[1]);
					$_POST['id_lista']=$IdLista;
					$backOffice->manipulaDatos($tabla,$indice,$_POST,(isset($_POST['editar']))?$id=$_POST[$indice]:$id=0,$url);
				    echo "ok";
				}
				else
				{
				   echo"fail";
				}
	        }
		}
}		 
?>