<?php
include("presets.php");

# from the list of manufacturer
if(array_key_exists("manufacturer", $_GET))
	$manu = $_GET["manufacturer"];
# store form
if(array_key_exists("manufacturer", $_POST))
	$manu = $_POST["manufacturer"];
if(!isset($manu) || !is_numeric($manu))
	$manu = 0;
if(array_key_exists("manufacturersid", $_GET))
	$manufacturersid = $_GET["manufacturersid"];
if(!isset($manufacturersid) || !is_numeric($manufacturersid))
	$manufacturersid = 0;

include("helpers.php");

if($loggedIn == 0){
	header("Location: admin.php");
	die();
}

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<link rel="stylesheet" type="text/css" href="engsas.css" />
		<link rel="stylesheet" type="text/css" href="ajaxtabs/ajaxtabs.css" />
		<script type="text/javascript" src="ajaxtabs/ajaxtabs.js">
			/***********************************************
			* Ajax Tabs Content script v2.2- C Dynamic Drive DHTML code library (www.dynamicdrive.com)
			* This notice MUST stay intact for legal use
			* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
			***********************************************/
		</script>
	</head>
	<body class="iframecontent">
<?php

$connId = @ mysql_connect("localhost", Settings::value("ADMINUSER"), Settings::value("ADMINPASSWORD"));
if(!$connId){
	echo "<div class=\"log\">\n";
	echo "<div class=\"logLine\">Please specify the database admin user at <a href=\"admin.php\">Admin</a></div>\n";
	echo "</div>\n";
	die("</body></html>");
}
if(!mysql_select_db(Settings::value("DBNAME"))){
	echo "<div class=\"log\">\n";
	echo "<div class=\"logLine\">Could not select the specified database ". Settings::value("DBNAME") .".</div>\n";
	echo "</div>\n";
	mysql_close($connId);
	die("</body></html>");
}

if($manu > 0){
	if($_GET["action"] == "delete"){
		# the queued manufacturer should be deleted.
		# therefore delete also all mins which references this manufacturer
		# and not needed min types
		# start transaction
		if(!mysql_query("BEGIN")){
			mysql_close($connId);
			echo "Could not delete manufacturer (Could not start transaction).<br>\n";
			echo "</body>\n";
			echo "</html>";
			mysql_close($connId);
			exit;
		}
		if(!mysql_query("DELETE FROM manufacturerhasmins_queue WHERE manufacturersId=". $manu)){
			echo "Could not delete manufacturer (Could delete all related queued MINs).<br>\n";
			echo "</body>\n";
			echo "</html>";
			mysql_query("ROLLBACK");
			mysql_close($connId);
			exit;
		}
		# remove not needed mintypes
		if(!mysql_query("DELETE FROM mintypes_queue WHERE id NOT IN (SELECT mintypesId FROM manufacturerhasmins_queue)")){
			echo "Could not delete manufacturer (Could not remove queued MIN-Types).<br>\n";
			echo "</body>\n";
			echo "</html>";
			mysql_query("ROLLBACK");
			mysql_close($connId);
			exit;
		}
		if(!mysql_query("DELETE FROM manufacturers_queue WHERE id=". $manu)){
			echo "Could not delete manufacturer (Could delete manufacturer).<br>\n";
			echo "</body>\n";
			echo "</html>";
			mysql_query("ROLLBACK");
			mysql_close($connId);
			exit;
		}
		mysql_query("COMMIT");
		echo "<script type=\"text/javascript\">\n";
		echo "alert(\"Deleted selected manufacturer\");";
		echo "window.top.location.replace(\"". $_SERVER["$PHP_SELF"] ."?lang=". $lang ."\");";
		echo "</script>\n";
		echo "</body>\n";
		echo "</html>";
		mysql_close($connId);
		exit;
	}
	if($manufacturersid > 0){
		# $manu is the same manufacturer as the already stored one at $manufacturersid
		if(!mysql_query("UPDATE manufacturers_queue SET manufacturersId=". $manufacturersid ." WHERE id=". $manu))
			echo "Could not associate the selected manufacturers.<br>\n";
		else{
			echo "<script type=\"text/javascript\">\n";
			echo "alert(\"Associated selected manufacturers.\");";
			echo "window.top.location.reload();";
			echo "</script>\n";
		}
		echo "</body>\n";
		echo "</html>";
		mysql_close($connId);
		exit;
	}
	if(array_key_exists("storemanu", $_POST)){
		# store the manufacturer
		$query = sprintf(
			"INSERT INTO manufacturers
			(name, street, number, city, postalCode, postOfficeBox, country, website, email, phone, fax)
			VALUES('%s', '%s', '%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s')",
			mysql_real_escape_string(stripText($_POST["manuname"])),
			mysql_real_escape_string(stripText($_POST["manustreet"])),
			mysql_real_escape_string(stripText($_POST["manunumber"])),
			mysql_real_escape_string(stripText($_POST["manucity"])),
			mysql_real_escape_string($_POST["manuzip"]),
			mysql_real_escape_string($_POST["manupostofficebox"]),
			mysql_real_escape_string(stripText($_POST["manucountry"])),
			mysql_real_escape_string(Manufacturer::prepareWebsite(stripText($_POST["manuwebsite"]))),
			mysql_real_escape_string(stripText($_POST["manuemail"])),
			mysql_real_escape_string(stripText($_POST["manuphone"])),
			mysql_real_escape_string(stripText($_POST["manufax"]))
		);
		if(!mysql_query($query)){
			echo "Could not store manufacturer (Could not insert)";
			mysql_close($connId);
			echo "</body>\n";
			echo "</html>";
			exit;
		}

		# get id of new manufacturer
		$name = mysql_real_escape_string($_POST["manuname"]);
		$result = mysql_query("SELECT id FROM manufacturers WHERE name='". $name ."'");
		if(!$result){
			echo "Could not store manufacturer (Could not fetch new id)";
			mysql_close($connId);
			echo "</body>\n";
			echo "</html>";
			exit;
		}

		$id = 0;
		$result = mysql_fetch_object($result);
		if($result){
			if($result->id > 0)
				$id = $result->id;
		}
		if($id < 1){
			echo "Could not store manufacturer (New id < 1)";
			mysql_close($connId);
			echo "</body>\n";
			echo "</html>";
			exit;
		}

		# insert soundexes
		$manufacturer = new Manufacturer($name);
		$manufacturer->setId($id);
		if(!insertSoundexes($manufacturer, true)){
			echo "Could not store the selected manufacturer (Could not insert soundexes).<br>\n";
			echo "</body>\n";
			echo "</html>";
			mysql_close($connId);
			exit;
		}

		# set the new id as manufacturersId at the manufacturer_queue
		# $manu is the same as $manufacturersid
		if(!mysql_query("UPDATE manufacturers_queue SET manufacturersId=". $id ." WHERE id=". $manu)){
			echo "Could not store the selected manufacturer.<br>\n";
		}
		else{
			echo "<script type=\"text/javascript\">\n";
			echo "alert(\"Stored selected manufacturer.\");";
			echo "window.top.location.reload();";
			echo "</script>\n";
		}
		echo "</body>\n";
		echo "</html>";
		mysql_close($connId);
		exit;
	}

	$res = mysql_query("SELECT * FROM manufacturers_queue WHERE id=". $manu);
	if(!$res){
		
		die("</body></html>");
	}

	$manu = mysql_fetch_object($res);

	$manus = matchManufacturer($manu->name);
	$maxManus = 10;
	if($manus){
		if(count($manus) > 0){
			echo "Found "; 
			if(count($manus) > $maxManus)
				echo $maxManus ." of ". count($manus);
			else
				echo count($maxManus);
			echo " possible Manufacturers:\n";
			echo "<table>\n";
			
			$i = 0;
			foreach(array_keys($manus) as $score){
				foreach(array_keys($manus[$score]) as $key){
					if($i == $maxManus)
						break 2;
					echo "	<tr>\n";
					echo "		<td>\n";
					echo "			". $manus[$score][$key];
					echo "			". $score ."% (<a href=\"". $_SERVER["PHP_SELF"] ."?lang=". $lang ."&manufacturer=". $manu->id ."&manufacturersid=". $key ."\">";
					echo "Use";
					echo "</a>)\n";
					echo "		</td>\n";
					echo "	</tr>\n";
					$i++;
				}
			}
			echo "</table>\n";
		}
	}

	echo "<form action=\"". $_SERVER['PHP_SELF'] ."\" method=\"post\">\n";
	echo "	<input type=\"hidden\" name=\"manufacturer\" value=\"". $manu->id ."\">\n";
	echo "	<table>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Name") .":</td>\n";
	echo "			<td><input type=\"text\" name=\"manuname\" maxlength=\"120\" value=\"". $manu->name ."\" autofocus required></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Address") .":</td>\n";
	echo "			<td>\n";
	echo "				<input type=\"text\" name=\"manustreet\" maxlength=\"50\" value=\"". $manu->street ."\">\n";
	echo "				<input type=\"text\" name=\"manunumber\" maxlength=\"50\" value=\"". $manu->number ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("City") .":</td>\n";
	echo "			<td><input type=\"text\" name=\"manucity\" maxlength=\"50\" value=\"". $manu->city ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("ZIP") .":</td>\n";
	echo "			<td><input type=\"number\" name=\"manuzip\" min=\"0\" value=\"". $manu->postalCode ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Post Office Box") .":</td>\n";
	echo "			<td><input type=\"number\" name=\"manupostofficebox\" min=\"0\" value=\"". $manu->postOfficeBox ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Country") .":</td>\n";
	echo "			<td><input type=\"text\" name=\"manucountry\" maxlength=\"50\" value=\"". $manu->country ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Website") .":</td>\n";
	echo "			<td><input type=\"url\" name=\"manuwebsite\" maxlength=\"120\" value=\"". $manu->website ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("E-Mail") .":</td>\n";
	echo "			<td><input type=\"email\" name=\"manuemail\" maxlength=\"120\" value=\"". $manu->email ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Phone") .":</td>\n";
	echo "			<td><input type=\"text\" name=\"manuphone\" maxlength=\"50\" value=\"". $manu->phone ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td>". _("Fax") .":</td>\n";
	echo "			<td><input type=\"text\" name=\"manufax\" maxlength=\"50\" value=\"". $manu->fax ."\"></td>\n";
	echo "		</tr>\n";
	echo "		<tr>\n";
	echo "			<td><input type=\"submit\" name=\"storemanu\" value=\"". _("Store") ."\"></td>\n";
	echo "			<td></td>\n";
	echo "		</tr>\n";
	echo "	</table>\n";
	echo "</form>\n";

	echo "</body>\n";
	echo "</html>";
	mysql_close($connId);
	exit;
}
?>
<ul id="manufacturerslinks">
	<?php
	$res = mysql_query("SELECT * FROM manufacturers_queue WHERE manufacturersId IS NULL");
	while ($manu = mysql_fetch_object($res)) {
		echo "<li>\n";
		echo "	<a href=\"". $_SERVER['PHP_SELF'] ."?lang=". $lang ."&manufacturer=". $manu->id ."\" rel=\"#iframe\" class=\"selected\">". $manu->name ."</a>\n";
		echo "	 (<a href=\"". $_SERVER["PHP_SELF"] ."?lang=". $lang ."&manufacturer=". $manu->id ."&action=delete\" rel=\"#iframe\">Delete</a>)\n";
		echo "</li>\n";
	}
	?>
</ul>

<div id="manufacturerscontainer">
</div>
<script type="text/javascript">
	var manus=new ddajaxtabs("manufacturerslinks", "manufacturerscontainer")
	manus.setpersist(true)
	manus.setselectedClassTarget("link") //"link" or "linkparent"
	manus.init()
</script>

<?php
mysql_close($connId);
?>
	</body>
</html>