<?php 
@set_time_limit(900);

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
$table = "##contacts";

$CSVValidColumns = array('EMAIL','FIRSTNAME','LASTNAME','MISC_1','MISC_2','MISC_3');
$error = "";
$msg = "";
$fileElementName = 'fileToUpload';
$addrid = $_GET['addrid'];
$filename = $_FILES['fileToUpload']['name'];
$fileExt = substr($filename, -4);
if (empty($addrid))
{
	echo '{';
	echo "error: 'Address book is missing'\n";
	echo '}';
	exit;
}

if(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
{
	echo '{';
	echo "error: 'No file was uploaded'\n"; 
	echo '}';
	exit;
}	
else if ($fileExt != '.csv')
{
	echo '{';
	echo "error: '$fileExt Please upload CSV file only.'\n"; 
	echo '}';
	exit;

}

$row = 1;
$handle = fopen($_FILES['fileToUpload']['tmp_name'], "r");
$csvColumnSeq = array();

$colMappings = false;
$tempArray = array();


while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
	$num = count($data);
	//echo "<p> $num fields in line $row: <br /></p>\n";
	
	## EMAIL IS THE ONLY MANDATORY COLUMN
	## ALL OTHER COLUMNS ARE OPTIONAL
	
	
	if (!$colMappings)
	{
		$tempArray = array_keys($data, 'EMAIL');
		$EMAIL = $tempArray[0];
		
		$tempArray = array_keys($data, 'FIRSTNAME');
		$FIRSTNAME = $tempArray[0];
		
		$tempArray = array_keys($data, 'LASTNAME');
		$LASTNAME = $tempArray[0];
		
		$tempArray = array_keys($data, 'MISC_1');
		$MISC_1 = $tempArray[0];
		
		$tempArray = array_keys($data, 'MISC_2');
		$MISC_2 = $tempArray[0];
		
		$tempArray = array_keys($data, 'MISC_3');
		$MISC_3 = $tempArray[0];
	
		if (strlen($EMAIL) == 0)
		{
			echo '{';
			echo "error: 'Email column heading is mandatory'\n"; 
			echo '}';
			exit;
		}
		$colMappings = true;	
	}
	
	for ($c=0; $c < $num; $c++) 
	{
		if ($row == 1)
		{
			## CHECK HEADER ROWS. MAKE SURE THE HEADER ROWS CONTAIN THE NAME COLUMN HEADER
			## AS PER THE SPECIFICATIONS
			
			/*
			VALID HEADER ROW COLUMN NAMES ARE:
			EMAIL
			FIRSTNAME
			LASTNAME
			MISC_1
			MISC_2
			MISC_3
			*/
			
			if (in_array($data[$c], $CSVValidColumns))
			{
				//echo "good";
				$csvColumnSeq[] = $data[$c];
			}
			else
			{
				echo '{';
				echo "error: 'CSV contains invalid header(s)'\n";
				echo '}';
				exit;

			}
			
		}
		else
		{
			## ONLY PROCEED IF THERE ARE NO ERRORS IN THE HEADER ROW.
			if ($error == "")
			{
				if ($c == 0)
				{
					$query = "INSERT INTO $table SET
					ADDR_ID	= '$addrid',  
					EMAIL='$data[$EMAIL]',";
					 
					if (strlen($FIRSTNAME) > 0)
						$query .= "FIRSTNAME = '$data[$FIRSTNAME]',";
					else
						$query .= "FIRSTNAME = '',";
						
					if (strlen($LASTNAME) > 0)
						$query .= "LASTNAME = '$data[$LASTNAME]',";
					else
						$query .= "LASTNAME = '',";
						
					if (strlen($MISC_1) > 0)
						$query .= "MISC_1 = '$data[$MISC_1]',";
					else
						$query .= "MISC_1 = '',";	
	
					if (strlen($MISC_2) > 0)
						$query .= "MISC_2 = '$data[$MISC_2]',";
					else
						$query .= "MISC_2 = '',";
								
					if (strlen($MISC_3) > 0)
						$query .= "MISC_3 = '$data[$MISC_3]',";
					else
						$query .= "MISC_3 = '',";
									
					$query .= "LAST_UPDATED=NOW()";
					$insertId = $funcObj->insertQuery($query);
					//echo $data[$c] . "<br />\n";
				}
			}
		}	
	}
	$row++;

}

## DELETE DUPLICATE RECORDS
$conntion = $sqlObj->mysqlClass();
$query = "SELECT ID FROM smlr_contacts WHERE ADDR_ID = '$addrid' GROUP BY EMAIL having count(EMAIL) > 1";
$resultSet = mysqli_query($conntion,$query);
$delIDs = array();
while ($row = mysqli_fetch_array($resultSet,MYSQLI_BOTH))
{
	$delIDs[] = $row["ID"];
}

$result = implode(",", $delIDs);

if (count($delIDs))
{
	$query = "DELETE FROM ##contacts WHERE ID IN ($result)";
	$funcObj->CustomDelete($query);
}

echo "{";
echo				"error: '" . $error . "',\n";
echo 				"msg: 'Successfully Imported'\n";
echo "}";

fclose($handle);

?>