<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
	if ($_FILES['userfile']['error']) {
		switch ($_FILES['userfile']['error']) {
			case 1:
			case 2: echo __('Filesize is higher than your PHP installation allows, please contact your Hostingpartner', 'wct'); break;
			case 3: echo __('Fileupload was interupted and only a part of the file was uploaded' , 'wct'); break;
			case 4: echo __('No file was uploaded?!?', 'wct'); break;
		}
	}
	else {
		if ($_FILES['userfile']['type'] == 'text/csv' OR $_FILES['userfile']['type'] == 'application/vnd.ms-excel'  OR $_FILES['userfile']['type'] == 'application/csv') {
			$handle = fopen ($_FILES['userfile']['tmp_name'], 'r');
			$i = '0';
			while (($data = fgetcsv($handle, 1000, ';', '"')) !== FALSE) {
				$i++;
				if ($i != '1') {
					$query = "REPLACE INTO `".$wpdb->prefix."wct".$tableid."` VALUES (\"". html_entity_decode(implode("\",\"", $data),ENT_QUOTES,'UTF-8') ."\")";
					$wpdb->get_row($query);
				}
			}
			echo __('CSV File has been imported sucessfully', 'wct');
		}
		else {
			echo __('Please upload only valid CSV Files!', 'wct');
		}
		unlink($_FILES['userfile']['tmp_name']);
	}
}

$qry = $wpdb->get_row("SELECT `secret` FROM `".$wpdb->prefix."wct_list` WHERE `id`='".$tableid."' LIMIT 1;");

echo "<div style=\"width:350px;\"><h2>" . __('Export', 'wct') ." ". __('Table', 'wct') . "</h2>". __('Klick on a Icon to export table', 'wct')."<br />".
     "<a target=\"_blank\" href=\"".plugins_url('custom-tables/dl.php')."?i=".$tableid."&l=".$qry->secret."&t=excel\"><img src=\"".plugins_url('custom-tables/img/excel.png')."\" border=\"0\" alt=\"Excel\" /></a>".
     "&nbsp;<a target=\"_blank\" href=\"".plugins_url('custom-tables/dl.php')."?i=".$tableid."&l=".$qry->secret."&t=csv\"><img src=\"".plugins_url('custom-tables/img/csv.gif')."\" border=\"0\" alt=\"CSV\" /></a>".
     "</div><div style=\"float:left;width:350px;height:300px;\"><h2>" . __('Import', 'wct') ." ". __('Table', 'wct') . "</h2>".
     "<form enctype=\"multipart/form-data\" action=\"admin.php?page=wct_table_".$tableid."&wcttab=importexport\" method=\"post\">".
     __('Please select CSV File to upload and import', 'wct').": <input name=\"userfile\" type=\"file\" value=\"\">".
     "<input type=\"submit\" name=\"fileupload\" value=\"". __('Upload File', 'wct')."\"></form></div>".
     "<div><h2>" . __('Import', 'wct') ." ". __('Instructions', 'wct') . "</h2>".
     __('To import a CSV, make sure that you do not touch the first line in the exported CSV. Each modification will be wiped out in the import process. You cannot create new fields or rename them trotught the CSV file!','wct')."<br/><br/>".
     __('The file to import need to be saved as a CSV (Delimiter splitted) File (fields splitted with ; and optional enquoted &quot; fields). Excel is supporting this save possibility in all known versions.','wct')."</div>";

?>