<?php

if(isset($_REQUEST['btn_update'])) {
	$favlist = array();
	foreach($_POST as $ky=>$ps) {	
		if(substr($ky,0,3) == "ch_") {
			$chd = explode("_",$ky);
			
			if($ps>0) {
				$favlist[$ps] = $chd[1];
			}
		}
	}

	ksort($favlist);
	
	$sql = "delete from mst_user_fav where user_id = " . $_SESSION['seas_user_id'];
	mysql_query($sql);
	
	$lcnt=1;
	foreach($favlist as $fky=>$fav) {
		$sqlins = "insert into mst_user_fav (user_id,chid,forder) values (" . $_SESSION['seas_user_id'] ."," . $fav ."," . $fky . ")";
		mysql_query($sqlins);
		$lcnt++;
		
		if($lcnt>5) break; // Maximum 3 channels
	}
}

$chlist = array();

$sql = "select mst_channels.chid,mst_channels.chname,
			mst_networks.netdesc ,mst_typologies.typo_desc
			from mst_channels 
				 left join mst_networks on mst_channels.grpid = mst_networks.id
				 left join mst_typologies on mst_channels.typoid = mst_typologies.id
				 order by chid"; 

$rslt = mysql_query($sql);


$sql2  = "select chid,forder from mst_user_fav where user_id = " . $_SESSION['seas_user_id'] . " order by forder";
$rslt2 = mysql_query($sql2);
$favlist = array();
if(mysql_num_rows($rslt2) >0) {
	while($rw2=mysql_fetch_assoc($rslt2)) {
		$favlist[$rw2['forder']] = $rw2['chid'];
	}
	mysql_free_result($rslt2);
}


while($rw=mysql_fetch_assoc($rslt)) {
	$forder = array_search($rw['chid'], $favlist);
	if($forder<=0) $forder =99999;
	$rw['forder'] = $forder;
	$chlist[] = $rw;
}

$chlist_data = array();
foreach ($chlist as $data_lst) {    
	$chlist_data[] = $data_lst['forder'];
}

array_multisort($chlist_data, SORT_ASC, $chlist);


mysql_free_result($rslt);

?>