<?php 
include("connect.php");
include ("./assets/PHPExcel/IOFactory.php");
include("functions.php");
 
$function = $_REQUEST['f'];
if($function == "sales"){
	
	ImportSales();
}elseif($function == "payments"){
	ImportPayments();
}
function ImportSales(){
	//$files = ["sales_history_header.csv","sales_detail.csv"];
	$folder = "./uploads/";
	$filename = $folder . "sales_history_header.csv";
	if(file_exists($filename)){
		//read_and_delete_first_line($filename);
		CSVImport("SALES_HISTORY_HEADER", array("`ST`", "`SaleDate`", "`AccountNumber`", "`Job`", "`InvoiceNumber`", "`Reference`", "`Subtotal`", "`IVU`", "`TaxCode`"),$filename);
		
		//CSVImport($table, $fields, $csv_fieldname='csv', $additionalParams = array()) 
	}
	$filename = $folder . "sales_detail.csv";
	if(file_exists($filename)){
		//read_and_delete_first_line($filename);
		CSVImport("SALES_HISTORY_DETAIL", array("`ST`", "`Salesman`", "`Price`", "`GrossMargin`", "`MarginPercent`", "`PartNumber`", "`Description`", "`InvoiceNumber`", "`AccountNumber`", "`LineCode`"),$filename);
		
		//CSVImport($table, $fields, $csv_fieldname='csv', $additionalParams = array()) 
	}
	//unlink($filename);
	
}

function ImportPayments(){
	//$files = ["sales_history_header.csv","sales_detail.csv"];
	$folder = "./uploads/";
	$filename = $folder . "payment_detail.csv";
	if(file_exists($filename)){
		//read_and_delete_first_line($filename);
		$result = CSVImport("PAID_INVOICE", array("`Salesman`", "`ST`", "`AccountNumber`", "`CustomerName`", "`InvoiceNumber`", "`PaidDate`", "`Reference`", "`PaymentAmt`", "`Discount`", "`Job`", "`Tax`"),$filename);
		
		//CSVImport($table, $fields, $csv_fieldname='csv', $additionalParams = array()) 
	}
	
	
}

function read_and_delete_first_line($filename) {
  $file = file($filename);
  $output = $file[0];
  unset($file[0]);
  file_put_contents($filename, $file);
  return $output;
}



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