<?php

	$actions = array('inbox', 'outbox', 'form', 'add', 'delete_inbox', 'delete_outbox', 'sprava', 'contact_add_form', 'add_contact');
	$types = array('inbox', 'outbox');
	
	(key_exists('action', $_GET) && in_array($_GET['action'], $actions)) ? $action = $_GET['action'] : $action = 'inbox';
	(key_exists('i', $_GET) && $_GET['i']>0) ? $i = (int)$_GET['i'] : $i = 1;
	(key_exists('id', $_GET) && $_GET['id']>0) ? $id = (int)$_GET['id'] : $id = 0;
	(key_exists('type', $_GET) && in_array($_GET['type'], $types)) ? $type = $_GET['type'] : $type = '';
	
	if(session_is_registered('mobile_logged_in') && session_is_registered('mobile_page_posta') && $_SESSION['mobile_page_posta']!=0)
	{
		$nastranu = $_SESSION['mobile_page_posta'];
	}
	else
	{
		$nastranu = 5;
	}
	
	if($action == 'delete_inbox' && $id>0)
	{
		$query = "UPDATE mobile_posta SET visible_rec=0, precitana=1 WHERE ID=$id limit 1";
		$dba->ExecuteQuery($query);
		$query = "DELETE FROM mobile_posta WHERE visible_rec=0 AND visible_sender=0";
		$dba->ExecuteQuery($query);
		$action = 'inbox';
	}
	
	if($action == 'delete_outbox' && $id>0)
	{
		$query = "UPDATE mobile_posta SET visible_sender=0, precitana=1 WHERE ID=$id limit 1";
		$dba->ExecuteQuery($query);
		$query = "DELETE FROM mobile_posta WHERE visible_rec=0 AND visible_sender=0";
		$dba->ExecuteQuery($query);
		$action = 'outbox';
	}
	
	switch ($action):
		case 'inbox': $nadpis = 'prijatá pošta'; break;
		case 'outbox': $nadpis = 'odoslaná pošta'; break;
		case 'form': $nadpis = 'písanie správy'; break;
		default: $nadpis = 'pošta';
	endswitch;

?>
	<script language="javascript">
	function AddSmile(s)
	{
	   document.forms.frm.sprava.value += ' ' + s + ' ';
	   document.forms.frm.sprava.focus();
   	}
	
	function DeleteConfirm(link)
	{
		if (confirm('Naozaj chcete zmazať túto správu?')) window.location = link;
	}
	</script>
    <div id="register_form01">
	  <div id="menu01_head">:: <?php echo $nadpis; ?></div>
	  <div id="melodie_01">
	    <?php 
	    	$navi_actions = array('inbox', 'outbox');
	    	
	    	// ***************** INBOX ********************
	    	if($action == 'inbox' && session_is_registered('my_id'))
			{
				$query = "SELECT ID FROM mobile_posta WHERE user_to=".$_SESSION['my_id']." AND visible_rec=1";
				$chunk = $dba->GetLimit($query);
				$lim = $chunk[0];
				$stranok = $chunk[2];
				
				if(in_array($action, $navi_actions)) fnNavi($i, $stranok, "module=posta&amp;action=$action");
				
				$final_query = "SELECT mobile_posta.*, 
									   mobile_users.login as user 
									   FROM mobile_posta, mobile_users 
									   WHERE user_to=".$_SESSION['my_id']." AND 
									   visible_rec=1 AND 
									   mobile_users.ID=mobile_posta.user_from 
									   ORDER BY ID DESC
									   limit $lim, $nastranu";
				
				$result = $dba->GetResult($final_query);
				$sprav = mysql_num_rows($result);
				if($sprav == 0) echo 'Nemáte žiadne prijaté správy!';
				while($row = mysql_fetch_array($result))
				{
					$message_link = "... <a href=\"index.php?module=posta&amp;action=sprava&amp;type=inbox&amp;id=".$row['ID']."\" id=\"posta_link\"><b>čítaj správu</b></a>";
					echo "<div id=\"melodia_div\">";
					echo "<span id=\"red\">".$row['predmet']."</span> od <b>".$row['user']."</b> | odoslaná ".$row['cas'];
					$znakov = 50;
					if(strlen($row['text']) > $znakov)
					{
						$uvod = substr($row['text'],0,$znakov);
						for($jz=0;$jz<$znakov;$jz++)
						{
							if($uvod[$jz]==' ') $l = $jz;
						}
						$uvod = substr($uvod,0,$l);
						$uvod = fnSmile($uvod);
						$uvod .= $message_link;
					}
					else
					{ 
						$uvod = $row['text'];
						$uvod = fnSmile($uvod);
						$uvod .= $message_link;
					}
					if($row['precitana']==0) echo " <span id=\"red\"><b>NEPREČÍTANÁ!</b></span>";
					echo "<br />".$uvod;
					$predmet = (substr($row['predmet'], 0, 3) == 'RE:') ? $row['predmet'] : 'RE: '.$row['predmet'];
					echo "<br /><a href=\"index.php?module=posta&amp;action=form&amp;komu=".$row['user']."&amp;predmet=$predmet\" id=\"posta_link\">odpovedať</a> | <a href=\"javascript: DeleteConfirm('index.php?module=posta&amp;action=delete_inbox&amp;id=".$row['ID']."')\" id=\"posta_link\">zmazať</a>";
					echo "</div>";
				}
				if(in_array($action, $navi_actions)) fnNavi($i, $stranok, "module=posta&amp;action=$action");
			}
			
			// ***************** OUTBOX ********************
			if($action == 'outbox' && session_is_registered('my_id'))
			{
				$query = "SELECT ID FROM mobile_posta WHERE user_from=".$_SESSION['my_id']." AND visible_sender=1";
				$chunk = $dba->GetLimit($query);
				$lim = $chunk[0];
				$stranok = $chunk[2];
				
				if(in_array($action, $navi_actions)) fnNavi($i, $stranok, "module=posta&amp;action=$action");
				
				$final_query = "SELECT mobile_posta.*, 
									   mobile_users.login as user 
									   FROM mobile_posta, mobile_users 
									   WHERE user_from=".$_SESSION['my_id']." AND 
									   visible_sender=1 AND 
									   mobile_users.ID=mobile_posta.user_to
									   ORDER BY ID DESC
									   limit $lim, $nastranu";
				
				$result = $dba->GetResult($final_query);
				$sprav = mysql_num_rows($result);
				if($sprav == 0) echo 'Neodoslali ste žiadne správy!';
				while($row = mysql_fetch_array($result))
				{
					$message_link = "... <a href=\"index.php?module=posta&amp;action=sprava&amp;type=outbox&amp;id=".$row['ID']."\" id=\"posta_link\"><b>čítaj správu</b></a>";
					echo "<div id=\"melodia_div\">";
					echo "<span id=\"red\">".$row['predmet']."</span> komu: <b>".$row['user']."</b> | odoslaná ".$row['cas'];
					$znakov = 50;
					if(strlen($row['text']) > $znakov)
					{
						$uvod = substr($row['text'],0,$znakov);
						for($jz=0;$jz<$znakov;$jz++)
						{
							if($uvod[$jz]==' ') $l = $jz;
						}
						$uvod = substr($uvod,0,$l);
						$uvod = fnSmile($uvod);
						$uvod .= $message_link;
					}
					else
					{ 
						$uvod = $row['text'];
						$uvod = fnSmile($uvod);
						$uvod .= $message_link;
					}
					echo "<br />".$uvod;
					echo "<br /><a href=\"javascript: DeleteConfirm('index.php?module=posta&amp;action=delete_outbox&amp;id=".$row['ID']."')\" id=\"posta_link\">zmazať</a>";
					echo "</div>";
				}
				if(in_array($action, $navi_actions)) fnNavi($i, $stranok, "module=posta&amp;action=$action");
			}
			
			if($action == 'sprava' && $id>0 && $type!='')
			{
				if($type == 'inbox') 
				{
					$as = 'user_from'; $af = 'od';
					$xch = 'user_to';
				}
				if($type == 'outbox') 
				{ 
					$as = 'user_to'; $af = 'komu:';
					$xch = 'user_from';
				}
				echo "<div id=\"melodia_div\">";
				$query = "SELECT 
						  mobile_posta.ID,
						  mobile_posta.user_from, 
						  mobile_posta.user_to, 
						  mobile_posta.text, 
						  mobile_posta.predmet, 
						  mobile_posta.cas,
						  mobile_users.login as user
						  FROM mobile_posta, mobile_users 
						  WHERE 
						  mobile_users.ID=mobile_posta.$as
						  AND mobile_posta.$xch = '".$_SESSION['my_id']."'
						  AND mobile_posta.ID='$id' limit 0, 1";
//				dump($query);
				$result = $dba->GetResult($query);
				if($result)
				{
					$row = mysql_fetch_array($result);
					$text = fnSmile(fnSmileys(stripslashes($row['text'])));
					echo '<b>'.$row['predmet'].'</b> | '.$af." <span id=\"red\"><b>".$row['user']."</b></span> | odoslaná ".$row['cas']."<br /><br />";
					echo $text."<br /><br />";
					$predmet = (substr($row['predmet'], 0, 3) == 'RE:') ? $row['predmet'] : 'RE: '.$row['predmet'];
					if($type == 'inbox') echo "<a href=\"index.php?module=posta&amp;action=form&amp;komu=".$row['user']."&amp;predmet=$predmet\" id=\"posta_link\">odpovedať</a> |";
					echo "<a href=\"javascript: DeleteConfirm('index.php?module=posta&amp;action=delete_inbox&amp;id=".$row['ID']."')\" id=\"posta_link\">zmazať</a>";
					echo "</div>";
					if($type == 'inbox')
					{
						$query = "UPDATE mobile_posta SET precitana=1 WHERE ID=$id";
						$dba->ExecuteQuery($query);
					}
				}
			}

			if($action == 'add')
			{
				$add_err = '';
				$komu = (key_exists('komu', $_POST)) ? $_POST['komu'] : '';
				$predmet = (key_exists('predmet', $_POST) && $_POST['predmet']!='') ? $_POST['predmet'] : 'Bez predmetu';
				$sprava = (key_exists('sprava', $_POST) && $_POST['sprava']!='') ? $_POST['sprava'] : '';
				if($komu != '' && $sprava != '')
				{
					$komu = htmlspecialchars(addslashes($komu));
					$predmet = htmlspecialchars(addslashes($predmet));
					$sprava = htmlspecialchars(addslashes($sprava));
					$komu_id = $dba->GetOne2('mobile_users', 'ID', 'login', $komu);
					if($komu_id!=0)
					{
						$query = "INSERT INTO mobile_posta (predmet, text, user_from, user_to, cas) values ('$predmet', '$sprava', ".$_SESSION['my_id'].", ".$komu_id.", NOW())";
						$dba->ExecuteQuery($query);
						$add_err = 'Správa bola úspešne odoslaná!';
					}
					else 
					{
						$add_err = 'Zadaný príjemca neexistuje!';
						$action = 'form';
					}
				}
				else 
				{
					$add_err = 'Nevyplnili ste príjemncu alebo text správy';
					$action = 'form';
				}
			}
			
			if(isset($add_err)) echo '<span id=\"red\"><b>'.$add_err.'</b></span>';
			
			if($action == 'add_contact')
			{
				$contact = (isset($_POST['kontakt']) && trim($_POST['kontakt']) != '') ? $_POST['kontakt'] : '';
				if($contact != '')
				{
					$kontakt_id = $dba->GetOne2('mobile_users', 'ID', 'login', $contact);
					if($kontakt_id != 0)
					{
						$query = "SELECT * FROM mobile_address_book WHERE user_ID = '".$_SESSION['my_id']."' AND contact_ID = '$kontakt_id'";
						$exists_check = $dba->GetNums($query);
						if($exists_check == 0)
						{
							$query = "INSERT INTO mobile_address_book (user_ID, contact_ID) VALUES (".$_SESSION['my_id'].", $kontakt_id)";
							$check = $dba->ExecuteQuery($query);
							if($check)
							{
								$add_err = 'Kontakt pridaný!';
								$action = 'form';
							}
							else 
							{
								$add_err = 'Chyba pri pridávaní kontaktu!';
								$action = 'contact_add_form';
							}
						}
						else 
						{
							$add_err = 'Zadaný kontakt už je vo vašom adresári!';
							$action = 'contact_add_form';
						}
					}
					else 
					{
						$add_err = 'Zadaný kontakt neexistuje!';
						$action = 'contact_add_form';
					}
				}
				else 
				{
					$add_err = 'Zadaný kontakt neexistuje!';
					$action = 'contact_add_form';
				}
				if(isset($add_err)) echo '<span id=\"red\"><b>'.$add_err.'</b></span>';
			}
			
			if($action=='form')
			{
				$komu = (key_exists('komu', $_POST) && $_POST['komu']!='') ? $_POST['komu'] : '';
				$komu = (key_exists('komu', $_GET) && $_GET['komu']!='') ? $_GET['komu'] : '';
				?>
				<table align="center">
				<tr>
					<td><br />
						<form name="frm" action="index.php?module=posta&amp;action=add" method="post">
						<table border="0" cellspacing="0" cellpadding="0" align="center">
						  <tr> 
						    <td width="100" align="right">Komu:</td>
						    <td align="left"> 
						      <input id="form_field01" type="text" name="komu" size="63" maxlength="30" value="<? echo $komu; ?>">
						    </td>
						  </tr>
						   <tr> 
						    <td align="right">Predmet:</td>
						    <td align="left"> 
						      <input id="form_field01" type="text" name="predmet" size="63" maxlength="30" value="<? if(key_exists('predmet', $_POST)) echo $_POST["predmet"]; if(key_exists('predmet', $_GET)) echo $_GET["predmet"]; ?>">
						    </td>
						  </tr>
						  <tr> 
						      <td valign="top" align="right">Správa:</td>
						      <td valign="top" align="left"> 
						        <textarea id="form_field01" rows="10" cols="60" name="sprava"><? if(key_exists('sprava', $_POST)) echo $_POST["sprava"]; ?></textarea><br />
						        <? for($j=1;$j<=20;$j++){echo"<a href=\"javascript:AddSmile('s".$j."')\"><img src=\"images/smile/".$j.".gif\" border=\"0\" align=\"top\"/></a> ";}?> 
						
						    </td>
						  </tr>
						  <tr> 
						    <td></td>
						    <td align="left" valign="top">
						            <input id="form_button01" type="submit" name="Submit" value="Pošli">
						            <input id="form_button01" type="reset" name="reset" value="Reset">
						    </td>
						  </tr>
						</table>
					</td>
					<td valign="top" align="left">
					<script language="javascript" type="text/javascript">
					function AddContact()
					{
						var index = document.forms.frm.address_book.selectedIndex;
						if(index > -1)
						{
							document.forms.frm.komu.value = document.forms.frm.address_book.options[index].value;
						}
				   	}
					</script>
						Adresár: <br />
						<select name='address_book' class='form_field01' id='address_book' size='14' onchange="AddContact();">
						
							<?php
							
								$query = 'SELECT 
											b.login 
										  FROM 
										    mobile_address_book a, 
										    mobile_users b 
										  WHERE
										    a.contact_ID = b.ID AND 
										    a.user_ID = '.$_SESSION['my_id'];
								$array = $dba->GetArray($query);
								if(is_array($array))
								{
									foreach ($array as $a)
									{
										echo "<option value='".$a['login']."'>".$a['login']."</option>";
									}
								}
							echo "</select><br />";
							echo "<a href='index.php?module=posta&amp;action=contact_add_form' id='index_link_01'>Pridaj kontakt</a>";
					?>
					</form>	
					</td>
				</tr>
				</table>
				
				<?php
			}
			
			if($action == 'contact_add_form')
			{
				?>
				
				<form name="frm" action="index.php?module=posta&amp;action=add_contact" method="post">
					<table border="0" cellspacing="0" cellpadding="0" align="center">
					  <tr> 
					    <td width="100" align="right">Meno kontaktu:</td>
					    <td align="left"> 
					      <input id="form_field01" type="text" name="kontakt" size="30" maxlength="30"> 
					      <input id="form_button01" type="submit" name="Submit" value="Pridaj">
					    </td>
					  </tr>
					</table>
				</form>
				
				<?php
			}
			
	    	
			
    	?>
	  </div>
	</div>