<?php
	session_start();
	if (($_SESSION['logged_in']) != 10)
		header("Location: index.php");
		
	$view_id = $_SESSION['view_id'];
?>
<HTML>
<HEAD>
<TITLE>Little Blossoms Arts Inventory Manager</TITLE>
<STYLE>
TH
{
    TEXT-ALIGN: right
}
.row0
{
    BACKGROUND-COLOR: #d5d5d5
}
.row1
{
    BACKGROUND-COLOR: #e5e5e5
}   
</STYLE>
<SCRIPT LANGUAGE="JavaScript1.1"><!--
function clearform()
{
    for (var i = 0; i<document.Inventory.elements.length; i++)
    {
	var type = document.Inventory.elements[i].type;
        if (type == 'select-one')
        {
            document.Inventory.elements[i].selectedIndex = 0;
        }
        else if (type == 'text' || type == 'textarea')
        {
	    document.Inventory.elements[i].value = '';
        }
    }
}

function chkForm() {
	var frm = document.forms["Inventory"];
	if (frm.products_model.value == "")
	{
		alert("Please fill in the model number.");
		frm.products_model.focus();
		bOKtoSend = false;
		return;
	}
	else if (frm.manufacturers_id.value == "")
	{
		alert("Please select an artist.");
		frm.manufacturers_id.focus();
		bOKtoSend = false;
		return;
	}
	else if (frm.master_categories_id.value == "")
	{
		alert("Please select a category.");
		frm.master_categories_id.focus();
		bOKtoSend = false;
		return;
	}
	bOKtoSend = true;
}

function sendMe() {
	return bOKtoSend;
}

function parseDescription()
{
	description = document.Inventory.products_description.value;
	description_array = description.split('\n');
	item_name = description_array[0];
	size = description_array[1];
	item_num = description_array[2];
	tmp = item_num.split('#');
	item_num = tmp[1];
	item_num = item_num.substring(1)
//	artist = description_array[4];
	document.Inventory.products_name.value = item_name;
	document.Inventory.size.value = size;
	document.Inventory.products_model.value = item_num;
}
//--></SCRIPT>
</HEAD>

<?
ini_set('max_execution_time', 2000);

include ("image_processing.php");
include ("../connect/db_connection_2.php");

///////////////////////////////////////////////////////////////////////////////////////
function read_columns($view_id, $link)
{
    global $columns, $column_types;

    $sql = "SELECT * FROM view_fields WHERE view_id = $view_id ORDER BY vf_Order, vf_id";
    if (!($ret = mysql_query($sql, $link)))
        return;

    while ($row = mysql_fetch_assoc($ret))
    {
	$columns[$row["vf_ColumnName"]] = $row["vf_DisplayName"];
	if ($row["vf_FieldType"] != null)
	    $column_types[$row["vf_ColumnName"]] = $row["vf_FieldType"];

	if ($row["vf_DataQuery"] != null)
	    $queries[$row["vf_ColumnName"]] = $row["vf_DataQuery"];
    }

    if (is_array($queries))
        foreach ($queries as $field => $query)
	    read_field_values($field, $query);
}

///////////////////////////////////////////////////////////////////////////////////////
function read_field_values($field, $query)
{
    global $enums, $column_types;

    $sql = $query;
    if (!($ret = mysql_query($sql)))
        return;

    if ($column_types[$field] == 'select' || $column_types[$field] == 'multiselect')
    {
        while ($row = mysql_fetch_assoc($ret))
        {
	    if (!is_array($enums[$field]))
		$enums[$field] = array();
	    array_push($enums[$field], $row["Value"]);
        }
    }
    else
    {
	$row = mysql_fetch_assoc($ret);
	$enums[$field] = $row["Value"];
    }
}

//////////////////////////////////////////////////////////////////////////////////////
function read_enums($link)
{
    global $enums;
	
	//Add enumerations from manufacturers table.
	$sql = "SELECT * FROM `zen_manufacturers` ORDER BY `manufacturers_id`";
    if (!($ret = mysql_query($sql, $link)))
        return;
		
	while ($row = mysql_fetch_assoc($ret))
    {
	if (!is_array($enums["manufacturers_id"]))
	    $enums["manufacturers_id"] = array();
	array_push($enums["manufacturers_id"], $row["manufacturers_id"], $row["manufacturers_name"]);
    }
	
	//Add enumerations from categories table.
	$sql = "SELECT * FROM `zen_categories_description` ORDER BY `categories_id`";
    if (!($ret = mysql_query($sql, $link)))
        return;
		
	while ($row = mysql_fetch_assoc($ret))
    {
	if (!is_array($enums["master_categories_id"]))
	    $enums["master_categories_id"] = array();
	array_push($enums["master_categories_id"], $row["categories_id"], $row["categories_name"]);
    }
}  
    
/////////////////////////////////////////////////////////////////////////////////////
function input_html($column_types, $column, $value, $attribs)
{
    global $enums;

    $datatype = $column_types[$column];

	if (is_array($values = $enums[$column]))
    {
		if ($datatype == 'multiselect')
			$attribs += ' MULTIPLE SIZE="5"';

	$html = "<SELECT name='$column' $attribs><OPTION value=''>(None)";

	$value_count = count($values);
	for ($i = 0; $i < ($value_count - 1); $i++)
	{
		$option_val = $values[$i];
		$i++;
		$member = $values[$i];
		
		$html .= "<OPTION";
		if ($value == $option_val)
			$html .= " SELECTED";
	
		$html .= " VALUE=$option_val>" . htmlentities($member);
	}

	$html .= "</SELECT>";
    }
    elseif ($datatype == "text")
    {
		$html = "<TEXTAREA name='$column' $attribs>" . htmlentities($value) . "</TEXTAREA>";
    }
	elseif ($datatype == "checkbox")
    {
		if (htmlentities($value) == 1)
			$html = "<input name='$column' type='checkbox' value='1' checked='checked' />";
		else
			$html = "<input name='$column' type='checkbox' value='1' />";
    }
    else
    {
	if (preg_match('/char\(([0-9]+)/', $datatype, $matches))
	    $length = $matches[1];

	$html = "<INPUT name='$column' $attribs";
	if ($length)
	    $html .= " maxlength=$length size=$length";
	$html .= ' value="' . htmlspecialchars($value) . '">';
    }
    
    return $html;
}

////////////////////////////////////////////////////////////////////////////
function get_column_info($table)
{
    global $column_types;

    $sql = "SHOW COLUMNS FROM $table";
    if (!($ret = mysql_query($sql)))
        die("Error: Could not show columns");

    while ($row = mysql_fetch_assoc($ret))
	$array[$row["Field"]] = $row["Type"];

    # now add in known column types
    if (is_array($column_types))
        foreach ($column_types as $field => $type)
	    $array[$field] = $type;

    return $array;
}

/////////////////////////////////////////////////////////////////////////////
function create_images($srcfile, $destfile_fs, $destfile_tn, $destdir)
{
	$crop_area = $_POST['crop_area'];
	$crop_percent = $_POST['crop_percent'];
	
    @mkdir($destdir);
    @mkdir("$destdir/fs");
    @chmod("$destdir/fs", 0755);

    // if the source is the fullsize one, don't mess with it
    if ($srcfile != "$destdir/fs/$destfile_fs")
	{
		if (!resize_image($srcfile, 600, 600, "$destdir/fs/$destfile_fs"))
			return 0;
		// Move image to Zen cart location for viewing in cart.
		$zendir = getenv('DOCUMENT_ROOT') . "/shoppingcart/images";
		copy ("$destdir/fs/$destfile_fs", "$zendir/$destfile_fs");
	}

    @mkdir("$destdir/tn");
    @chmod("$destdir/tn", 0755);
	crop_image($srcfile, $crop_percent, "$destdir/tn/$destfile_tn", $crop_area);
    resize_image("$destdir/tn/$destfile_tn", 75, 75, "$destdir/tn/$destfile_tn");

    return 1;
}

///////////////////////////////////////////////////////////////////////////////
function re_crop_image($link)
{
	$crop_area = $_POST['crop_area'];
	$crop_percent = $_POST['crop_percent'];
	
	$image_folder = get_image_folder($_POST["products_id"], $link);
	$destdir = getenv('DOCUMENT_ROOT') . "/inventory_images/" . $image_folder;

	$destfile_tn = $_POST['thumbnail_image'];
	$srcfile = $destdir . "/fs/" . $_POST['products_image'];

	crop_image($srcfile, $crop_percent, "$destdir/tn/$destfile_tn", $crop_area);
    resize_image("$destdir/tn/$destfile_tn", 75, 75, "$destdir/tn/$destfile_tn");

    return 1;
}

//////////////////////////////////////////////////////////////////////////////
function create_column_list($array)
{
    // assume $array already has addslashes run on it
    global $columns;
    
    foreach ($columns as $column => $desc)
	if ($array[$column] != "")
	    $list[$column] = "`$column` = '" . $array[$column] . "'";
	
    return $list;	
}

/////////////////////////////////////////////////////////////////////////////
function write_table($array, $link)
{
    // assume $array already has addslashes run on it
    global $columns, $view_id, $enums;

    $table_info = get_column_info('zen_products');
        
    echo <<<END
<FORM method=post action="manage_inventory.php" name="Inventory" enctype="multipart/form-data" onSubmit="return sendMe()">
<TABLE>
<TR>
<TD valign='top'>
<TABLE cellspacing=0>
END;

    foreach ($columns as $column => $desc)
    {
	if (isset($enums[$column]) && !is_array($enums[$column]) && !isset($array[$column]))
	    $val = $enums[$column];
	else
	    $val = stripslashes($array[$column]);

	if ($column == 'products_last_modified')
	    $tag = $val . input_html($table_info, $column, $val, "type=hidden");
	elseif ($column == 'thumbnail_image')
	{
	    $tag = input_html($table_info, $column, $val, "type=hidden");
	    if ($val != "")
	    {
		$img = $val;
		if (!preg_match("/.jpg/i", $val))
		    $img .= ".jpg";

		$folder = get_image_folder($array["products_id"], $link);
		
		$tag .= "$val" . '<br><IMG src="/inventory_images/'
		    . $folder . "/tn/" . htmlspecialchars($img) . '">';
			
		$tag .= "&nbsp; <INPUT type=submit name='Re_Crop' value='Re-crop Thumbnail'>";
	    }
	}
	elseif ($column == 'products_image')
	{
	    $tag = input_html($table_info, $column, $val, "type=hidden");
	    $tag .= "<input type=file name=IMAGE>\n";
		//Thumbnail cropping control
		$tag .= " Thumbnail crop area:\n
		<SELECT name='crop_area'>\n
		<OPTION value='center'>Center</OPTION>\n
		<OPTION value='top'>Top</OPTION>\n
		<OPTION value='bottom'>Bottom</OPTION>\n
		<OPTION value='left'>Left</OPTION>\n
		<OPTION value='right'>Right</OPTION>\n
		</SELECT>\n
		Crop %:\n
		<INPUT type='text' name='crop_percent' value='5' size='4' maxlength='3'>\n\n";
	    
	    if ($val != "")
	    {
			$img = $val;
			if (!preg_match("/.jpg/i", $val))
				$img .= ".jpg";
	
			$folder = get_image_folder($array["products_id"], $link);
			
			$tag .= "<br>$val" . '<br><IMG src="/inventory_images/'
				. $folder . "/fs/" . htmlspecialchars($img) . '">';	
	    }
	}
	elseif ($column == 'products_status')
	{
		 $tag = input_html($table_info, $column, $val, "");
	}
	else
	{
	    if ($column == 'products_description')
			$attribs = "rows=10 cols=60";
	    elseif ($table_info[$column] == 'hidden')
			$attribs = "type=hidden";
	    else	
			$attribs = "";
			
	    $tag = input_html($table_info, $column, $val, $attribs);
//		if (($column == 'products_description') && ($_POST["Clear"]))
//			$tag .= "&nbsp; <INPUT type=button name='Parse Description' value='Parse description from old site' onClick='parseDescription();'>";
	}

	if ($table_info[$column] == 'hidden')
	    $hidden .= $tag;
	else
	    echo "<TR class='row" . ($row++ % 2) . "'><TH>$desc</TH><TD>$tag</TD></TR>\n";
    }
    
    echo <<<END
</TABLE>
$hidden
</TD>


<TD valign="top">

<INPUT type=submit name="Search" value="Search for Item">
<br>
<INPUT type=submit name="Update" value="Update Item" onClick="return chkForm()">
END;

//	$products_id = $_POST['products_id'];
    if ($array["products_id"])
	{
		$products_id = $array["products_id"];
		echo <<<END
	
<br>
<TABLE>
<TR><TD>
<INPUT type=submit name='First' value='&lt;&lt;'>
</TD>
<TD>
<INPUT type=submit name="Previous" value="&lt;">
</TD><TD>&nbsp;</TD><TD>
<INPUT type=submit name="Next" value="&gt;">
</TD>
<TD>
<INPUT type=submit name='Last' value='&gt;&gt;'>
</TD>
</TR>
</TABLE>


<br>
<br>
END;
	}
	else
		$products_id = $_POST['products_id'];

//	$products_id = $_POST['products_id'];
    if ($products_id)
	echo <<<END
<INPUT type=button name="Delete" value="Delete Item" onClick="location='delete_item_confirm.php?products_id=$products_id'">
END;

    echo <<<END
<br>
<br>
<INPUT type=reset value="Cancel Changes">
<br>
<INPUT type=submit name="Clear" value="Clear Form">
<br><br>
<em><input name="Artist" type="button" id="Artist" value="Go to Artist Manager" onClick="location='artist.php'"></em>
<br>
<em><input name="Category" type="button" id="Category" value="Go to Category Manager" onClick="location='category.php'"></em>
<br>
<em><input name="Users" type="button" id="Users" value="Go to User Manager" onClick="location='users.php'"></em>
END;

if ($array["products_id"])
{
	echo <<<END
<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
<TABLE>
<TR><TD>
END;

//if ($search > 2)
	echo "<INPUT type=submit name='First' value='&lt;&lt;'>\n</TD>\n<TD>\n";

echo <<<END
<INPUT type=submit name="Previous" value="&lt;">
</TD><TD>&nbsp;</TD><TD>
<INPUT type=submit name="Next" value="&gt;">
</TD>
END;

//if ($search > 2)
	echo "<TD>\n<INPUT type=submit name='Last' value='&gt;&gt;'>\n</TD>\n";

echo <<<END
</TR>
</TABLE>
END;
}


echo <<<END
</TD>
</TR>

</TABLE>
</FORM>
END;
}

///////////////////////////////////////////////////////////////
function do_search($view_id, $link)
{
    $ret = mysql_query("SELECT view_Criteria FROM view_names WHERE view_id = $view_id");
    $row = mysql_fetch_assoc($ret);
    if ($row["view_Criteria"] != null)
	$criteria = "AND " . $row["view_Criteria"];

    $cols = create_column_list($_POST);
    if (!$cols)
	$cols = create_column_list($_GET);

    if ($_POST["Search"] || $_GET["Search"])
    {
	if ($cols)
	    $where = join($cols, " AND ");
	if ($where)
	    $where = "WHERE $where $criteria";
	else
	    $where = "WHERE 1=1 $criteria";

	$ret = mysql_query("SELECT COUNT(*) FROM zen_products $where");
	$row = mysql_fetch_array($ret);
	$count = $row[0];

	if ($count != 1)
	    echo "Your search found $count items.";
	if (!$count)
	    return 0;

	$sql = "SELECT * FROM zen_products $where ORDER BY products_id LIMIT 0, 1";
    }
    elseif ($_POST["Next"])
	$sql = "SELECT * FROM zen_products WHERE products_id > " . $_POST["products_id"] . " $criteria ORDER BY products_id LIMIT 0, 1";	   
    elseif ($_POST["Previous"])
	$sql = "SELECT * FROM zen_products WHERE products_id < " . $_POST["products_id"] . " $criteria ORDER BY products_id DESC LIMIT 0, 1";
	elseif (($_POST["First"]) && $criteria)
	$sql = "SELECT * FROM zen_products WHERE $criteria ORDER BY products_id LIMIT 0, 1";
	elseif (($_POST["First"]) && !$criteria)
	$sql = "SELECT * FROM zen_products ORDER BY products_id LIMIT 0, 1";
	elseif (($_POST["Last"]) && $criteria)
	$sql = "SELECT * FROM zen_products WHERE $criteria ORDER BY products_id DESC LIMIT 0, 1";
	elseif (($_POST["Last"]) && !$criteria)
	$sql = "SELECT * FROM zen_products ORDER BY products_id DESC LIMIT 0, 1";

    if ($sql)
    {
	if (!($ret = mysql_query($sql)))
	    die("Error: Could not query '$sql'");
	while ($row = mysql_fetch_array($ret))
	{
	    write_table($row, $link);
	    $count++;
	}    
    
	if (!$count)
	    echo "Sorry, no items were found.";
    }

    return $count;
}

///////////////////////////////////////////////////////////////
function do_update($link)
{
    if ($_POST["Update"] || $_POST["Next"] || $_POST["Previous"])
    {
	global $columns, $view_id;
	

	$cols = create_column_list($_POST);
	if (count($cols) < 1)
	    return 0;

	if (is_uploaded_file($_FILES['IMAGE']['tmp_name']))
	{
		$image_folder = get_image_folder($_POST["products_id"], $link);
		$dir = getenv('DOCUMENT_ROOT') . "/inventory_images/" . $image_folder;

		$filename = str_replace("/", "", $_FILES['IMAGE']['name']);
		$filename = substr($filename, 0, strpos($filename, "."));
		$filename = $filename . time();
		$filename_fs = $filename . ".jpg";
		$filename_tn = $filename . "_tn.jpg";
		

	    if (!create_images($_FILES['IMAGE']['tmp_name'], $filename_fs, $filename_tn, $dir))
	    {
		echo "Invalid file upload!";
		return 0;
	    }

		$cols['products_image'] = "`products_image` = '" . addslashes($filename_fs) . "'";
		$cols['thumbnail_image'] = "`thumbnail_image` = '" . addslashes($filename_tn) . "'";
		
		// Next 2 lines are to get images to display after insert.
		$_POST['products_image'] = $filename_fs;
		$_POST['thumbnail_image'] = $filename_tn;

	    $update++;
	}

	if ($_POST["products_id"])
	{
	    // we have to make sure that we don't update the modification date if there is no change
	    $sql = "SELECT * FROM zen_products WHERE products_id = " . $_POST["products_id"];
	    $ret = mysql_query($sql);
	    $curdb = mysql_fetch_array($ret);

	    foreach ($columns as $colname => $desc)
	        if (addslashes($curdb[$colname]) != $_POST[$colname])
		    $update++;


	    if (!$update)
	        return 0;

	    $verb = "REPLACE";
	}
	else
	{
	    $verb = "INSERT";
	}


	$cols['products_last_modified'] = '`products_last_modified` = NOW()';
	if ($verb == "INSERT")
	{
		// Set status = 1 so it will display in Zen cart.
//		$cols['products_status'] = '`products_status` = 1';
		$cols['products_quantity'] = '`products_quantity` = 1000000';
		$cols['products_tax_class_id'] = '`products_tax_class_id` = 1';
	}
	$sql = $verb . " INTO zen_products SET " . join($cols, ", ");

	if (!($ret = mysql_query($sql)))
	{
	    echo "Sorry, but there is an error in your data.<BR>" . mysql_error();
		if (mysql_error() == "Unknown column 'products_name' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `products_name` varchar(64) NULL";
			$result_alt = mysql_query($sql_alter);
		}
		elseif (mysql_error() == "Unknown column 'thumbnail_image' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `thumbnail_image` varchar(255) NULL";
			$result_alt = mysql_query($sql_alter);
		}
		elseif (mysql_error() == "Unknown column 'search_term' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `search_term` varchar(255) NULL";
			$result_alt = mysql_query($sql_alter);
		}
		elseif (mysql_error() == "Unknown column 'products_description' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `products_description` TEXT NULL";
			$result_alt = mysql_query($sql_alter);
		}
		elseif (mysql_error() == "Unknown column 'width' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `width` double NULL";
			$result_alt = mysql_query($sql_alter);
		}
		elseif (mysql_error() == "Unknown column 'height' in 'field list'")
		{
			$sql_alter = "ALTER TABLE `zen_products` ADD `height` double NULL";
			$result_alt = mysql_query($sql_alter);
		}
	}
	else
	{
	    if ($verb == "INSERT")
		{
			$products_id = mysql_insert_id();
			echo "Created Item #" . $products_id;
			copy_to_products_desc_table_etc($products_id, $verb, $link);
		}
		else
		{
			echo "Updated Item #" . $_POST['products_id'];
			copy_to_products_desc_table_etc($_POST['products_id'], $verb, $link);
		}
			
//	    if ($_POST["Update"])
//			write_table(array('MODIFIER' => $_POST["MODIFIER"]));
	}
    }	    
    return $ret;	
}

///////////////////////////////////////////////////////////////
function get_image_folder($products_id, $link)
{
	if ($products_id)
	{
		$query = "SELECT * FROM `zen_products` WHERE `products_id` = $products_id";
		$result = mysql_query($query, $link);
		$num_results = mysql_num_rows($result);
		$row = mysql_fetch_array($result);
		$manufacturers_id = $row["manufacturers_id"];
		$master_categories_id = $row["master_categories_id"];
	}
	else
	{
		$manufacturers_id = stripslashes($_POST["manufacturers_id"]);
		$master_categories_id = stripslashes($_POST["master_categories_id"]);
	}
	
	$query = "SELECT * FROM `zen_manufacturers` WHERE `manufacturers_id` = $manufacturers_id";
	$result = mysql_query($query, $link);
	$num_results = mysql_num_rows($result);
	$row = mysql_fetch_array($result);
	$artist_folder = $row["image_folder"];
	
	$query = "SELECT * FROM `zen_categories_description` WHERE `categories_id` = $master_categories_id";
	$result = mysql_query($query, $link);
	$num_results = mysql_num_rows($result);
	$row = mysql_fetch_array($result);
	$cat_folder = $row["categories_name"];
	$cat_folder = str_replace(" ", "_", $cat_folder);
	$cat_folder = strtolower($cat_folder);
	
	$image_folder = $cat_folder . "/" . $artist_folder;
	return($image_folder);
}

///////////////////////////////////////////////////////////////
function copy_to_products_desc_table_etc($products_id, $verb, $link)
{
	$query = "SELECT * FROM `zen_products` WHERE `products_id` = $products_id";
	$result = mysql_query($query, $link);
	$num_results = mysql_num_rows($result);
	$row = mysql_fetch_array($result);
	$products_name = $row["products_name"];
	$products_description = $row["products_description"];
	$categories_id = $row["master_categories_id"];
		
	if ($verb == "INSERT")
	{
		$query = "INSERT INTO `zen_products_description` SET `products_id`=$products_id, `products_name`='$products_name', `products_description`='$products_description'";
		$result = mysql_query($query, $link);
		$query = "INSERT INTO `zen_products_to_categories` SET `products_id`=$products_id, `categories_id`=$categories_id";
		$result = mysql_query($query, $link);
	}
	else
	{
		$query = "UPDATE `zen_products_description` SET `products_name`='$products_name', `products_description`='$products_description' WHERE `products_id`=$products_id";
		$result = mysql_query($query, $link);
		$query = "UPDATE `zen_products_to_categories` SET `categories_id`='$categories_id' WHERE `products_id`=$products_id";
		$result = mysql_query($query, $link);
	}
}

///////////////////////////////////////////////////////////////////

if ($_POST['Re_Crop'])
	re_crop_image($zen_link);

read_enums($zen_link);
read_columns($view_id, $zen_link);

$search = do_search($view_id, $zen_link);
$update = do_update($zen_link);
	
if ($_GET['Deleted'])
	echo "Item deleted.";

if ($_POST["Clear"])
    write_table(array(), $zen_link);
elseif (!$search)
    write_table($_POST, $zen_link);

?>

</HTML>