<?php
/********
Amitai Sasson
feedCreator2.php
This is the file that does
all the cleanup, stores the file and uploads 
the information into the database.
*********/
// feedCreator.php: makes the feed
include "config.php";
// Database connection variables 
$dbServer = $mysqlserver; 
$dbDatabase = $mysqldatabase; 
$dbDatabase2 = $mysqldatabase2; 
$dbUser = $mysqlusername; 
$dbPass = $mysqlpassword;
$row = 0; //number of rows
if(!isset($sort)) $sort = "Primary"; //set sorting for the main table
$sConn = mysql_connect($dbServer, $dbUser, $dbPass) 
or die("Couldn't connect to database server"); 
$dConn = mysql_select_db($dbDatabase2, $sConn) 
or die("Couldn't connect to database $dbDatabase2");
$data = ''; //start clean data
$frames20x24 = '';
$frames24x36 = '';
$frames36x48 = '';
$frames30x40 = '';
$crossSell = '';

$array_parts = array();  //array to check for the entire list

$header = "ProductID	Title	shortTitle	Description	Price	URL	ThumbURL	ImageURL	Retail Price	Quantity	Shipping	Currency	Style	Subject	Artist	Keywords	Size	widthArt	hieghtArt	widthExt	heightExt	Original Image	Unframed Price	frameTitle	Check" . " \n"; //	color1	color2	color3	color4	color5	color6	color7	color8	color9

$querybest = "SELECT LEFT( p.`pnchina` , LOCATE( '-', p.`pnchina` ) -1 ) AS `part_china`, SUM( pt.sales  ) AS `total_rev` , SUM( pt.units_sold ) AS `total_units` 
FROM peachtree pt
JOIN parts p ON pt.`itemID` = p.`partno`
WHERE pt.`itemID` NOT LIKE '%FR-%'
AND p.`active` =1
GROUP BY LEFT( p.`pnchina` , LOCATE( '-', p.`pnchina` ) -1 ) 
ORDER BY SUM( pt.`units_sold` ) DESC";
//echo $query1;
$resultbest = mysql_query($querybest);
while($myrowbest = mysql_fetch_array($resultbest))
{
	$dConn = mysql_select_db($dbDatabase2, $sConn) or die("Couldn't connect to database $dbDatabase");
	$partno = "";
	$partid = $myrowbest["part_china"];
	$queryPN = "SELECT partno FROM parts WHERE LEFT( `pnchina` , LOCATE( '-', `pnchina` ) -1 ) = '" . $partid . "' ORDER BY unit_sold DESC LIMIT 1;"; //AND qty_on_hand > 1
		//echo $queryPN;
		$resultPN = mysql_query($queryPN);
		$rowPN = mysql_fetch_array($resultPN, MYSQL_NUM);
		$partno = $rowPN[0];
		
		if ($partno == "") continue;
		
		//if the part number is already present then skip...
		if(in_array($partno,$array_parts)) continue;

		$dConn = mysql_select_db($dbDatabase, $sConn) or die("Couldn't connect to database $dbDatabase");
		$part_full = "";
		$fullproduct_files = glob("frameCropIpad/" . $partno . "-*.png");
		//extract the part number of the product
		if(is_array($fullproduct_files) && count($fullproduct_files) > 0)
		{
			foreach($fullproduct_files as $fullproduct_file)
			{
				$fullproduct = basename($fullproduct_file, ".png").PHP_EOL;
				$fullproduct = trim($fullproduct);
				//find the painting part number
				$pos = strpos($fullproduct, "-");
				$artSKU = strtoupper(substr($fullproduct,0,$pos));//get the pic of the painting itself
				$artSKU = trim($artSKU);
				$query5 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $artSKU . "' || UPPER(CatalogSK) = '" . $artSKU . "P'  LIMIT 1;";
				//echo $query5 . "<br>";
				$result5 = mysql_query($query5);
				if (mysql_num_rows($result5)) 
				{
				$frameSKU = strtoupper(substr($fullproduct,strpos($fullproduct,"-")+1)); //find the frame part number
				$frameSKU = trim($frameSKU);
				$query4 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $frameSKU . "' || UPPER(CatalogSK) = 'FR-" . $frameSKU . "' LIMIT 1;";	
					//echo $query4 . "<br>";
					//echo "full product: " . $fullproduct . "frame sku: " . $frameSKU . "<br>";
					$result4 = mysql_query($query4);
					if (mysql_num_rows($result4)) 
					{
					$part_full = trim($fullproduct); 
					//echo "full product: " . $part_full . "<br>";
					continue; 
					}
				}
			}
		}

		$query3 = "SELECT * FROM `framed-feed` WHERE `CatalogSK` = '" . $part_full . "' ORDER BY `Primary` DESC LIMIT 1;"; // WHERE `active` = 1 AND  ORDER BY `SpecialPrice` ASC for sorted by price...
		//echo $query3 . "<br>";
		$result2 = mysql_query($query3) or die("Couldn't add row 1"); 
		while($myrow = mysql_fetch_array($result2))
			{
			
			if ( ($myrow["CatalogSK"] != "") && (substr($myrow["CatalogSK"],0,4) != 'STR-' ) && (substr($myrow["CatalogSK"],0,7) != 'GAL-WRP' ) && (substr($myrow["CatalogSK"],0,2) != 'FR' ) && (substr($myrow["CatalogSK"],0,2) != 'GC' ) && ($myrow["CatalogSK"] != "CATALOG1"))
				{
				
				$shortTitle =  substr($myrow["Ordertext"],0,strpos($myrow["Ordertext"],"with"));
				$frameTitle = substr($myrow["Ordertext"],strpos($myrow["Ordertext"],"with")+5);
			
$caption = "Art Reproduction Oil Painting - " . $myrow["Caption"] . " - " . $myrow["SubDeptName4"] . " - Hand Painted Canvas Art";
					//DESCRIPTION
					$description = $myrow["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!"));
					 }
 					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);
					$description = trim($description);
					$catalogSK = $myrow["CatalogSK"];
					
					//find the painting part number
					$pos = strpos($catalogSK, "-");
					$artSKU = strtoupper(substr($catalogSK,0,$pos));//get the pic of the painting itself
					
					$path_thumb = $default_url . "shadow/";
					$path_large = $default_url . "framedpng/";
					$path_framed_thumb = $default_url . "frameCropIpad/";
					$path_original = $default_url . "large/"; //"http://site.overstockart.com/sorter/original/";
					
					$part_id = $catalogSK;
					//$imagePartId = $row['CatalogSK'];
					//$part_id = substr($catalogSK,0,strpos($catalogSK,'-'));
					$large_image = $path_large . $part_id . '.png';
					$thumbnail_framed_image = $path_framed_thumb . $part_id . '.png';
					
					$original_image = $path_original . $artSKU . '.jpg';
					
					$path_to_thumb_jpg = $path_thumb . $artSKU . '.jpg';
					$path_to_thumb_gif = $path_thumb . $artSKU . '.gif';
					if(file_exists('shadow/'. $artSKU .'.jpg'))
					{
					// file exists
					$path_to_thumb = $path_to_thumb_jpg;
					} 
					else 
					{
						if(file_exists('shadow/'. $artSKU .'.gif'))
						{
						$path_to_thumb = $path_to_thumb_gif;
						}
						else
						{
						// file doesn't exists
						continue;
						}
					}
					
					$orderText = $myrow["Ordertext"] . " - " . $myrow["SubDeptName4"] . " - Hand Painted Canvas Art";
					$fullprice = $myrow["Price"];
					$fileName = $myrow["Filename"];
					$link = "http://www.overstockart.com/" . $myrow["YahooID"] . ".html" . "?utm_source=iphone-app&utm_medium=iphone-app&utm_term=" . $catalogSK;
					
			$keywords = $myrow["Caption"] . ",Art Reproduction, Oil Paintings, " . $orderText . " ,Oil Paintings, Oil painting, Art, Wall Decor, Reproductions, Canvas, Paintings";
					
					$salePrice = $myrow["SpecialPrice"];
					
					$SubDeptName1 = $myrow["SubDeptName1"];
					$SubDeptName2 = $myrow["SubDeptName2"];
					$SubDeptName3 = $myrow["SubDeptName3"];
					
					$SubDeptName1 = $myrow["SubDeptName1"];
		    		if ($SubDeptName1 != "")
					$Artist = $SubDeptName1;
					else  $Artist = "";
					
					$SubDeptSubject = $myrow["SubDeptName2"];
					$SubDeptStyle = $myrow["SubDeptName3"];
					
					$SubDeptName4 = $myrow["SubDeptName4"];
		    		if ($SubDeptName4 != "")
					$Size = $SubDeptName4;
					else  $Size = "";
					
					$query5 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $artSKU . "' || UPPER(CatalogSK) = '" . $artSKU . "P'  LIMIT 1;";
					//echo $query5 . "<br>";
					$result5 = mysql_query($query5);
					if (!mysql_num_rows($result5)) continue;
					while($row2 = mysql_fetch_array($result5))
					{
					//$artSKU = strtoupper($row2["CatalogSK"]);
					$unframed_price = $row2["SpecialPrice"]; 
					$widthArt  = $row2["Widthart"];
					$hieghtArt  = $row2["Hieghtart"];
					$shortTitle = $row2["Ordertext"];
					}
					
					//find the frame part number
					$frameSKU = strtoupper(substr($catalogSK,strpos($catalogSK,"-")+1)); //find the frame part number
					$query4 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $frameSKU . "' || UPPER(CatalogSK) = 'FR-" . $frameSKU . "' LIMIT 1;";
	
					//echo $query4 . "<br>";
					$result4 = mysql_query($query4);
					if (!mysql_num_rows($result4)) continue;
					while($row3 = mysql_fetch_array($result4))
					{
					$frameTitle = $row3["Ordertext"];
					$FinishedSize=str_replace(' 1/2','.5', $row3["SubDeptName4"]);
					$FinishedSize=str_replace(' 1/8','.125', $FinishedSize);
					$FinishedSize=str_replace(' 1/4','.25', $FinishedSize);
					$FinishedSize=str_replace(' 3/4','.75', $FinishedSize);
					$widthExt = trim(substr($FinishedSize,0,strpos($FinishedSize,'"')));
						if (strpos($FinishedSize,'x')){
	$heightExt = trim(substr($FinishedSize,strpos($FinishedSize,'x')+1,strrpos($FinishedSize,'"')-(strpos($FinishedSize,'x')+1)));				
						}
						else {
	$heightExt = trim(substr($FinishedSize,strpos($FinishedSize,'X')+1,strrpos($FinishedSize,'"')-(strpos($FinishedSize,'X')+1)));
						}
					}
					
					//get the right sides for each frame then perform swap
					if ($widthArt > $hieghtArt && $widthExt < $heightExt) $widthExt ^= $heightExt ^= $widthExt ^= $heightExt;
					else if ($widthArt < $hieghtArt && $widthExt > $heightExt) $widthExt ^= $heightExt ^= $widthExt ^= $heightExt;
					
					$checkImage = "frameCropIpad/" . $part_id . '.png';
			if (file_exists($checkImage)) $checkMain = 'Y'; 
			else $checkMain = 'N';
					
					//FOR THE COLOR LIST
					/*$colors=array(); 
					$query4 = "SELECT * FROM `color_match2` WHERE `partno`='". $artSKU ."' AND `color_count` > 25 ORDER BY `color_count` DESC LIMIT 16";
					$result4 = mysql_query($query4) or die("Couldn't add row 1"); 
					while($row_color = mysql_fetch_array($result4))
						{
						//ECHO "INSIDE";
						$colors[] = $row_color['color_code']; 
						}
					$color_tabs = implode("	",$colors);
					$i = 0;
					while(count($colors)+$i < 10)
					{
					   $color_tabs .= "	";
					   $i++;
					}*/
					//echo $color_tabs . "<br>";
					
					$array_parts[] = $partno; //insert an item into an array to check
						
	   $line = $catalogSK . "	" . $caption  . "	" . $shortTitle . "	" . $description . "	" . $salePrice . "	" . $link . "	" . $thumbnail_framed_image . "	" . $large_image . "	" . $fullprice . "	" . "3" . "	" . "0.00" . "	" . "USD" . "	" . $SubDeptStyle . "	" . $SubDeptSubject . "	" . $Artist . "	" . $keywords . "	" . $Size . "	" . $widthArt . "	" . $hieghtArt . "	" . $widthExt . "	" . $heightExt . "	" . $original_image . "	" . $unframed_price . "	" . $frameTitle . "	" . $checkMain . "\n"; 
	   //. "	" . $color_tabs 
	   
	   //start line for excell output.
	   $data .= $line ;
		//		}
			}
		}
	}

	$dConn = mysql_select_db($dbDatabase, $sConn) or die("Couldn't connect to database $dbDatabase");

	$query3 = "SELECT * FROM `framed-feed` WHERE `active` = '1' GROUP BY SUBSTR( `CatalogSK` , 1, POSITION( '-' IN `CatalogSK` ) - 1 )  ORDER BY `Primary` DESC";  //ORDER BY `SpecialPrice` ASC
		//echo $query3 . "<br>";
		$result2 = mysql_query($query3) or die("Couldn't add row 1"); 
		while($myrow = mysql_fetch_array($result2))
			{
			$catalogSK = $myrow["CatalogSK"];
			
			$checkImage = "frameCropIpad/" . $catalogSK . '.png';
			if (!file_exists($checkImage)) continue; 
			
			if ( ($myrow["CatalogSK"] != "") && (substr($myrow["CatalogSK"],0,4) != 'STR-' ) && (substr($myrow["CatalogSK"],0,7) != 'GAL-WRP' ) && (substr($myrow["CatalogSK"],0,2) != 'FR' ) && (substr($myrow["CatalogSK"],0,2) != 'GC' ) && ($myrow["CatalogSK"] != "CATALOG1"))
				{

				$shortTitle =  substr($myrow["Ordertext"],0,strpos($myrow["Ordertext"],"with"));
				$frameTitle = substr($myrow["Ordertext"],strpos($myrow["Ordertext"],"with")+5);
			
$caption = "Art Reproduction Oil Painting - " . $myrow["Caption"] . " - " . $myrow["SubDeptName4"] . " - Hand Painted Canvas Art";
					//DESCRIPTION
					$description = $myrow["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!"));
					 }
 					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);
					$description = trim($description);
					
					//find the painting part number
					$pos = strpos($catalogSK, "-");
					$artSKU = strtoupper(substr($catalogSK,0,$pos));//get the pic of the painting itself
					
					$path_thumb = $default_url . "shadow/";
					$path_large = $default_url . "framedpng/";
					$path_framed_thumb = $default_url . "frameCropIpad/";
					$path_original = $default_url . "large/"; //"http://site.overstockart.com/sorter/original/";
					
					$part_id = $catalogSK;
					//$imagePartId = $row['CatalogSK'];
					//$part_id = substr($catalogSK,0,strpos($catalogSK,'-'));
					$large_image = $path_large . $part_id . '.png';
					$thumbnail_framed_image = $path_framed_thumb . $part_id . '.png';
					
					$original_image = $path_original . $artSKU . '.jpg';
					
					$path_to_thumb_jpg = $path_thumb . $artSKU . '.jpg';
					$path_to_thumb_gif = $path_thumb . $artSKU . '.gif';
					if(file_exists('shadow/'. $artSKU .'.jpg'))
					{
					// file exists
					$path_to_thumb = $path_to_thumb_jpg;
					} 
					else 
					{
						if(file_exists('shadow/'. $artSKU .'.gif'))
						{
						$path_to_thumb = $path_to_thumb_gif;
						}
						else
						{
						// file doesn't exists
						continue;
						}
					}
					
					$orderText = $myrow["Ordertext"] . " - " . $myrow["SubDeptName4"] . " - Hand Painted Canvas Art";
					$fullprice = $myrow["Price"];
					$fileName = $myrow["Filename"];
					$link = "http://www.overstockart.com/" . $myrow["YahooID"] . ".html" . "?utm_source=iphone-app&utm_medium=iphone-app&utm_term=" . $catalogSK;
					
				$keywords = $myrow["Caption"] . ",Art Reproduction, Oil Paintings, " . $orderText . " ,Oil Paintings, Oil painting, Art, Wall Decor, Reproductions, Canvas, Paintings";
					
					$salePrice = $myrow["SpecialPrice"];
					
					$SubDeptName1 = $myrow["SubDeptName1"];
					$SubDeptName2 = $myrow["SubDeptName2"];
					$SubDeptName3 = $myrow["SubDeptName3"];
					
					$SubDeptName1 = $myrow["SubDeptName1"];
		    		if ($SubDeptName1 != "")
					$Artist = $SubDeptName1;
					else  $Artist = "";
					
					$SubDeptSubject = $myrow["SubDeptName2"];
					$SubDeptStyle = $myrow["SubDeptName3"];
					
					$SubDeptName4 = $myrow["SubDeptName4"];
		    		if ($SubDeptName4 != "")
					$Size = $SubDeptName4;
					else  $Size = "";
					
					$query5 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $artSKU . "' LIMIT 1;";
					//echo $query5 . "<br>";
					$result5 = mysql_query($query5);
					while($row2 = mysql_fetch_array($result5))
					{
					$artSKU = strtoupper($row2["CatalogSK"]);
					
					$unframed_price = $row2["SpecialPrice"]; 
					$widthArt  = $row2["Widthart"];
					$hieghtArt  = $row2["Hieghtart"];
					$shortTitle = $row2["Ordertext"];
					}
					
					//if the part number is already present then skip...
					if(in_array($artSKU,$array_parts)) continue;
					
					$array_parts[] = $artSKU; //insert an item into an array to check

					//find the frame part number
					$frameSKU = strtoupper(substr($catalogSK,strpos($catalogSK,"-")+1)); //find the frame part number
					$query4 = "SELECT * FROM `catalogcity` WHERE UPPER(CatalogSK) = '" . $frameSKU . "' || UPPER(CatalogSK) = 'FR-" . $frameSKU . "' LIMIT 1;";
	
					//echo $query4 . "<br>";
					$result4 = mysql_query($query4);
					while($row3 = mysql_fetch_array($result4))
					{
					$frameTitle = $row3["Ordertext"];
					$FinishedSize=str_replace(' 1/2','.5', $row3["SubDeptName4"]);
					$FinishedSize=str_replace(' 1/8','.125', $FinishedSize);
					$FinishedSize=str_replace(' 1/4','.25', $FinishedSize);
					$FinishedSize=str_replace(' 3/4','.75', $FinishedSize);
					$widthExt = trim(substr($FinishedSize,0,strpos($FinishedSize,'"')));
						if (strpos($FinishedSize,'x')){
	$heightExt = trim(substr($FinishedSize,strpos($FinishedSize,'x')+1,strrpos($FinishedSize,'"')-(strpos($FinishedSize,'x')+1)));				
						}
						else {
	$heightExt = trim(substr($FinishedSize,strpos($FinishedSize,'X')+1,strrpos($FinishedSize,'"')-(strpos($FinishedSize,'X')+1)));
						}
					}
					
					//get the right sides for each frame then perform swap
					if ($widthArt > $hieghtArt && $widthExt < $heightExt) $widthExt ^= $heightExt ^= $widthExt ^= $heightExt;
					else if ($widthArt < $hieghtArt && $widthExt > $heightExt) $widthExt ^= $heightExt ^= $widthExt ^= $heightExt;

					
			$checkImage = "frameCropIpad/" . $part_id . '.png';
			if (file_exists($checkImage)) $checkMain = 'Y'; 
			else $checkMain = 'N';
						
	   $line = $catalogSK . "	" . $caption  . "	" . $shortTitle . "	" . $description . "	" . $salePrice . "	" . $link . "	" . $thumbnail_framed_image . "	" . $large_image . "	" . $fullprice . "	" . "3" . "	" . "0.00" . "	" . "USD" . "	" . $SubDeptStyle . "	" . $SubDeptSubject . "	" . $Artist . "	" . $keywords . "	" . $Size . "	" . $widthArt . "	" . $hieghtArt . "	" . $widthExt . "	" . $heightExt . "	" . $original_image . "	" . $unframed_price . "	" . $frameTitle . "	" . $checkMain . "\n"; 
	   //. "	" . $color_tabs 
	   
	   //start line for excell output.
	   $data .= $line ;
		//		}
			}
		}

$data = remove_unnecessary($data);

//print $header . $data;
$document = $header . $data; 
//echo $document;
$document = trim($document);
//creating the file on the server
$fh = fopen("feeds/ipad-app.txt", "w");
fwrite($fh, $document);
$file = 'feeds/ipad-app.txt';
$remote_file = 'ipad-app.txt';
fclose($fh);

header("Content-type: text/xml");
header("Content-Disposition: attachment; filename=ipad-app.txt");
header("Pragma: no-cache");
header("Expires: 0");
print $header . $data;

//echo $header . \n;
//echo $data;
function remove_unnecessary($str, $char = "\n") {
    while (true) {
        if (substr ($str, -(strlen($char))) == $char) {
            $str = substr ($str, 0, -(strlen($char)));
        } else {
            break;
        }
    }
   
    return $str;
}
	?>