<?php 
include_once("../connect.php");
global $con;
include_once("../session.php");

$for = $_REQUEST['t'];
$id = isset($_REQUEST['id'])?$_REQUEST['id']:"";
 ?>
 
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />
 
     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <script src="../js/functions.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
           <script src="../js/fileinput.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
				 <script src="../js/bootstrap-waitingfor.min.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
               
       //        $('.grpline').css("width", "100px");
             });
           </script>

     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	<link rel="stylesheet" href="../css/fileinput.min.css"/>
   </head>
   <body>
<?php 
	//include("navbar.php");
	$page['sales'] = array(
								"page_title" => "Sales CSV Import",
								"page_body" => "In order to import the sales data, the CSV data must be in the following order: <br />
								<pre><samp>| LOCATION | SALESMAN | SALE AMOUNT | GROSS MARGIN | MARGIN PERCENT | PART NUMBER | DESCRIPTION | INVOICE NUMBER | DATE | CUSTOMER NUMBER | CUSTOMER NAME | LINECODE |</samp></pre>");
	$page['payments'] = array(
								"page_title" => "Payments CSV Import",
								"page_body" => "In order to import the Payments data the CSV data must be in the following order: <br />
								<pre><samp>| SALESMAN | LOCATION | AccountNumber | CUSTOMER NAME | INVOICE NUMBER | DATE | PAYMENT AMT | DISCOUNT | TAX (REFERENCE) |</samp></pre>");
	$page['specials'] = array(
								"page_title" => "Specials CSV Import",
								"page_body" => "In order to import the Specials data the CSV data must be in the following order: <br />
								<pre><samp>| LINE | SKU |</samp></pre>");
	$page['specialCustomer'] = array(
								"page_title" => "Specials CSV Import",
								"page_body" => "In order to import the Customers with Special Pricing data the CSV data must be in the following order: <br />
								<pre><samp>| ACCOUNT NUMBER |</samp></pre>");
	$page['specialCustomerItems'] = array(
								"page_title" => "Specials CSV Import",
								"page_body" => "In order to import the Items for the Customers With Special Pricing data the CSV data must be in the following order: <br />
								<pre><samp>| LINE | SKU |</samp></pre>");
	$page['salesHeaders'] = array(
								"page_title" => "Sales Headers CSV Import",
								"page_body" => "In order to import the sales headers data the CSV data must be in the following order: <br />
								<pre><samp>| ST | ACCOUNT NUMBER | JOB | INVOICE NUMBER | REFERENCE | SUBTOTAL | IVU | MONTH | </samp></pre>");
?>
        
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
     <div class="container " style="padding-top: 10px;">
     </div>    
		<div class="panel panel-default">
		  <div class="panel-heading">
		    <h3 class="panel-title"><?= $page[$for]['page_title']; ?></h3>
		  </div>
		  <div class="panel-body">
		    <?= $page[$for]['page_body']; ?>
		    The CSV file should NOT contain the column headers.	
		    <p class="bg-danger" id="uploadError"></p>
		    <div class="well">
		    	<input id="inputCSV" type="file" name="csv" class="file" data-show-preview="false">
		    	<select name="replace_append" class="form-control">
		    		<option value="replace">Replace [WARNING - THIS WILL DELETE THE ENTIRE TABLE]</option>
						<option value="append">Append/Update</option>
		    		
		    	</select>
		    </div>
		    
		    <div class="alert alert-info" style="display: none;" id="uploadSuccess" role="alert">
		    	File has been uploaded successfully! Proceeding to Insert the data into the table...</div>
		  </div>
		  <div class="alert alert-success" style="display: none;" id="importSuccess" role="alert">The inventory has been imported successfully!</div>
		  <div class="alert alert-danger" style="display: none;" id="importFail" role="alert">There has been an error while importing the data.</div>
		</div>
     <?php 
      ?>
     <script type="text/javascript">
     $('#inputCSV').on('filebatchuploadsuccess', function(event, data, previewId, index) {
         response = data.response;
         if(response.fileuploaded == true){
			$("#uploadSuccess").css('display', "");
			var a = $("[name=replace_append]").val();
			runImportCSV("<?= $for; ?>", a);
			
         }
         
     });
     $('#inputCSV').on('fileuploaded', function(event, data, previewId, index) {
         response = data.response;
         if(data.response.fileuploaded == true){
     		$("#uploadSuccess").css('display', "");
     		var a = $("[name=replace_append]").val();
     		runImportCSV("<?= $for; ?>", a);
         }
         
     });
     	var a = $("[name=replace_append]").val();
     	$("[name=replace_append]").on("change", function(event) {
     		a = $("[name=replace_append]").val();
     		$("#inputCSV").fileinput({
     			'showUpload':true, 
     			'uploadUrl':"upload_csv.php?for=<?= $for; ?>",
     			'fileTypeSettings':'text',
     			'elErrorContainer':'#uploadError',
     		});
     	});
     	$("#inputCSV").fileinput({
     		'showUpload':true, 
     		'uploadUrl':"upload_csv.php?for=<?= $for; ?>",
     		'fileTypeSettings':'text',
     		'elErrorContainer':'#uploadError',
     	});
     	function runImportCSV(destination, a) {
				waitingDialog.show('Processing Data');
     		$.get("mod.php?p=commission&a=import_csv&for=" + destination + "&t=" + a, function(data) {
				waitingDialog.hide();
				console.log(data);
				
				
				var errorText = "";
				if (data.result.result === "true") {
					
					if (data.result.falseCount > 0) {
						for (var i = 0; i < data.result.errors.length; i++) {
							errorText = errorText + "Error " + (i+1) + ": " + data.result.errors[i] + "<br />";
						}
						errorText = "<br />Errors found: <br />" + errorText;
					}
					$("#importSuccess").html("Import Success! <br /> Total Rows Processed: " + data.result.rowCount + "<br />" + "Rows Successfully Inserted: " + data.result.trueCount + "<br />Rows with errors: " + data.result.falseCount + errorText);
					
					$("#importSuccess").css('display', "");
				}else {
					errorText = "";
					for (var i = 0; i < data.result.errors.length; i++) {
						errorText = errorText + "Error " + (i+1) + ": " + data.result.errors[i] + "<br />";
					}
					var text = $("#importFail").text();
					$("#importFail").html(text + "<br />Errors found: <br />" + errorText);
					$("#importFail").css('display', "");
				}
     			
     		
     		})
					.fail(function(){
							alert("Server has stopped the script. Timeout Error. ");
						});
     	}     	
     
     </script>
   </body>
 </html>