<?php 
	// We check in which language we will work
	if (isset($_SESSION["DATAGLOBAL"][0]) && !empty($_SESSION["DATAGLOBAL"][0])) $C->LANGUAGE = $_SESSION["DATAGLOBAL"][0];

	$this->load_langfile('inside/dashboard.php');

	// We are here only if you're logged in
	if (!$this->user->is_logged) {
		echo('0: '.$this->lang('dashboard_no_session'));
		die();
	}

	$errored = 0;
	$txterror = '';
	
	$action=0;
	
	if (isset($_POST["todo"]) && $_POST["todo"] != '') $action = $this->db1->e($_POST["todo"]);
	if (!is_numeric($action)) {
		$errored = 1;
		$txterror .= 'Error. ';
		echo('0: '.$caderror);
		die();
	}


	if ($action == 1)	{

		$nameg = $url = $description= '';
		$privacy = 0;
		
		if (isset($_POST["ng"]) && !empty($_POST["ng"])) $nameg = $this->db1->e(htmlspecialchars($_POST["ng"]));
		if (isset($_POST["ug"]) && !empty($_POST["ug"])) $url = $this->db1->e(htmlspecialchars($_POST["ug"]));
		if (isset($_POST["dg"]) && !empty($_POST["dg"])) $description = $this->db1->e(htmlspecialchars($_POST["dg"]));
		if (isset($_POST["pg"])) $privacy = $this->db1->e($_POST["pg"]);
		
		if (empty($nameg)) { $errored = 1; $txterror .= 'Error... '; }
		if (empty($url)) { $errored = 1; $txterror .= 'Error... '; }
		if (!is_numeric($privacy)) { $errored = 1; $txterror .= 'Error... '; }
		
	}

	if ($action == 2)	{

		$namegroup = $description= $cgroup = '';
		$privacy = 0;
		
		if (isset($_POST["ng"]) && !empty($_POST["ng"])) $namegroup = $this->db1->e(htmlspecialchars($_POST["ng"]));
		if (isset($_POST["dg"]) && !empty($_POST["dg"])) $description = $this->db1->e(htmlspecialchars($_POST["dg"]));
		if (isset($_POST["priv"])) $privacy = $this->db1->e($_POST["priv"]);
		if (isset($_POST["cg"]) && !empty($_POST["cg"])) $cgroup = $this->db1->e($_POST["cg"]);
		
		if (empty($cgroup)) { $errored = 1; $txterror .= 'Error... '; }
		if (empty($namegroup)) { $errored = 1; $txterror .= 'Error... '; }
		if (!is_numeric($privacy)) { $errored = 1; $txterror .= 'Error... '; }

	}
	
	if ($action == 3)	{
		$loadedimage = $cgroup = '';
		$didchanges = 0;
		if (isset($_POST["dch"]) && !empty($_POST["dch"])) $didchanges = $this->db1->e($_POST["dch"]);
		if (isset($_POST["limg"]) && !empty($_POST["limg"])) $loadedimage = $this->db1->e($_POST["limg"]);
		if (isset($_POST["cg"]) && !empty($_POST["cg"])) $cgroup = $this->db1->e($_POST["cg"]);
		
		if (empty($cgroup)) { $errored = 1; $txterror .= 'Error... '; }
		if ($didchanges == 0) { $errored = 1; $txterror .= 'Error... '; }
		if (empty($loadedimage)) { $errored = 1; $txterror .= 'Error... '; }
	}

	if ($action == 4 || $action == 5 || $action == 6 || $action == 7) {
		$idgroup = $iduser = 0;
		if (isset($_POST["idg"])) $idgroup = $this->db1->e($_POST["idg"]);
		if (isset($_POST["idu"])) $iduser = $this->db1->e($_POST["idu"]);
		
		if ($idgroup == 0) { $errored = 1; $txterror .= 'Error... '; }
		if ($iduser == 0) { $errored = 1; $txterror .= 'Error... '; }
	}

	if ($errored == 1) {
		echo('0: '.$txterror);
	} else {
		
		if ($action == 1) {	
			if (!validateUsername($url)) {
				echo('0: '.$this->lang('dashboard_groups_error_urlnovalid'));
				return;
			}
			
			// verify that no files with the same name registrant username
			if( file_exists($C->INCPATH.'controllers/'.strtolower($url).'.php') ) {
				$errored = 1;
				$txterror = $this->lang('dashboard_groups_error_urlnovalid');
				echo("0: ".$txterror); die();
			}
			if( file_exists($C->INCPATH.'../'.strtolower($url)) ) {
				$errored = 1;
				$txterror = $this->lang('dashboard_groups_error_urlnovalid');
				echo("0: ".$txterror); die();
			}
	
			$numu = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$url."'");
			if ($numu != 0) {
				echo('0: '.$this->lang('dashboard_groups_error_urlnovalid'));
				return;
			}

			$numu = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$url."'");
			if ($numu != 0) {
				echo('0: '.$this->lang('dashboard_groups_error_urlnovalid'));
				return;
			}

			$numu = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$url."'");
			if ($numu != 0) {
				echo('0: '.$this->lang('dashboard_groups_error_urlnovalid'));
				return;
			}
			
			$code = uniqueCode(11, 1, 'groups', 'code');

			$this->db1->query("INSERT INTO groups SET code='".$code."', idcreator=".$this->user->id.", privacy=".$privacy.", name_group='".$nameg."', url='".$url."', about_group='".$description."', created='".time()."', num_members=1, num_followers=1");
			
			$idgroupn = $this->db1->insert_id();
			
			$this->db1->query("INSERT INTO groups_members SET idgroup=".$idgroupn.", iduser=".$this->user->id.", when_request='".time()."', when_accepted='".time()."', added_by=".$this->user->id.", accepted_by=".$this->user->id.", status=1, is_admin=1");
			
			$this->db1->query("INSERT INTO relations SET leader=".$idgroupn.", subscriber=".$this->user->id.", type_leader=2, rltdate='".time()."'");
			
			$this->db1->query("UPDATE users SET num_groups=num_groups+1 WHERE iduser=".$this->user->id." LIMIT 1");
			
			$txtreturn = 'Ok';
			echo('1: '.$txtreturn);
			return;
		}

		if ($action == 2) {	
			$this->db1->query("UPDATE groups SET privacy=".$privacy.", name_group='".$namegroup."', about_group='".$description."'  WHERE code='".$cgroup."' LIMIT 1");
			$txtreturn = $this->lang('dashboard_groups_update_txt_msgok');
			echo('1: '.$txtreturn);
			return;
		}
		

		if ($action == 3) {	
			if ($didchanges == 1) {
				$ext = explode(".",$loadedimage);
				$finalphoto = $cgroup.'.'.$ext[count($ext)-1];
				
				$this->db1->query("UPDATE groups SET cover_group='".$finalphoto."' WHERE code='".$cgroup."' LIMIT 1");
				
				$raiz = '../';
				$tmppath = $C->FOLDER_TMP;
				$coversfolder = $C->FOLDER_COVERS_GROUPS;
								
				// move photo file
				if (file_exists($raiz.$tmppath.$loadedimage)) {
					
					$thumbnail = new SmartImage($raiz.$tmppath.$loadedimage, true);
					$thumbnail->mycrop($C->widthCover1, $C->heightCover1);
					$thumbnail->saveImage($raiz.$coversfolder.'min1/'.$finalphoto);				
					$thumbnail->close();

					$thumbnail = new SmartImage($raiz.$tmppath.$loadedimage, true);
					$thumbnail->mycrop($C->widthCover2, $C->heightCover2);
					$thumbnail->saveImage($raiz.$coversfolder.'min2/'.$finalphoto);				
					$thumbnail->close();

					$thumbnail = new SmartImage($raiz.$tmppath.$loadedimage, true);
					$thumbnail->mycrop($C->widthCover3, $C->heightCover3);
					$thumbnail->saveImage($raiz.$coversfolder.'min3/'.$finalphoto);				
					$thumbnail->close();
					
					copy($raiz.$tmppath.$loadedimage, '../'.$C->FOLDER_COVERS_GROUPS.$finalphoto);
					
					unlink($raiz.$tmppath.$loadedimage);
			
					$txtreturn = $this->lang('dashboard_groups_update_txt_cover_ok');
					echo("1: ".$txtreturn);
					return;
				} else {
					$txtreturn=$this->lang('dashboard_groups_update_txt_cover_noupdate');
					echo("0: ".$txtreturn);
					return;
				}		
			} else {
				$txtreturn = $this->leng('dashboard_groups_update_txt_cover_msg4');
				echo("0: ".$txtreturn);
				return;
			}
		}
		
		if ($action == 4) {	
		
			$countReg = $this->db2->fetch_field('SELECT count(id) FROM groups_members WHERE iduser='.$iduser.' AND idgroup='.$idgroup.' AND status=0');
			if ($countReg>0) {
				// membership
	
				$this->db2->query('UPDATE groups_members SET accepted_by='.$this->user->id.', when_accepted="'.time().'", status=1 WHERE iduser='.$iduser.' AND idgroup='.$idgroup);
	
				$this->db2->query("DELETE FROM notifications WHERE notif_type=10 AND notif_object_type=4 AND to_user_id=".$this->user->id." AND from_user_id=".$iduser." AND notif_object_id=".$idgroup);
				$numdeleted = $this->db2->affected_rows();
				if ($numdeleted > $this->user->info->num_notifications) $numdeleted = $this->user->info->num_notifications;
				$this->db2->query('UPDATE users SET num_notifications=num_notifications-'.$numdeleted.' WHERE iduser="'.$this->user->id.'" LIMIT 1');
				
				$this->db2->query('UPDATE groups SET num_members=num_members+1, num_followers=num_followers+1 WHERE idgroup='.$idgroup.' LIMIT 1');
	
				$this->db2->query("INSERT INTO notifications SET notif_type=11, notif_object_type=4, to_user_id=".$iduser.", notif_object_id=".$idgroup.", from_user_id=".$idgroup.", date='".time()."'");				
	
				$this->db2->query('UPDATE users SET num_notifications=num_notifications+1 WHERE iduser="'.$iduser.'" LIMIT 1');
	
				//Following
				$this->db2->query('INSERT INTO relations SET type_leader=2, subscriber='.$iduser.', leader='.$idgroup.', rltdate="'.time().'"');
				
				$txtreturn = 'Ok';
				echo('1: '.$txtreturn);
			} else {
				$txtreturn = $this->lang('dashboard_no_request');
				echo('0: '.$txtreturn);	
			}
			return;
		}


		if ($action == 5) {	
		
			$countReg = $this->db2->fetch_field('SELECT count(id) FROM groups_members WHERE iduser='.$iduser.' AND idgroup='.$idgroup.' AND status=0');
			if ($countReg>0) {

				$this->db2->query('DELETE FROM groups_members WHERE iduser='.$iduser.' AND idgroup='.$idgroup);
								
				$this->db2->query("DELETE FROM notifications WHERE notif_type=10 AND notif_object_type=4 AND notif_object_id=".$idgroup." AND to_user_id=".$this->user->id." AND from_user_id=".$iduser);
				$numdeleted = $this->db2->affected_rows();
				if ($numdeleted > $this->user->info->num_notifications) $numdeleted = $this->user->info->num_notifications;
				$this->db2->query('UPDATE users SET num_notifications=num_notifications-'.$numdeleted.' WHERE iduser="'.$this->user->id.'" LIMIT 1');

				$txtreturn = 'Ok';
				echo('1: '.$txtreturn);
			} else {
				$txtreturn = $this->lang('dashboard_no_request');
				echo('0: '.$txtreturn);	
			}
			return;
			
		}

		if ($action == 6) {	
		
			$numReg = $this->db1->fetch_field('SELECT count(id) FROM groups_members WHERE status=1 AND iduser='.$iduser.' AND idgroup='.$idgroup);
			if ($numReg == 0) {
				$txtreturn = $this->lang('dashboard_no_request');
				echo('0: '.$txtreturn);	
			} else {
				$this->db2->query('DELETE FROM groups_members WHERE status=1 AND iduser='.$iduser.' AND idgroup='.$idgroup.' LIMIT 1');

				$hayNotif = $this->db2->fetch_field('SELECT count(idnotification) FROM notifications WHERE notif_type=12 AND notif_object_type=4 AND notif_object_id='.$idgroup.' AND to_user_id='.$iduser);
				
				if ($hayNotif > 0) {
					$this->db2->query("DELETE FROM notifications WHERE notif_type=12 AND notif_object_type=4 AND to_user_id=".$iduser.' AND notif_object_id='.$idgroup);
					$numdeleted = $this->db2->affected_rows();
					$numnotific = $this->network->getNumNotifications($iduser);
					if ($numdeleted > $numnotific) $numdeleted = $numnotific;
					$this->db2->query('UPDATE users SET num_notifications=num_notifications-'.$numdeleted.' WHERE iduser="'.$iduser.'" LIMIT 1');
					
				} else {
					$this->db2->query("DELETE FROM notifications WHERE notif_type=11 AND notif_object_type=4 AND to_user_id=".$iduser." AND from_user_id=".$idgroup);
					$numdeleted = $this->db2->affected_rows();
					$numnotific = $this->network->getNumNotifications($iduser);
					if ($numdeleted > $numnotific) $numdeleted = $numnotific;
					$this->db2->query('UPDATE users SET num_notifications=num_notifications-'.$numdeleted.' WHERE iduser="'.$iduser.'" LIMIT 1');
					
				}				

				$this->db2->query('UPDATE groups SET num_members=num_members-1 WHERE idgroup='.$idgroup.' LIMIT 1');
				
				$this->db2->query('DELETE FROM relations WHERE subscriber='.$iduser.' AND type_leader=2 AND leader='.$idgroup);
				if ($this->db2->affected_rows()>0) $this->db2->query('UPDATE groups SET num_followers=num_followers-1 WHERE idgroup='.$idgroup.' LIMIT 1');

				$txtreturn = 'Ok';
				echo('1: '.$txtreturn);
			}
			return;
		}
		
		
		if ($action == 7) {	

			$countReg = $this->db2->fetch_field('SELECT count(id) FROM groups_members WHERE iduser='.$iduser.' AND idgroup='.$idgroup);
			if ($countReg == 0) {
				// membership
	
				$this->db2->query('INSERT INTO groups_members SET added_by='.$this->user->id.', accepted_by='.$this->user->id.', when_request="'.time().'", when_accepted="'.time().'", status=1, iduser='.$iduser.', idgroup='.$idgroup);
				
				$this->db2->query('UPDATE groups SET num_members=num_members+1, num_followers=num_followers+1 WHERE idgroup='.$idgroup.' LIMIT 1');
	
				$this->db2->query("INSERT INTO notifications SET notif_type=12, notif_object_type=4, to_user_id=".$iduser.", notif_object_id=".$idgroup.", from_user_id=".$this->user->id.", date='".time()."'");				
	
				$this->db2->query('UPDATE users SET num_notifications=num_notifications+1 WHERE iduser="'.$iduser.'" LIMIT 1');
	
				//Following
				$this->db2->query('INSERT INTO relations SET type_leader=2, subscriber='.$iduser.', leader='.$idgroup.', rltdate="'.time().'"');
	
				$txtreturn = 'Ok';
				echo('1: '.$txtreturn);
			} else {
				$txtreturn = $this->lang('dashboard_no_request');
				echo('0: '.$txtreturn);	
			}
			
			return;
		}

	
	}
?>