<?php
include ("config.php");
ob_start();
require("../ccm/functions.php");
$data = ob_get_clean();
ob_end_clean();
$selectuser = $_SESSION['sorter_username'];
$eventName = $_POST["eventName"];
$startdate = $_POST["startdate"];
$countItems = $_POST["totalRows"];

$partArray = array();
$qtyArray = array();

//GO THROUGH THE CHECKBOXES THAT ARE CHECKED...
	$i = 0; //start a counter
	//It is necessary to turn the $_POST map into a number valued array
	foreach ($_POST as $key => $value)
		{
			if(substr($key,0,5) == "check")  //TAKE OUT THE Checked FIELD VALUE
			{
				if (in_array($value,$partArray))
				continue;
				else
				$partArray[$i] = $value; //after check
			}
			else if(substr($key,0,3) == "qty")  //TAKE OUT THE QTY FIELD VALUE
			{
				if (in_array(substr($key,3),$partArray))
					{
						$qtyArray[$i] = $value;
						$i++;
					}
				else continue;
			}
		}
	
// Database connection variables 
$dbServer = $mysqlserver; 
$dbDatabase = $mysqldatabase; 
$dbDatabase2 = $mysqldatabase2; 
$dbUser = $mysqlusername; 
$dbPass = $mysqlpassword;

$sConn = mysql_connect($dbServer, $dbUser, $dbPass) 
or die("Couldn't connect to database server"); 
$dConn = mysql_select_db($dbDatabase, $sConn) 
or die("Couldn't connect to database $dbDatabase");

$data = ''; //start clean data

$header1 = "TemplateType=Home	Event: $eventName	Generated by: $selectuser	Start Date: $startdate	Number of Items: $countItems" . " \n";
//$header2 = "Caption	Description	catalogSK	Price	Filename	DeptName1	SubDeptName1	DeptName2	SubDeptName2	DeptName3	SubDeptName3	DeptName4	SubDeptName4	Keywords" . " \n";

$header2 = "SKU	UPC	ProductName	Brand	BulletPoint1	BulletPoint2	BulletPoint3	BulletPoint4	BulletPoint5	Description	Frame Description	MainImageURL	OtherImageURL1	OtherImageURL2	OtherImageURL3	ShippingWeight	ShippingWeightUnitOfMeasure	GalleryPrice	SalePrice	Currency	SaleStartDate	ConditionType	Ext. Length	Ext. Height	Ext. Width	Orientation	Keywords	Box Length (longest side)	Box Height (shortest side)	Box Width (2nd longest side)	Packaged Weight	Quantity	Qty Available" . " \n";


	$i = 0; //Start the counter 
    //$j = 0;
	//echo "Number of records: " . count($partArray) . "<br>";
	
	while ($i < (count($partArray))) //Loop for the entire size of the array
	{
			$SKU = ($partArray[$i]);
			//$i++;
			$qty = ($qtyArray[$i]);
			$i++;
        //echo " SKU: " . $SKU . " ";
        //echo " qty: " . $qty . "<br>";
		
		if ($SKU == "")
		continue 1;
		else
		{
		  /*$queryCheck = "UPDATE `hiresolution` SET `checked` = '1' WHERE `SKU` = '" . $SKU . "' LIMIT 1;";
		  $skuResultCheck = mysql_query($queryCheck);*/
		
		$querySKU = "SELECT * FROM `hiresolution` WHERE `SKU` = '" . $SKU . "' LIMIT 1;";
		$skuResult = mysql_query($querySKU);
		$myrow = mysql_fetch_array($skuResult);
		
			$SKU = $myrow["SKU"];
			$artName = $myrow["artName"];
			$artSKU = $myrow["artSKU"];
			$frameSKU = $myrow["frameSKU"];
			$artPrice = $myrow["artPrice"];
			$framePrice = $myrow["framePrice"];
			$totalPrice = $myrow["totalPrice"];
			
			$qtyOnHandArt = $myrow["qtyOnHandArt"];
			$qtyAvailable = $myrow["qtyAvailable"];
			$qtyOnHandFrames = $myrow["qtyOnHandFrames"];
			$unitsSoldArt = $myrow["unitsSoldArt"];
			$unitsSoldFrames = $myrow["unitsSoldFrames"];
			$dollarsSold = $myrow["dollarsSold"];
			
			$qtyRemain = $myrow["qtyRemain"];
			$idFrame = $myrow["idFrame"];	
			$mainImage = "http://www.overstockart.net/sorter/overstock/" . $SKU . ".jpg";
			
			$altImage = "overstock/rooms/" . $artSKU . "-" . $frameSKU . ".jpg";
			if (!file_exists($altImage)) 
			{
			$altImage = "overstock/rooms/" . $artSKU . "-" . $frameSKU . "R.jpg";
						if (!file_exists($altImage)) 
						{
						$altImage = "overstock/rooms/" . $SKU . "R.jpg";
						}
			}
			if (file_exists($altImage)) {
			$altImageDone2 = "http://www.overstockart.net/sorter/" . $altImage;
			//$checkAlt2 = '<a href="' . $altImageDone2 . '" target="_blank">ROOM IMAGE AVAILABLE</a>'; 
			}
			else {
			//$checkAlt2 = 'NO ROOM IMAGE';
			$altImageDone2 = "";
			}	
			
			$altImage = "overstock/corners/" . $artSKU . "-" . $frameSKU . ".jpg";
			if (!file_exists($altImage)) 
			{
			$altImage = "overstock/corners/" . $artSKU . "-" . $frameSKU . "C.jpg";
						if (!file_exists($altImage)) 
						{
						$altImage = "overstock/corners/" . $SKU . "C.jpg";
						}
			}
			if (file_exists($altImage)) {
			$altImageDone1 = "http://www.overstockart.net/sorter/" . $altImage;
			//$checkAlt2 = '<a href="' . $altImageDone2 . '" target="_blank">ROOM IMAGE AVAILABLE</a>'; 
			}
			else {
			//$checkAlt2 = 'NO ROOM IMAGE';
			$altImageDone1 = "";
			}
			
			/***************START UPC MODULE******************/
			//select from database all the referers
			/*$dbQuery = "SELECT * FROM `upc_manager` ORDER BY `upc5` DESC LIMIT 1";  
			$resultUPC = mysql_query($dbQuery) or die("Couldn't get the Contacts 2");
			$rowUPC = mysql_fetch_array($resultUPC); 
			$upc5 = $rowUPC['upc5'] + 1; //find the last upc and add 1 for frames*/			
			//Fetch first available upc5 codes:
			$dbQuery = "SELECT `upc5` FROM `upc_open` WHERE 1 ORDER BY `upc5` ASC LIMIT 1";  
			$result = mysql_query($dbQuery) or die("Couldn't get the Contacts");
			$row = mysql_fetch_array($result); 
			$upc5 = $row['upc5']; //find the next open upc
			
					//check if SKU has a UPC code in the UPC manager:
					$num_rows_upc = 0;
					$queryCheck = "SELECT * FROM `upc_manager` WHERE `CatalogSK` = '" . $SKU . "'";
					$resultCheck = mysql_query($queryCheck);
					$num_rows_upc = mysql_num_rows($resultCheck);
					if ( $num_rows_upc > 0) 
					{
					$queryUPC = "SELECT * FROM `upc_manager` WHERE `CatalogSK` = '" . $SKU . "' LIMIT 1";
					$resultUPC = mysql_query($queryUPC);
						while($rowUPC = mysql_fetch_array($resultUPC))
						{
						if ($rowUPC["UPC"] != "")
						$upc = $rowUPC["UPC"];	
						else
							{
							$upc = createUPC($upc5);
							$query = "UPDATE `upc_manager` SET `UPC` = '" . $upc . "',  `upc5` = '" . $upc5 . "' WHERE `CatalogSK` = '" . $SKU . "';";
							//$query = "INSERT INTO upc_manager (CatalogSK, UPC) VALUES ('$SKU', '$upc');";
							mysql_query($query) or die("Couldn't MOD row to UPC manager $SKU, $upc");
							$queryDelete = "DELETE FROM `upc_open` WHERE `upc5` = '$upc5';";
				 			mysql_query($queryDelete); 
							} 
						}
					}
					else {
					$upc = createUPC($upc5);
					$query = "INSERT INTO upc_manager (CatalogSK, UPC, upc5) VALUES ('$SKU', '$upc', '$upc5');";
					mysql_query($query) or die("Couldn't add row to UPC manager $SKU, $upc");  
					$queryDelete = "DELETE FROM `upc_open` WHERE `upc5` = '$upc5';";
				 	mysql_query($queryDelete); 
					//echo $query . "<br><Br>"; 
					}
			/***************END UPC MODULE******************/
			
			//end duplicate check
			$query5 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $artSKU . "' || UPPER(CatalogSK) = '" . $artSKU . "P' || UPPER(SUBSTRING(CatalogSK,1,7)) = '" . $artSKU . "' ORDER BY LENGTH(CatalogSK) ASC LIMIT 1;";
			//echo $query5 . "<br>";
			$result5 = mysql_query($query5);
			while($row2 = mysql_fetch_array($result5))
			{
					$Caption = $row2["Ordertext"];
					$Caption = strip_tags($Caption);
					$imageCaption = trim($Caption);
					$imagePrice = $row2["Price"];
					$imageSPrice = $row2["SpecialPrice"];
					$heightArt = $row2["Hieghtart"];
					$widthArt = $row2["Widthart"];
					$artist = $row2["SubDeptName1"];
					
					if($heightArt > $widthArt) $orientation = "Vertical";
					else if ($heightArt < $widthArt) $orientation = "Horizontal";
					else $orientation = "Square";
					
					$ProductName = "Art Reproduction Oil Painting - " . $imageCaption . " - " . $row2["SubDeptName4"] . " - Hand Painted Canvas Art";
					
					//TAKE OUT ALL OF THE HTML FROM THE DESCRIPTION
					$description = " " . $row2["Description"];
					if(strpos($description,"Looking for other sizes?  Click Here  for more options!") > 0 )
					{
					$description = substr($description,strpos($description,"Looking for other sizes?  Click Here  for more options!") + strlen("Looking for other sizes?  Click Here  for more options!"));
					}
					if(strpos($description,"Need Help Decorating your Home?  Click Here  to get Inspired!") > 0 )
					{
					$description = substr($description,strpos($description,"Need Help Decorating your Home?  Click Here  to get Inspired!") + strlen("Need Help Decorating your Home?  Click Here  to get Inspired!"));
					 }
					 
					$description = strip_tags($description);
					$imageDesc = trim($description);
					//$fileName2 = $row2["Filename"];
					//echo "painting: " . $fileName2 . "<br>";
					$SubDeptName1 = $row2["SubDeptName1"];
					$SubDeptName2 = $row2["SubDeptName2"];
					$SubDeptName3 = $row2["SubDeptName3"];
					$SubDeptName4 = $row2["SubDeptName4"];
					$artSize = $row2["SubDeptName4"];
			}
			
				//for gallery wraps...
				if (substr($frameSKU,0,3) == "GAL") {
				//	echo $frameSKU . "<br>";
						if ($artSize == 'Customary  16" X 20"' ) $frameSKU = "GALWRP14X18";
						else if ($artSize == 'Classic 20" X 24"' ) $frameSKU = "GALWRP18X22";
						else if ($artSize == 'Square 24" X 24"' ) $frameSKU = "GALWRP22X22";
						else if ($artSize == 'Large 24" X 36"' ) $frameSKU = "GALWRP22X34";
						else if ($artSize == 'Extra Large 30" X 40"' ) $frameSKU = "GALWRP28X38";						
				}

			//end duplicate check
			$query5 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $frameSKU . "' || UPPER(CatalogSK) = 'FR-" . $frameSKU . "' LIMIT 1;";
			//echo $query5 . "<br>";
			$result5 = mysql_query($query5);
			while($row3 = mysql_fetch_array($result5))
			{			
			$frameSKU = $row3["CatalogSK"];
			$frameText = $row3["Ordertext"]; 
			$framePrice = $row3["Price"]; 
			$frameSPrice = $row3["SpecialPrice"];
			$frameWeight = $row3["Weight"];
			
			$frameWidth = $row3["FrameWidth"];
			$frameLength = $row3["FrameHeight"];
			$frameHeight = 2;
			
			$frameCheck = substr($frameSKU,strpos($frameSKU,"-")+1); //find the frame part number
			$frameCheck6 = substr($frameSKU,0,6);
			
			$frameSize = $frameWidth . '" X ' . $frameHeight . '"'; 
			
					$size = substr($frameSKU,strlen($frameSKU)-5,5);
					$size8X10 = substr($frameSKU,strlen($frameSKU)-4,4);					
					
					list ($boxLength, $boxWidth, $boxHeight, $boxWeight) = dimensions($frameSKU,$frameCheck,$frameCheck6,$size,$size8X10);
			}
					
					if ($SubDeptName1 != "")
					{
					$DeptName1 = "Shop by Artist";
					}
					else  
					{
					$DeptName1 = "";
					}
					
		    		if ($SubDeptName2 != "")
					$DeptName2 = "Shop by Subject";
					else  $DeptName2 = "";
					
		    		if ($SubDeptName3 != "")
					$DeptName3 = "Shop by Style";
					else  $DeptName3 = "";
					
		    		if ($SubDeptName4 != "")
					{
					$DeptName4 = "Shop by Size";
										
					if ($SubDeptName4 == 'Standard 20"x24"')
						{
						$weight = 24;
						}
						else if ($SubDeptName4 == 'Framed Small 8" X 10"')
						{
						$weight = 12;
						} 
						else if ($SubDeptName4 == 'Large 24" X 36"')
						{
						$weight = 30;
						} 
						else if ($SubDeptName4 == 'Square 24"x24"')
						{
						$weight = 30;
						} 
						else if ($SubDeptName4 == 'Square 24"x24"')
						{
						$weight = 30;
						} 
						else if ($SubDeptName4 == 'Extra Large 30"x40"')
						{
						$weight = 63;
						} 
						else if ($SubDeptName4 == 'Extra Large 30" X 40"')
						{
						$weight = 63;
						} 
						else if ($SubDeptName4 == 'Extra Large 36" X 48"')
						{
						$weight = 63;
						} 
						else
						{
						$weight = 26;
						}
					}
					else  
					{
					$DeptName4 = "";
					$bullet1 = "Call for Size information: 1-866-686-1888";
					$weight = 26;
					}
			
			$fullCaption = stripslashes($imageCaption . " with ". $frameText);
			$fullDescription = stripslashes($imageDesc . " Frame Description: " . $frameText);
			$fullPrice = $imagePrice + $framePrice;
			$salePrice = $imageSPrice + $frameSPrice;
			$totalWeight = $frameWeight + $shipWeight;
			
				$artK = $imageCaption;
				$artistK = "";
					if (strpos($imageCaption," - "))
					{
					list($artistK,$artK) = explode(" - ",$imageCaption,2);
					}
					
			$SKUfix = $artSKU . "-" . $frameSKU; //fix when the frame SKU is not right
			
			//echo $SKUfix . "<br>";
			if (substr($SKUfix,0,3) == "WOA" || (substr($SKUfix,0,1) == "2" && substr($artSKU,-1) != "H") )
					{			
					$bullet1 = "Framed canvas print size (not including frame): " . $SubDeptName4;
					$bullet2 = "Framed canvas print size (exterior dimensions inches): " . $frameSize;					
					$bullet3 = "Framed canvas print arrives ready to hang on your wall with hanging hardware included";
					$bullet4 = "";
					if ($artist != "")
						{
						$bullet5 = trim($artK) . " - Framed canvas print of an original painting by " . $artist;
						}
						else  
						{
						$bullet5 = trim($artK) . " - Framed canvas print.";
						}
					$keywords = $artK . ";" . $artist . ";Art Reproduction; Canvas Print; " . $orderText . " ;Print on Canvas;Art; Wall Decor; Reproductions; Canvas; Framed Art";
					}
					else if (strpos($SKUfix,"FR-") || strpos($SKUfix,"-G"))
					{
					$bullet1 = "Framed painting size (not including frame): " . $SubDeptName4;
					$bullet2 = "Framed painting size (exterior dimensions inches): " . $frameSize;					
					$bullet3 = "100% handmade oil painting on artist grade canvas - certificate of authenticity included";
					$bullet4 = "Framed paintings arrive ready to hang on your wall with hanging hardware included";
						if ($artist != "")
						{
						$bullet5 = trim($artK) . " - Framed Oil reproduction of an original painting by " . $artist;
						}
						else  
						{
						$bullet5 = trim($artK) . " - Framed Oil reproduction.";
						}
					$keywords = $artK . ";" . $artist . ";Art Reproduction; Oil Paintings; " . $orderText . " ;Oil Paintings; Oil painting; Art; Wall Decor; Reproductions; Canvas; Paintings; Framed Art";
					}
					else
					{
					$bullet1 = "Hand carved and hand painted ceramic tile";
					$bullet2 = "Ceramic Trivet Tiles arrive ready to hang on your wall with hanging hardware included";					
					$bullet3 = "";
					$bullet4 = "";
					if ($artist != "")
						{
						$bullet5 = trim($artK) . " - Hand carved ceramic tile of an original painting by " . $artist;
						}
						else  
						{
						$bullet5 = trim($artK) . " - Hand carved ceramic tile.";
						}
					$keywords = $artK . ";" . $artist . "Art Tiles; Ceramic Tiles; " . $orderText . "; Ceramic Art Tiles";
					}
				
			//$keywords = $artK . ";" . $artistK . ";Art Reproduction; Oil Paintings; " . $orderText . " ;Oil Paintings; Oil painting; Art; Wall Decor; Reproductions; Canvas; Paintings; Framed Art";
		
		 $line = $SKUfix . "	" . $upc . "	" . $fullCaption . "	" . "overstockArt" . "	" . $bullet1 . "	" . $bullet2 . "	" . $bullet3 . "	" .  $bullet4 . "	" . $bullet5 .	"	" . $fullDescription . "	" . $frameText . "	" . $mainImage  . "	" .  $altImageDone1  . "	" .  $altImageDone2  . "	" . "" . "	" . $weight . "	" . "LB" . "	" . $fullPrice . "	" . $salePrice . "	" . "USD" . "	" . $startdate . "	" . "New" . "	" . $frameLength . "	" . $frameHeight . "	" . $frameWidth . "	" . $orientation . "	" . $keywords . "	" . $boxLength . "	" . $boxHeight . "	" .  $boxWidth . "	" . $boxWeight . "	" . $qty . "	" . $qtyAvailable . " \n"; 
		//echo $line . "<br>"; 
	   //start line for excell output.
	   $data .= $line ;
        }
	}
	
	//print $header . $data;
$document = $header1 . $header2 . $data;
//echo $document;
$document = trim($document);
//creating the file on the server
$fh = fopen("feeds/$eventName.txt", "w");
fwrite($fh, $document);
$file = 'feeds/' . $eventName . '.txt';
$remote_file = $eventName . '.txt';
fclose($fh);

header("Content-type: text/xml");
//can change the name of file here to the 
header("Content-Disposition: attachment; filename=$eventName.txt");
header("Pragma: no-cache");
header("Expires: 0");
print $header1 . $header2 . $data;
?>