<?php

if (!isset($PathPrefix)) {
	$PathPrefix='../';
}

$PageSecurity=0;

ob_start();

include($PathPrefix . 'includes/session.php');
$Title=_('Import Contacts');
include('includes/header.php');

$FieldHeadings = array(
	'email', 		//  0 'email',
	'full_name',    //  1 'full_name',
	'phone_number',	//  2 'phone_number',
	'company_name',	//  3 'company_name',
	'location',		//  4 'location',
	'owner' 		//  5 'owner',
);

if ( isset($_POST['gettemplate']) || isset($_GET['gettemplate']) ) //download an import template
{
	ob_clean();

	$csv = '"' . implode('","',$FieldHeadings) . '"';

	header("Content-Type: application/force-download");
	header("Content-Type: application/octet-stream");
	header("Content-Type: application/download");

	// disposition / encoding on response body
	header("Content-Disposition: attachment; filename=ImportTemplate.csv");
	header("Content-Transfer-Encoding: binary");

	echo $csv;

	exit;
}
else if(isset($_POST['import']))
{
	if(isset($_SESSION['last_id']) && $_SESSION['last_id'] == $_POST['key'])
    {
        // do nothing if same id as previous indicating a form resubmit
        prnMsg('Import file has been processed and will not be processed again', 'warn');
	}
	else
	{
		$_SESSION['last_id'] = $_POST['key'];

		$FieldTarget = count($FieldHeadings);
		
		//check file info
		$FileName = $_FILES['import_file']['name'];
		$TempName  = $_FILES['import_file']['tmp_name'];
		$FileSize = $_FILES['import_file']['size'];

		$ext=substr($FileName,strrpos($FileName,"."),(strlen($FileName)-strrpos($FileName,".")));
		
		//check file must be have csv extention
		if($ext!=".csv")
		{
			prnMsg('Failed to import! Only .csv file format supported','error');
		}
		else
		{
			//get file handle
			$FileHandle = fopen($TempName, 'r');

			//get the header row
			$headRow = fgetcsv($FileHandle, 0, ",",'"');  // Modified to handle " "" " enclosed csv - useful if you need to include commas in your text descriptions

			//check for correct number of fields
			if ( count($headRow) != count($FieldHeadings) ) {
				prnMsg (_('File contains '. count($headRow). ' columns, expected '. count($FieldHeadings). '. Try downloading a new template.'),'error');
				fclose($FileHandle);
				include('includes/footer.php');
				exit;
			}

			//test header row field name and sequence
			$head = 0;
			foreach ($headRow as $headField) {
				if ( mb_strtoupper($headField) != mb_strtoupper($FieldHeadings[$head]) ) {
					prnMsg (_('File contains incorrect headers '. mb_strtoupper($headField). ' != '. mb_strtoupper($FieldHeadings[$head]). '. Try downloading a new template.'),'error');  //Fixed $FieldHeadings from $headings
					fclose($FileHandle);
					include('includes/footer.php');
					exit;
				}
				$head++;
			}


			// get list of existing active www_users for the owners
			$sql = "SELECT userid FROM www_users WHERE blocked = 0";
			$result = DB_query($sql);
			while($myrow = DB_fetch_array($result))
			{
				$owners[] = $myrow['userid'];
			}

			// set a default status
			$sql = "SELECT id FROM lms_status WHERE probability>0 AND probability<1 ORDER BY probability LIMIT 1";
			$result = DB_query($sql);
			while($myrow = DB_fetch_array($result))
			{
				$status = $myrow['id'];
			}

			$imported_list = '<table class="table table-striped table-condensed">
								<thead>
									<tr>
										<th>Name</th>
										<th>Phone Number</th>
										<th>Email</th>
										<th>Company</th>
										<th>Locations</th>
										<th>Owner</th>
									</tr>
								</thead>
								<tbody>';

			//start database transaction
			DB_Txn_Begin();

			//loop through file rows
			$row = 1;
			while ( ($myrow = fgetcsv($FileHandle, 0, ",")) !== FALSE )
			{
				//check for correct number of fields
				$fieldCount = count($myrow);
				if ($fieldCount != $FieldTarget){
					prnMsg (_($FieldTarget. ' fields required, '. $fieldCount. ' fields received'),'error');
					fclose($FileHandle);
					DB_Txn_Rollback();
					include('includes/footer.php');
					exit;
				}

				// cleanup the data (csv files often import with empty strings and such)
				foreach ($myrow as &$value) {
					$value = trim($value);
				
				}
				
				//next validate inputs are sensible
				$myrow[2] = str_ireplace(array(' ', '-', 'p', ':'), '', $myrow[2]); // remove all - p: and space
				
				if(empty($myrow[5]))
				{
					$myrow[5] = $_SESSION['UserID'];
				}
				else if($myrow[5]!='' && !in_array($myrow[5], $owners)){
					$InputError = 1;
					prnMsg ('Invalid owner id detected','error');
				}


				if ($InputError !=1){

					//attempt to insert the stock item
					$sql = "INSERT INTO lms_leads (
								email,
								name,
								contactno,
								company,
								location,
								owner,
								remarks,
								status
							)
							VALUES (
								'" . DB_escape_string($myrow[0]) . "',
								'" . DB_escape_string($myrow[1]) . "',
								'" . DB_escape_string($myrow[2]) . "',
								'" . DB_escape_string($myrow[3]) . "',
								'" . DB_escape_string($myrow[4]) . "',
								'" . DB_escape_string($myrow[5]) . "',
								'',
								'" . $status . "'
							)";

					$ErrMsg =  _('The account group could not be added because');
					$DbgMsg = _('The SQL that was used to add the account failed was');
					$result = DB_query($sql, $ErrMsg, $DbgMsg, true);

					if (DB_error_no() != 0) { //item insert failed so set some useful error info
						$InputError = 1;
						prnMsg(_($result),'error');
					}
					else
					{
						$imported_list .= '	<tr>
												<td>'.$myrow[1].'</td>
												<td>'.$myrow[2].'</td>
												<td>'.$myrow[0].'</td>
												<td>'.$myrow[3].'</td>
												<td>'.$myrow[4].'</td>
												<td>'.$myrow[5].'</td>
											</tr>';
					}

				}

				if ($InputError == 1) { //this row failed so exit loop
					break;
				}

				$row++;

			}

			if ($InputError == 1) { //exited loop with errors so rollback
				prnMsg(_('Failed on row '. $row. '. Batch import has been rolled back.'),'error');
				DB_Txn_Rollback();
				$imported_list = '';
			} else { //all good so commit data transaction
				DB_Txn_Commit();
				prnMsg( _('Batch Import of') .' ' . $FileName  . ' '. _('has been completed. All transactions committed to the database.'),'success');
				$imported_list .= '</tbody></table>';
			}

			fclose($FileHandle);
		
		}
	}
}

?>

<div class="row">
    <div class="col-sm-12">
        <h2>Import Contacts</h2>
    </div>
</div>

<div class="row">
	<div class="col-sm-12">
		<form method="post" enctype="multipart/form-data">
			<div class="form-group">
				<label for="import_file">Select file to import:</label>
				<input type="file" class="form-control" name="import_file" id="import_file" required>
			</div>
			<div class="form-group"> 
				<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
				<input type="hidden" name="key" value="<?php echo uniqid(); ?>" />
				<button type="submit" class="btn btn-primary" name="import">
					Import <span class="glyphicon glyphicon-import"></span>
				</button>
				<a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '?gettemplate=1'; ?>">Get Import Template</a>
			</div>
		</form>
	</div>
</div>

<?php
if($imported_list != '')
{
	echo '<div class="row">
		<div class="col-sm-2"></div>
		<div class="col-sm-8"><h3 class="text-center">Imported Record(s)</h3></div>
		<div class="col-sm-2"></div>
	</div>
	<div class="row">
		<div class="col-sm-12">
			<div class="table-responsive">
				'.$imported_list .'
			</div>
		</div>
	</div>';
}
include('includes/footer.php');
?>