/*
		Collection 400 is the collection that stores the whole content tree
		Collection 403 is the collection used for defining all the page types
		
*/


	
$q = "SELECT * FROM Collection_400 INNER JOIN Collection_403 ON Collection_403_ID = Collection_400_3 group by Collection_400_ID Order By Collection_400_1";
$allRows = $dbh->queryAll($q);

$q = "SELECT * FROM Collection_403 Order By Collection_403_1";
$allTemplates = $dbh->queryAll($q);

$q = "SELECT * FROM Collection_405 Order By Collection_405_1";
$allFieldRelations = $dbh->queryAll($q);

$q = "SELECT CollectionFieldID , CollectionFieldName FROM CollectionTaxonomy WHERE CollectionID = 13 Order By CollectionSortOrder  ";
$allFieldRelationsContent = $dbh->getAssoc($q);

$q = "SELECT CollectionFieldID , CollectionFieldName FROM CollectionTaxonomy WHERE CollectionID = 400 Order By CollectionSortOrder ";
$allFieldRelationsMigration = $dbh->getAssoc($q);

$smarty->assign('allFieldRelations',$allFieldRelations);
$smarty->assign('allFieldRelationsContent',$allFieldRelationsContent);
$smarty->assign('allFieldRelationsMigration',$allFieldRelationsMigration);

$smarty->assign('allRows',$allRows);	
$smarty->assign('allTemplates',$allTemplates);
	
$smarty->assign('errors',$errors);
$smarty->assign('ourTreeID',400);


if ($_POST['migrate'] == 1)
{
		/* 
				we start migrating the content 
		*/
		
		 include_once $_SERVER["DOCUMENT_ROOT"] ."/classes/classTree.php";
		 $tree 					= new Tree(); 
		 $CID 					= 400;
		 $collectionSettings  	= $api ->getCollectionSettings($CID);
		
		 $TreeSettings 			= $collectionSettings[9];
		 $SCID 					= $TreeSettings['ParentMenuColumn'];
		 $DisplayColumn 		= $TreeSettings['DisplayColumn'];
		
		 $tree->setup('Collection_'.$CID , 'Collection_'.$CID.'_ID' , 'Collection_'.$CID.'_'.$DisplayColumn , 'Collection_'.$CID.'_'.$SCID);
		 
		 $rootId = $tree -> getRootID();
		 
		 function getNodePath ($NodeID , $tree)
		 {
		 			$tmpCatId = $NodeID;
					$pathArray = array();
					$pathArray[] = $Node;
					while ( $tmpCatId != $rootId )
					{
							$parentCategories = $tree -> getParentsForNode ($tmpCatId);
										
							if (count($parentCategories) == 0)
							{
								$tmpCatId = $rootId;
							}
							else
							{
								$tmpCatId = $parentCategories[0]['CategoryID'];
								$pathArray[] = $tmpCatId;
							}
							
					}
						
							
					$tmp = array();
					$k = 0;
					for ($i = count ($pathArray); $i--; $i>-1)
					{
						$tmp[$k] = $pathArray[$i];
						$k++;
					}
					
					return $tmp;
					
		 }//end function 
		 
		 function textToParagraph ($text)
		 {
		 		$t = "";
				foreach(preg_split("/((\r?\n)|(\r\n?))/", $text) as $line){
					// do stuff with $line
					if($line !='')
					$t .= "<p>".$line."</p>\n";
				} 
				return $t;
		 }
		 
		/*
				STEP 1
				initialize all variables that we are going to use
				
		*/
		
		$ContentIDs 	= array();
		$PageIDs 		= array();
		$SideMenuIDs 	= array();
		$URLs 			= array();
		$ParentsIDs		= array();
		
		$MigrateFieldName = $api->_getCollectionFieldName(405,2);
		$ContentFieldName = $api->_getCollectionFieldName(405,3);
		
		/*
				STEP 2
				prepare URLs and an array that stores ID and Parent ID
		*/
		
		foreach ($allRows as $k => $v)
		{
				$url 	= preg_replace('/[^a-zA-Z0-9\s\._\-]/', '', strtolower($v['Collection_400_4']));
				$url 	= str_replace(' ','-',$url);
				$url 	= str_replace('--','-',$url);
				
				$URLs[$v['Collection_400_ID']] = $url;
				$ParentsIDs[$v['Collection_400_ID']] = $v['Collection_400_2'];
				
		}//end foreach
		
		foreach ($allTemplates  as $k => $v)
		{
				$Templates[$v['Collection_403_ID']] = $v;
		
		}//end foreach
		/*
				STEP 3
				We need to know if a row has children or not
		*/
		$tmp = array();
		foreach ($ParentsIDs as $k => $v)
		{
				$tmp[intval($v)] = intval($k);
		}//end foreach
		unset($tmp[0]);
		
		$HasChildrenArray = $tmp;
		
		
		/*
				STEP 4
				Loop through all the items and start creating content , pages and site menu items
		*/
		
		
		foreach ($allRows as $k => $v)
		{
				$CreateContent = 1;
				$CreatePage = 1;
				$CreateSiteMenu = 1;
				$PageDuplicate = 0;
				$SiteMenuDuplicate = 0;
				
				$thePath = getNodePath ($v['Collection_400_ID'] , $tree);
				
				$url = "";
				
				foreach ($thePath as $kpath => $vpath)
				{
						if ($vpath == "")
						{
						
						}
						else
						{
								$url.= "/".$URLs[$vpath];
						}
				}
				
				$url.= "/".$URLs[$v['Collection_400_ID']];
				
				$urlforpage = substr($url,1);
				
				if ($HasChildrenArray[$v['Collection_400_ID']])
				{
					$url.= "/";
				}
				else
				{
					$url.= ".html";
				}
				
				print "<h3>".$v['Collection_400_1'] . "</h3>";
				//print_r($thePath);
				//print "<br/>".$url . "<hr/>";
				
				//there is an exception to this URL creation way
				//if the page type is external link then the URL will be the one that is found inside the first line of the body content field
				if ($v['Collection_400_3'] == 2)
				{
					$url = strtok($v['Collection_400_6'], "\n");
					
					//we will also set the flag to not create content and page
					$CreateContent 		= 0;
					$CreatePage 		= 0;
					
				}	
				
				//if the page type is of home type , then we need the url to be /
				if ($v['Collection_400_3'] == 4)
				{
					$url = "/";
					$urlforpage = "index";
				}	
				
				
				//before we add, we need to make sure there is no other content that will share the same page url
				//if yes, we will have to update that page / content
				$q = "SELECT * FROM Collection_17 INNER JOIN Collection_13 ON Collection_13_ID = Collection_17_6 WHERE Collection_17_3 = '".$urlforpage."' ";
				$res = $dbh->query($q);
				if ($res->numRows() > 0)
				{
						$PageDuplicate = 1;
						$theDuplicatePage = $res->fetchRow(MDB2_FETCHMODE_ASSOC);
				}		
				
				//we also need to look for a duplicate site menu item
				$q = "SELECT * FROM Collection_276  WHERE Collection_276_2 = '".$url."' ";
				$res = $dbh->query($q);
				if ($res->numRows() > 0)
				{
						$SiteMenuDuplicate = 1;
						$theDuplicateSiteMenu = $res->fetchRow(MDB2_FETCHMODE_ASSOC);
				}		
				
				/*
						WE CREATE THE CONTENT
				*/
				$ContentID = NULL;
				if ($CreateContent == 1)
				{
							$Content = array();
							$Content['Collection_13_1'] = 'CNT - '. $v['Collection_400_1'];
							
							foreach ($allFieldRelations as $ak =>$av)
							{
									$FN1 = $api->_getCollectionFieldName(13,$av[$ContentFieldName]);
									$FN2 = $api->_getCollectionFieldName(400,$av[$MigrateFieldName]);
									
									//exception
									if ($av[$ContentFieldName] == 6)
									{
										$Content[$FN1] = textToParagraph ($v[$FN2]);
									}
									else
									{
										$Content[$FN1] = $v[$FN2];
									}	
							}//end foreach
							
							
							
							//if there is a special code 
							$TemplateCode = $Templates[$v[$api->_getCollectionFieldName(400,3)]][$api->_getCollectionFieldName(403,7)] ;
							if ($TemplateCode != '')
							{
									//we need to compile the template and get the content
									$smarty->assign('content',textToParagraph ($v[$api->_getCollectionFieldName(400,6)]));
									$smarty->assign('otherContent', $v);
									$Content[$api->_getCollectionFieldName(13,6)] = $smarty->fetch('string:'.$TemplateCode);
							}
							
							//content fields based on page type
							$Content['Collection_13_3'] = $Templates[$v[$api->_getCollectionFieldName(400,3)]][$api->_getCollectionFieldName(403,6)];
							$Content['Collection_13_4'] = $Templates[$v[$api->_getCollectionFieldName(400,3)]][$api->_getCollectionFieldName(403,5)];
							
							
							
							if ($PageDuplicate == 0)
							{
								$ContentID = $dbh->extended->getBeforeID('Collection_13');
								$dbh-> extended->autoExecute('Collection_13', $Content, MDB2_AUTOQUERY_INSERT);
								$ContentID = $dbh->extended->getAfterID($ContentID, 'Collection_13');
							}
							else
							{
								$dbh->extended->autoExecute('Collection_13', $Content, MDB2_AUTOQUERY_UPDATE, ' Collection_13_ID = ' . $theDuplicatePage['Collection_13_ID']);	
								$ContentID = $theDuplicatePage['Collection_13_ID'];
							}	
							
							
				}//end if create content
				/*
						WE CREATE THE PAGE
				*/
				if ($CreatePage == 1 && $ContentID != NULL)
				{
						$Page = array();
						$Page['Collection_17_1'] = 'CNT - '.$v['Collection_400_1'];
						$Page['Collection_17_2'] = $v['Collection_400_4'];
						$Page['Collection_17_3'] = $urlforpage;
						$Page['Collection_17_4'] = 1;
						$Page['Collection_17_5'] = $Templates[$v[$api->_getCollectionFieldName(400,3)]][$api->_getCollectionFieldName(403,2)] ;
						$Page['Collection_17_6'] = $ContentID;
						$Page['Collection_17_7'] = NULL;
						$Page['Collection_17_8'] = NULL;
						$Page['Collection_17_9'] = date(time());
						$Page['Collection_17_10'] = 'on';
						
						if ($PageDuplicate == 0)
						{
							$PageID = $dbh->extended->getBeforeID('Collection_17');
							$dbh-> extended->autoExecute('Collection_17', $Page, MDB2_AUTOQUERY_INSERT);
							$PageID = $dbh->extended->getAfterID($PageID, 'Collection_17');
						}
						else
						{
							$dbh->extended->autoExecute('Collection_17', $Page, MDB2_AUTOQUERY_UPDATE, ' Collection_17_ID = ' . $theDuplicatePage['Collection_17_ID']);	
							$PageID = $theDuplicatePage['Collection_17_ID'];
						}	
				
				}//end if
				
				/*
						WE CREATE THE SITE MENU
				*/
				if ($CreateSiteMenu == 1)
				{
						$SiteMenu = array();
						$SiteMenu['Collection_276_1'] = $v['Collection_400_4'];
						$SiteMenu['Collection_276_2'] = $url;
						$SiteMenu['Collection_276_3'] = NULL;
						$SiteMenu['Collection_276_4'] = 'on';
						$SiteMenu['Collection_276_5'] = NULL;
						$SiteMenu['Collection_276_6'] = NULL;
						$SiteMenu['Collection_276_7'] = NULL;
						$SiteMenu['Collection_276_8'] = NULL;
						$SiteMenu['Collection_276_9'] = NULL;
						
						if ($v['Collection_400_3'] == 2)
						{
							$SiteMenu['Collection_276_6'] = 'on';
						}
						
						if ($SiteMenuDuplicate == 0 )
						{
							$SiteMenuID = $dbh->extended->getBeforeID('Collection_276');
							$dbh-> extended->autoExecute('Collection_276', $SiteMenu, MDB2_AUTOQUERY_INSERT);
							$SiteMenuID = $dbh->extended->getAfterID($SiteMenuID, 'Collection_276');
						}
						else
						{
							$SiteMenuID = $theDuplicateSiteMenu['Collection_276_ID'];
							$dbh->extended->autoExecute('Collection_276', $SiteMenu, MDB2_AUTOQUERY_UPDATE, ' Collection_276_ID = ' . $theDuplicateSiteMenu['Collection_276_ID']);	
						}
						
						//we need to store this value so we can create the site menu tree structure a little bit later
						$SideMenuIDs[$v['Collection_400_ID']]  = $SiteMenuID;
				
				}//end if create site menu
				
				
				
				
				
				
		}//end foreach all rows
		
		
		/*
				STEP 5
				Go over the site menu one more time to be able to recreate the content site menu
		*/
		foreach ($allRows as $k => $v)
		{
				$TheID = $v['Collection_400_ID'];
				$TheParentID = $v['Collection_400_2'];
				
				if ($TheParentID > 0)
				{
						$TheSiteMenuID = $SideMenuIDs[$TheID];
						$TheSiteMenuParentID = $SideMenuIDs[$TheParentID];
						
						
						$q = "UPDATE Collection_276 SET Collection_276_7 = '".$TheSiteMenuParentID."' WHERE Collection_276_ID = '".$TheSiteMenuID."' ";
						$dbh->query($q);
						
				}
		
		}//end foreach 
		
		header('Location: /'.ADMIN_APP_DIR.'/admin.php?menu_id=11&module_id=11&collectionid=90&colid=2&nd=1');
		die('done');

}//end we start migrating the content


$page = array (
			"PageTitle"    => "Content Migration"
 		);
		
		
$smarty->assign("page",$page);
$smarty->display(ADMIN_APP_DIR.'/site-map-builder-migrate.html');