<?php
require_once("../config/connect.php");
require_once("../config/sIT_global_db_functions.php");

function get_ids($table, $id)
{
	global $con_i;
	mysql_select_db(SQL_DB);
	$datum = "";
	if ( $table == "dep" )
		$datum = "datum_zeit";
	else if ( $table == "abgeschlossener_bon" )
		$datum = "bon_erstellt_datum";
		
	$sql="SELECT $id+1 as id, ".$datum." as datum FROM $table WHERE $id NOT IN (SELECT $id-1 FROM $table) AND $id<>(SELECT max($id) FROM $table)";

	echo "<b>Tabelle: ".$table."<b>";
	echo "<br><p>";
	$Q1=sIT_mysql_run_query($con_i, $sql, true);
	if (! $Q1)
	{
		echo "Fehler :".mysql_error();
	}
	else
	{
		while ($row=sIT_mysql_get_row($Q1))
			echo "Fehlende ID: " . $row['id']. " | Datum: ".$row['datum']."<br>";
	}
	echo "<p><br>";
	
}

function check_fehlende_id_for_table($table, $id)
{
	global $con_i;
	mysql_select_db(SQL_DB);
	//$sql = "SELECT beleg_nr+1 as id FROM dep WHERE beleg_nr NOT IN (SELECT beleg_nr-1 FROM dep) AND beleg_nr<>(SELECT max(beleg_nr) FROM dep)";
	$sql="SELECT $id+1 as id FROM $table WHERE $id NOT IN (SELECT $id-1 FROM $table) AND $id<>(SELECT max($id) FROM $table)";

	
	$Q1=sIT_mysql_run_query($con_i, $sql, true);
	if (! $Q1)
	{
		echo "Fehler :".mysql_error();
	}
	else
	{
		while ($row=sIT_mysql_get_row($Q1))
		{
			$sqlinsert = "";
			
			if ( $table == "dep" )
				$sqlinsert = "INSERT INTO dep SET beleg_nr = ".$row['id'] ;
			else if ( $table == "abgeschlossener_bon" )
			{
				$sqlinsert = "INSERT INTO abgeschlossener_bon SET bon_id = ".$row['id'] ;
				echo $sqlinsert."<br>";
				sIT_mysql_run_query($con_i, $sqlinsert, true);
				$sqlinsert = "INSERT INTO abgeschlossener_bon_produkte SET printname='geloescht durch Software-Fehler' ,bon_id = ".$row['id'];
			}
		
			echo $sqlinsert."<br>";
			sIT_mysql_run_query($con_i, $sqlinsert, true);
		}
	}
	echo "<br>";
}	
	

	
?>

<html>
<head></head>
<body>
<?php
		if(isset($_POST['insertdep'])) {
           check_fehlende_id_for_table("dep", "beleg_nr" );
        }
        if(isset($_POST['insertbon'])) {
            check_fehlende_id_for_table("abgeschlossener_bon", "bon_id");
        }
	
	
		get_ids("dep", "beleg_nr" );
		get_ids("abgeschlossener_bon", "bon_id");
	
?>
	
	<form method="post">
        <input type="submit" name="insertdep" value="DEP befüllen" />
        <input type="submit" name="insertbon" value="Abgeschlossene Bon befüllen" />
    </form>
	
</body>
</html>