<?php 
include("connect.php");
include ("./assets/PHPExcel/IOFactory.php");

 
$path = 'admin/uploads/autoupload/';

$files = array_diff(scandir($path), array('.', '..'));

foreach($files as $key => $file){
	
	$file = explode("-",$file);
	$filename = $file[0] . "-" . $file[1];
	
	switch($file[1]){
		case "mtd.xls":
			$result = RunSalesMTD($path . $filename);
			$result = json_decode($result);
			echo "MTD";
			var_dump($result);
			if($result->result->falseCount == 0){
				
				unlink($path . $filename);
			}else{
				var_dump($result->result);
			}
			break;
		case "incentivo.csv":
			copy($path . $filename,'./admin/uploads/pickingincentive.csv');
			$result = file_get_contents_curl("http://orders.eurojaponautosupply.com/admin/import_csv.php?for=pickingincentive&a=append");
			$result = json_decode($result);
			echo "INCENTIVO";
			var_dump($result);
			if($result->result->falseCount == 0){
				unlink($path . $filename);
			}
			break;
		case "invoice.csv":
			copy($path . $filename,'./admin/uploads/invoice.csv');
			$result = file_get_contents_curl("http://orders.eurojaponautosupply.com/admin/import_csv.php?for=invoice&a=replace");
			$result = json_decode($result);
			echo "INVOICE";
			var_dump($result);
			if($result->result->falseCount == 0){
				unlink($path . $filename);
			}
			break;
		case "credit.csv":
			copy($path . $filename,'./admin/uploads/credit.csv');
			$result = file_get_contents_curl("http://orders.eurojaponautosupply.com/admin/import_csv.php?for=credit&a=replace");
			$result = json_decode($result);
			echo "CREDIT";
			var_dump($result);
			if($result->result->falseCount == 0){
				unlink($path . $filename);
			}
			break;
	}
}
function RunSalesMTD($file){
	
/** Load $inputFileName to a PHPExcel Object  **/
	$objPHPExcel = PHPExcel_IOFactory::load($file);
	$objPHPExcel->getActiveSheet()->removeRow(1);
	$objPHPExcel->getActiveSheet()->removeColumnByIndex(5);
	
	
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
	$objWriter->save('./admin/uploads/salesmanquota.csv');
	return file_get_contents_curl("http://orders.eurojaponautosupply.com/admin/import_csv.php?for=salesmanquota&a=replace");
	
}

function file_get_contents_curl($url){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, false);
	$data = curl_exec($curl);
	curl_close($curl);
	return $data;
}
?>
