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

 
$function = $_REQUEST['f'];
if($function == "salesmtd"){
	$url = $_REQUEST['url'];
	RunSalesMTD($url);
}elseif($function == "newsalesmtd"){
	RunNewSalesMTD();
}

function RunSalesMTD($url){
	$file = file_get_contents_curl($url);
	 file_put_contents("./tmp/salesmtd.xlsx", $file);
	$inputFileName = "./tmp/salesmtd.xlsx";

/** Load $inputFileName to a PHPExcel Object  **/
	$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
	$objPHPExcel->getActiveSheet()->removeRow(1);
	
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
	$objWriter->save('./admin/uploads/salesmanquota.csv');
	file_get_contents_curl("http://maker.ifttt.com/trigger/finished_quota_csv/with/key/lFjeHUspNA7nEk3ROVAaC");
	
}
function RunNewSalesMTD(){
	$files = array_diff(scandir("./reports/"),array('..', '.'));
	foreach($files as $filename){
		$file_parts = pathinfo($filename);
		$filename= "./reports/" . $filename;
		if($file_parts['extension'] == "csv"){
			read_and_delete_first_line($filename);
			rename($filename, './admin/uploads/salesmanquota.csv');
			file_get_contents_curl("http://orders.eurojaponautosupply.com/admin/import_csv.php?for=salesmanquota&a=replace");
			unlink($filename);
		}
	}
	
	//file_get_contents_curl("http://maker.ifttt.com/trigger/finished_quota_csv/with/key/lFjeHUspNA7nEk3ROVAaC");
	
}
function read_and_delete_first_line($filename) {
  $file = file($filename);
  $output = $file[0];
  unset($file[0]);
  file_put_contents($filename, $file);
  return $output;
}
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;
}



function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}
?>
