<?
$kon=mysql_query("select * from tb_comp");
while($res=mysql_fetch_assoc($kon))
{
	$t=time();
	$ed=strtotime($res["enddate"]);
	$dd=strtotime($res["deldate"]);

	if($t>$ed && $t<$dd)
	{
		$idk=$res["id"];
		$minvalue=$res["min"];

		$res1=mysql_query("select * from tb_compdata where idk='$idk' and resvalue>='$minvalue' order by resvalue desc limit 3");

		for($place=1;$place<=mysql_num_rows($res1);$place++)
		{
			$row1=mysql_fetch_assoc($res1);

			$iduser=$row1["iduser"];

			if($res["pris".$place."status"]=='0')
			{
				if($res["pris".$place."type"]=='0')
				{
					$prisvalue=$res["pris".$place."value"];
					if($res["lidername"]=='0'){$lidertype='username';}else{$lidertype='wmid';}

					$lidername=$row1["user"];
					$purse=$row1["purse"];

					$res2=mysql_query("select money from tb_users where $lidertype='$lidername'");
					if(mysql_num_rows($res2)>0)
					{
						$res2=mysql_fetch_assoc($res2);
						$money=$res2["money"]+$prisvalue;
						mysql_query("update tb_users set money='$money' where $lidertype='$lidername'");
						mysql_query("update tb_comp set pris".$place."status='1' where id='$idk'");
					}
				}else{
					$prisvalue=$res["pris".$place."value"];
					if($res["lidername"]=='0'){$lidertype='username';}else{$lidertype='wmid';}

					$lidername=$row1["user"];

					$res2=mysql_query("select referals,username from tb_users where $lidertype='$lidername'");
					if(mysql_num_rows($res2)>0)
					{
						$res2=mysql_fetch_assoc($res2);
						$refs=$res2["referals"]+$prisvalue;
						$login=$res2["username"];

						$res2=mysql_query("select * from tb_users where referer='' and username!='$login' order by visits desc limit $prisvalue");
						if(mysql_num_rows($res2)==$prisvalue)
						{
							while($row2=mysql_fetch_assoc($res2))
							{
								mysql_query("update tb_users set referer='$login', buying='4' where id='".$row2["id"]."'");
							}

							mysql_query("update tb_users set referals='$refs' where $lidertype='$lidername'");
							mysql_query("update tb_comp set pris".$place."status='1' where id='$idk'");
						}
					}
				}
			}
		}
	}
}
?>