// Checked for PHP5.6 / 8.x compatibility
<?php
include("../../operainfo/getq.php");

$locationid=safetext2(isset($_GET['locationid']) ? $_GET['locationid'] : '');
$stkref=safetext2(isset($_GET['stkref']) ? $_GET['stkref'] : '');
$offsetdif=safetext2(isset($_GET['offsetdif']) ? $_GET['offsetdif'] : '');
$outputdif=safetext2(isset($_GET['outputdif']) ? $_GET['outputdif'] : '');

if ($stkref=='')
	{
	$locationid=safetext2(isset($_POST['locationid']) ? $_POST['locationid'] : '');
	$stkref=safetext2(isset($_POST['stkref']) ? $_POST['stkref'] : '');
	$offsetdif=safetext2(isset($_POST['offsetdif']) ? $_POST['offsetdif'] : '');
	$outputdif=safetext2(isset($_POST['outputdif']) ? $_POST['outputdif'] : '');

	}

	
if ($offsetdif=='')
	{
	$sql="SELECT * FROM stocklist_tarriffs WHERE stock_ref = ?";
	$stmt=pdoquery($sql, array($stkref));
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
	foreach ($rows as $row)
		{

		$offsetdif=$row['offsetallowed']+0;
		$outputdif=$row['outputdiff']+0;

		}
	}

	
	$sql="SELECT * FROM stocklist_tarriffs WHERE stock_ref = ?";
	$stmt=pdoquery($sql, array($stkref));
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
	foreach ($rows as $row)
		{

		$multipart=$row['matchpairspn'];

		}

		$sql="SELECT * FROM stocklist_tarriffs WHERE stock_ref = ?";
	$stmt=pdoquery($sql, array($multipart));
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
	foreach ($rows as $row)
		{

		$usedesc=$row['label_description'];

		}
	
	
if ($multipart=='')
	{
	print "ERROR SEE PEN ICON TO SET MULTIPART PART NUMBER!";
	}
	ELSE
	{
	
?>





<?php

$sql="SELECT * FROM serialnumber_questions WHERE stock_ref = ? AND question_type = 'OEMQA'";
$stmt=pdoquery($sql, array($stkref));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row)
	{
	if ($row['question_text']=='OEMOFFSET')
			{
			$offsetid=$row['id'];
			}
	if ($row['question_text']=='OEMOUTPUT')
			{
			$outputid=$row['id'];
			}
	}
	



$sql="SELECT
Serialnumbers.id as barcode ,
serialnumber_answers.questionid as questionid,
serialnumber_answers.answer as answer,
Serialnumbers.Serialnumber as serialnumber,
Serialnumbers.Porref AS Porref
FROM serialnumber_answers,Serialnumbers WHERE

Serialnumbers.stocklocation2 = ? AND
Serialnumbers.Invoicenumber='' AND
Serialnumbers.Ordernumber='' AND
Serialnumbers.id=serialnumber_answers.barcode AND
serialnumber_answers.question_type='OEMQA'
";
$stmt=pdoquery($sql, array($locationid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row)
	{
	$barcode=$row['barcode'];
	$barcodes[$barcode]=1;
	$porrefbarcode[$barcode] = $row['Porref'];
	$questionid=$row['questionid'];
	$link=$barcode."a".$questionid;
	$answers[$link]=$row['answer'];
	$roundanswer[$link]=round($row['answer']/10);
	$serialnum[$barcode]=$row['serialnumber'];

	//print "$barcode | $questionid | $link | $row[answer] <br>";
	}

	
	
// First lets go by Barcode order
ksort($barcodes);
	
	
//print "<table>";
foreach ($barcodes as $barcode  => $answer)
		{
		
		$link1=$barcode."a".$offsetid;
		$link2=$barcode."a".$outputid;
		
		
		if (($answers[$link1]> $answers[$prelink1]-$offsetdif) and ($answers[$link1] < $answers[$prelink1]+$offsetdif) and ($answers[$link2]> $answers[$prelink2]-$outputdif) and ($answers[$link2] < $answers[$prelink2]+$outputdif) and ($matched[$barcode]=='' and $matched[$prebarcode]=='') )
			{
			//print "<tr bgcolor=green>";
			$matched[$barcode]=$prebarcode;
			$matched[$prebarcode]=$barcode;
			} else
			{
			//print "<tr bgcolor=red>";
			}

    	//print "<td>$barcode</td><td> $link1</td><td> $answers[$link1]</td><td> $answers[$link2]</td></tr>";
		
		$prebarcode=$barcode;
		$prelink2=$link2;
		$prelink1=$link1;
		}
		
$barcodeslist=$barcodes;
foreach ($barcodes as $barcode  => $answer)
		{
	
		$matchfound=0;
		$link1=$barcode."a".$offsetid;
		$link2=$barcode."a".$outputid;
		
		//print "$barcode ?<BR>";
		
		
		if ($matched[$barcode]=='')
		{
		
		foreach ($barcodes as $prebarcoded => $secanswer)
				{
				//print "LOOP $prebarcode $secanswer<br>";
				$prelink1=$prebarcoded."a".$offsetid;
				$prelink2=$prebarcoded."a".$outputid;
				if ($matchfound==0 and $prebarcoded<>$barcode and ($answers[$link1]> $answers[$prelink1]-$offsetdif) and ($answers[$link1] < $answers[$prelink1]+$offsetdif) and ($answers[$link2]> $answers[$prelink2]-$outputdif) and ($answers[$link2] < $answers[$prelink2]+$outputdif) and ($matched[$barcode]=='' and $matched[$prebarcoded]=='')  )
					{
					//print "hello $prebarcoded<br>";
					$matched[$barcode]=$prebarcoded;
					$matched[$prebarcoded]=$barcode;
					$matchfound=1;
					}
				
				
				
				}
		} else {
		//print "$barcode done";
		}


		}
		

		
$message="";	

$message .= "<hr> $stkref - End result Matching<hr>";


$message .= "<table>";
$count=0;
foreach ($barcodes as $barcode  => $answer)
		{
		$link1=$barcode."a".$offsetid;
		$link2=$barcode."a".$outputid;
		if ($matched[$barcode]<>'' and $shown[$barcode]=='')
			{
			$message .= "<tr bgcolor=green>";
			$message .= "<td>$count</td><td>$barcode</td><td>$matched[$barcode]</td><td> $answers[$link1]</td><td> $answers[$link2]</td></tr>";	
			
			// need to create a new number based upon todays date
			
			$PORREF="MatchedPair";
			$MANDATECODE="";
			$sql="SELECT * FROM Serialnumbers WHERE id = ?";
			$stmt=pdoquery($sql, array($barcode));
			$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
			foreach ($rows as $row)
				{
			          $STOCKREF = $row['Stock_ref'];
			          $PORREF = $row['Porref'];
			          $poid = preg_replace('/^\D+/', '', $PORREF);
				$MANDATECODE=$row['manufacture_date_code'];
				}

            $lineid = 0;
            $oldqty = 0;
            $sql = "SELECT * FROM viamedquote_purchase_orders_details WHERE orderid = ? AND stockref = ? AND qty_received < qty ORDER BY id DESC";
            $stmt = pdoquery($sql, array($poid, $STOCKREF));
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                $oldqty = $row['qty_received'];
                $lineid = $row['id'];
            }

            if ($lineid > 0) {
                $newqty = $oldqty + 1;
                $sql = "UPDATE viamedquote_purchase_orders_details SET qty_received = ? WHERE id = ?";
                pdoquery($sql, array($newqty, $lineid));
                print "UPDATE viamedquote_purchase_orders_details SET qty_received='$newqty' WHERE id='$lineid'<br>";
            
             $sql = "SELECT * FROM supplier_items WHERE lineid = ? ORDER BY id DESC";
             $stmt = pdoquery($sql, array($lineid));
             $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
             foreach ($rows as $row) {
                 $oldqty2 = $row['Quantity_Received'];
                 $newqty = $oldqty2 + 1;
                 $sql_u = "UPDATE supplier_items SET Quantity_Received = ? WHERE id = ?";
                 pdoquery($sql_u, array($newqty, $lineid));
                 print "UPDATE supplier_items SET Quantity_Received='$newqty' WHERE id='$lineid'<br>";
             }
            
            
            }  


			$tbar=$matched[$barcode];
			// newsn
			$newsn=$serialnum[$barcode]."/".$serialnum[$tbar];
			
			$sql="INSERT INTO Serialnumbers (Stock_ref , Serialnumber , Datebookedin , Bookedinby , Porref , usedescription , stocklocation2  ,manufacture_date_code )
			VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
			pdoquery($sql, array($multipart, $newsn, $nowis, $localname, $PORREF, $usedesc, $locationid, $MANDATECODE));
			$sql="SELECT * FROM Serialnumbers WHERE Serialnumber = ? AND Datebookedin = ?";
			$stmt=pdoquery($sql, array($newsn, $nowis));
			$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
			foreach ($rows as $row)
				{
				$id=$row['id'];
				}
			$sql="UPDATE Serialnumbers SET Invoicenumber = ?, Dateout = ?, Bookedoutby = ?, stocklocation2 = 'Matched Pair' WHERE id = ?";
			pdoquery($sql, array('ID'.$id, $nowis, $localname, $barcode));
			pdoquery($sql, array('ID'.$id, $nowis, $localname, $tbar));
			$sql="INSERT INTO viamed_production_jobs_extraparts (stock_ref,qty,addedby,addedon,mergeid) VALUES (?, '2', ?, ?, ?)";
			pdoquery($sql, array($stkref, $localname, $nowis, $id));
			
			
			
			
			
			$shown[$barcode]=1;
			$obarcode=$matched[$barcode];
			$shown[$obarcode]=1;
			$count++;
			
			
			} else
			{
			//print "<tr bgcolor=red>";
			}
		
			
			
		}
	print "Matched Pairs Created";
	}
?>
