<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/

$page_security = 'CRM_SETTINGS';
$path_to_root="../..";

include($path_to_root . "/includes/session.inc");
add_access_extensions();
include($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/ui.inc");

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}
if(isset($_POST['exportcsv'])){ //Export CSV
	global $db_connections;
	$company_name = $db_connections[$_SESSION['wa_current_user']->company]['name'];
	if(isset($_POST['Exporttype'])){
		if($_POST['Exporttype'] == 1)
			ExportLeads($company_name);
		elseif($_POST['Exporttype'] == 2)
			ExportProjects($company_name);
		elseif($_POST['Exporttype'] == 3)
			ExportCustomers($company_name);
		elseif($_POST['Exporttype'] == 4)
			ExportSuppliers($company_name);
		elseif($_POST['Exporttype'] == 5)
			ExportTasks($company_name);
		elseif($_POST['Exporttype'] == 6)
			ExportOpportunities($company_name);

	}
	//meta_forward($_SERVER['PHP_SELF'], "Exported=yes");
	
}

page(_($help_context = "Import and Export CSV"), false, false, "", $js);

if(isset($_GET['Exported']))
	display_notification(_("The Selected Type Exported To CSV"));
//------------------------------------------------------------------------------------
if (isset($_POST['submitcsv'])){

	//$content = base64_encode(file_get_contents($_FILES['filename']['tmp_name']));
	$tmpname = $_FILES['filename']['tmp_name'];
	if(pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION) == 'csv'){
		$dir =  dirname(__FILE__).'/backups/tmp';
		if (!file_exists($dir))	{
			mkdir ($dir,0777);
			$index_file = "<?php\nheader(\"Location: ../index.php\");\n";
			$fp = fopen($dir."/index.php", "w");
			fwrite($fp, $index_file);
			fclose($fp);
		}

		$filename = basename($_FILES['filename']['name']);
				
		move_uploaded_file($tmpname, $dir."/".$filename);
	
		//$arrResult  = array();
		$handle     = fopen($dir.'/'.$filename, "r");
		if(empty($handle) === false) {
			$flag = true;
			$id_exsit = $email_exist = 0; 
			$data = array();
		    while(($data1 = fgetcsv($handle, 1000, ",")) !== FALSE){
		    	if($flag) { $flag = false; $header = $data; continue; }		 
		    	$data[] = $data1;   	
		        //print_r($data);
		    }
		    if($_POST['type'] == 6)
		    	ImportOpportunities($data);
		    elseif($_POST['type'] == 2)
		    	ImportProjects($data);
		    elseif($_POST['type'] == 3)
		    	ImportCustomers($data);
		   	elseif($_POST['type'] == 4)
		    	ImportSuppliers($data);
		    elseif($_POST['type'] == 5)
		    	ImportTasks($data);
		    else
		    	$result = ImportLeads($data);

		    fclose($handle);
		}
		
		unlink($dir.'/'.$filename);
		$note = '';
		if(!empty($result)){
			$note .=" And Existing data's ";
			foreach($result as $res)
				$note .= " And ".$res;
			$note .=" are not inserted!";
		}
		display_notification(_("Successfully Imported ".$note));
	}else{
		display_error("Please Select a Valid CSV File to import Employee data.");
	}
	//$Mode = 'RESET';
}

echo '<center> <p style="text-align: justify; max-width:400px; width:100%;"> From the given CSV, you have to input date in a standard format. The Date format should be `YYYY-MM-DD` for all date fields.</p></center>';
start_form(true);
	start_outer_table(TABLESTYLE);
	table_section(1);
	table_section_title(_("Export"));
	crm_task_types_list_row(_("Select a Type"). " :", 'Exporttype', null,  _("Select Type"), false, true, false, true);
	label_row("", "");
	submit_row('exportcsv', 'Export CSV');
	table_section(2);
	table_section_title(_("Import"));

	crm_task_types_list_row(_("Select a Type"). " :", 'type', null,  _("Select Type"), true, true, false, true);
	if(list_updated('type')){
		if(get_post('type') == 6){
			$sample_filename = 'opportunities';
		} elseif(get_post('type') == 2){
			$sample_filename = 'projects';
		} elseif(get_post('type') == 3){
			$sample_filename = 'customers';
		} elseif(get_post('type') == 4){
			$sample_filename = 'suppliers';
		} elseif(get_post('type') == 5){
			$sample_filename = 'tasks';
		} else {
			$sample_filename = 'leads';
		}
		$Ajax->activate('_page_body');
	}
	if(isset($sample_filename))
	label_row(_("Sample File For CSV"), '<a href="'.$path_to_root.'/modules/KvcodesCRM/samples/'.$sample_filename.'.csv" > Click here to Download </a>');
	file_row("Select CSV to Import", "filename", null);
	label_row("", "");
	submit_row('submitcsv', 'Import CSV');
	end_outer_table();
	br();
	
end_form();

end_page(); ?>