<?php

include_once('connect.php');
include_once('functions.php');
include_once('modules/payment/payment.classes.php');
//echo date('Y-m-d H:i:s', time()-4*60*60);
ini_set('display_errors', 1);

$handle = fopen("ACCREC.TXT", "r");
if($handle){
	$index = 0;

	
	// if(!$stmt){
	// 	die("error on db: " . mysqli_error($con) );	
	// }
	
	$custData = [];
	$custName = [];
	$ADDED = 0;
	while (($buffer = fgets($handle)) !== false) {
		//var_dump( stripos($buffer, "Run Date") !== false );
		//var_dump(preg_match("/^\d{7} .*$/", $buffer));
		//echo preg_last_error();
		if(stripos($buffer, "DIVISION NO: ") === 0){			
			
			$currRoute = substr($buffer,13,2);
			//$currSalesperson = substr($buffer,15,4);
			

		}elseif(preg_match("/^\d{7} .*$/", $buffer)){
			$currCustomer = substr($buffer, 0,7);
			// echo "<bR>curr cus";
			// echo $currRoute . "-" . $currCustomer;
			// echo "<bR>";
			$custName[$currRoute . "-" . $currCustomer] = substr($buffer, 9,30);
		}elseif(preg_match("/^ \d{2}\/\d{2}\/\d{2} .{3,7}-.*$/", $buffer)){
			$ADDED++;
			$custData[$currRoute . "-" . $currCustomer][] = $buffer;// . $currSalesperson;
		}else{
			// echo "not matched ($index): " . $buffer;
			// echo "<bR>";
		}
        $index++;
		
    }
	echo "Added " . $ADDED;
	echo "<bR>";
	echo count($custData);
}else{
	echo "Cannot open file";
}
//echo "<pre>";
//var_dump($custName);
//echo "</pre>";
$stmt = $con->prepare("INSERT INTO INVOICE_HEAD (
	`InvoiceID`,
	`ShipToName`,
	`ShipToAddress1`, 
	`ShipToAddress2`, 
	`ShipToCity`,
	`ShipToState`, 
	`ShipToZip`, 
	`BillToName`, 
	`Salesman`,
	`AccountNumber`,
	`DueDate`,
	`InvoiceDate`,
	`Subtotal`,
	`Status`,
	Tax1Total,
	Tax2Total,
	Delivered,
	DeliveryDate,
	SalesmanOrder,
	Notes
	) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0, 1, ?,1, ?)");

$productStmt = $con->prepare("INSERT INTO INVOICE_DETAIL (
	`InvoiceID`,
	`Line`,
	`Group`,
	`SKU`, 
	`Description`, 
	`OrderQty`,
	`ShippedQty`,
	`Price`, 
	`AvgCost`, 
	`Taxable1`, 
	`Taxable2`
	) VALUES (?, 'ADM', 'ADM', 'BALFWD', 'BALANCE FORWARD', 1, 1, ?, ?, 0, 0)");	



	
// if(!$stmt){
	
// 	die("error on db: " . mysqli_error($con) );	
// }
	$InvoiceID = "";
	$ShipToName = ""; 
	$ShipToAddress1 = ""; 
	$ShipToAddress2 = ""; 
	$ShipToCity = "";
	$ShipToState = ""; 
	$ShipToZip = ""; 
	$Salesman = ""; 
	$NewAccountNumber = ""; 
	$DueDate = ""; 
	$InvoiceDate = "";
	$Subtotal = "";
	$Notes = "";

	

$stmt->bind_param("isssssssssssdss", 
	$InvoiceID, 
	$ShipToName,
	$ShipToAddress1, 
	$ShipToAddress2, 
	$ShipToCity,
	$ShipToState, 
	$ShipToZip, 
	$ShipToName, 
	$Salesman, 
	$NewAccountNumber, 
	$DueDate,
	$InvoiceDate,
	$Subtotal,
	$InvoiceDate,
	$Notes
);
//var_dump($custName);
$customerStmt = $con->prepare("INSERT INTO CUSTOMER (`Name`, AccountNumber, OldAccountNumber, Salesman, PriceLevel) VALUES (?,?,?,?, 'A')");
$CustAccountNumber = "";
$CustomerName = "";
$customerStmt->bind_param('ssss', $CustomerName, $CustAccountNumber, $AccountNumber, $Salesman);
$productStmt->bind_param("idd", $InvoiceID, $Subtotal, $Subtotal);
$nonNumericInvoiceIndex = 1;
foreach($custData as $AccountNumber => $cust){
	$customer = new Customer($AccountNumber);

	if(!$customer->Name){
		$CustomerName = $custName[$AccountNumber];
		$CustAccountNumber = getNewCustomerNumber();
		$Salesman = explode("-",$AccountNumber)[0];
		$customerStmt->execute();
		if(mysqli_error($con)){
			var_dump(mysqli_error($con));
		}
		
		//var_dump($CustomerName);
		//var_dump($custName);
		$customer = new Customer($AccountNumber);
		//die();


	

	}

	$Salesman = $customer->Salesman->ID;
	if(is_null($Salesman)){
		$Salesman = explode("-",$AccountNumber)[0];
	}
	//var_dump($customer);
	echo "<bR>";
	echo $AccountNumber . " ->  ";
	echo count($cust);
	echo "<bR>";
	foreach($cust as $invoice){

		$fields = [

			[1, 8, "InvoiceDate"],
			[9+1, 7, "InvoiceID"],
			[17+4, 8, "DueDate"],
			[52,10 , "Subtotal"],
			[52+10, 1 , "Signo"]
		];
		foreach($fields as $set){
			$$set[2] = trim(substr($invoice,$set[0], $set[1]));
		}
		
		
		foreach($customer as $index => $custInfo){
			if(is_null($custInfo)){
				$customer->$index = "";
			}
		}
		$NewAccountNumber = $customer->AccountNumber;
		$ShipToName = $customer->Name;
		$ShipToAddress1 = $customer->ShipToAddress1;
		$ShipToAddress2 = $customer->ShipToAddress2;
		$ShipToCity = $customer->ShipToCity;
		$ShipToState = $customer->ShipToState;
		$ShipToZip = $customer->ShipToZip;
		$Notes = "";
		if(is_numeric($InvoiceID)){
			$InvoiceID = intval($InvoiceID);
			
		}else{
			$Notes = "Original Invoice #" . $InvoiceID;
			$InvoiceID = $nonNumericInvoiceIndex;
			$nonNumericInvoiceIndex++;
			
		}
		
		$DueDate = date("y-m-d", strtotime($DueDate));
		$InvoiceDate = date("y-m-d", strtotime($InvoiceDate));
		$Subtotal = floatval(str_ireplace(",","",$Subtotal));
		if($Signo == "-"){
			$Subtotal = $Subtotal*-1;
		}
		
		
		$stmt->execute();
		if(mysqli_error($con)){
			echo "<pre>";
			echo mysqli_error($con);
			echo "</pre>";
		}
		$productStmt->execute();
		if(mysqli_error($con)){
			echo "<pre>";
			echo mysqli_error($con);
			echo "</pre>";
		}
	    // echo $stmt->error();

	}
	
}

// $customer = new Customer("10012");
// $invoices = $customer->getInvoices();
// var_dump($customer);
// $payment = new Payment("1737");
// $payment->SendPaymentEmail();
// $invoice = new Invoic;e("2556");
// $invoice->sendEmail();

//sendEstimate("10812");
//$customer = new Customer("10012");
//$customer->SendCollectionsEmail();

//$customer->transferARToLoss();


function generateUPC(){
	$item = new Item("%", "BUL", "38888");


	$upc = $item->getUPC("1");
	$originalUPC = $upc;

	$upc = substr($upc,0, strlen($upc)-1);
	if(strlen($upc) == 11){
		$upc = "0" . $upc;
	}
	$upc = "2" . $upc;
	$i = 0;
	$sum = 0;
	for($i = strlen($upc)-1; $i >= 0; $i--){
		//echo $upc[$i];
		if($i % 2 == 0){
			$sum += $upc[$i]*3;
		}else{
			$sum += $upc[$i];
		}

	}
	if(round($sum,-1) > $sum){
		$tenth = round($sum,-1);
	}else{
		$tenth = round($sum,-1)+10;
	}
	$check = $tenth-$sum;

	echo "Item:" . $item->SKU . "<br>";
	echo "Original UPC: " . $originalUPC;
	echo "<br>";
	echo "<br>Master Carton Code (ITF-14): " . $upc . $check;


}


//sendEstimate('10254');
//sendOrder("2191");
?>

<?php
/**
 * Author: Abu Ashraf Masnun
 * URL: http://masnun.me
 */
 /*
class WorkerThreads extends Thread
{
    private $workerId;

    public function __construct($id)
    {
        $this->workerId = $id;
    }

    public function run()
    {
        sleep(rand(0, 3));
        echo "Worker {$this->workerId} ran" . PHP_EOL;
    }
}

// Worker pool
$workers = [];

// Initialize and start the threads
foreach (range(0, 5) as $i) {
    $workers[$i] = new WorkerThreads($i);
    $workers[$i]->start();
}

// Let the threads come back
foreach (range(0, 5) as $i) {
    $workers[$i]->join();
}
*/
 //var_dump(sendEstimate(10028));

function getNewCustomerNumber(){
	global $con;
	$query = "SELECT MAX(SUBSTRING(AccountNumber, 1,5))+1 NewAccountNumber FROM `CUSTOMER` WHERE AccountNumber < 90000";
			$result = mysqli_query($con, $query);

			$row = mysqli_fetch_array($result);
			$newCustomerNumber = $row[0];
			return $newCustomerNumber;
}

?>
