<?php

class Welcome extends Controller {



	function Welcome()
	{

		parent::Controller();
		$this->load->helper(array('form', 'url','smsstore_helper'));
	}
	
	function checkavb()
	{	
		$f = $this->uri->segment(3,'username');
		$div = $this->uri->segment(4);
		$val = $this->uri->segment(5,NULL);
		
		$sql = mysql_query("select * from users where $f = '$val'") or die(mysql_error());
		if(mysql_num_rows($sql) && $val)
		{
			if($f=='number')
				{
					echo "<small style=\"color:#FF0000\">&nbsp;&nbsp;&nbsp;&nbsp;Phone already in use</small>";
				}
			else
				{
					
					echo "<small style=\"color:#FF0000\">&nbsp;&nbsp;&nbsp;&nbsp;Not Available</small>";
				}
		}
		else
		{
		
			echo "<small style=\"color:#006600\">&nbsp;&nbsp;&nbsp;&nbsp;Available</small>";
		}
			
	
	}

	

	function index()
	{ 
	 $this->load->Model('Main');
     $data['users'] = $this->Main->GetAllMembers();
	 $this->load->view('mainpage');
	}

	
	
	// Signup //
	function newuser()
	{
	    $iReff = $this->uri->segment(3);
	    $data = array( 
		  'reff_id' =>$iReff,
		 );
    	$this->session->set_userdata($data);
	    $this->load->view('newuser');
	}
	function step2()
	{
	   $data['membertype'] = $this->input->post('membertype');
	   $this->load->view('step2',$data);
	}
	function signup()
	{
	$username = $this->input->post('username');
	$email = $this->input->post('email');
	$membertype = $this->input->post('membertype');
	$affid = $this->input->post('affid');
	$pwd = $this->input->post('password');
    $rpwd = $this->input->post('rpassword');
	$password = $pwd;
	$number = $this->input->post('number');
	$fullname = $this->input->post('fullname');
			
	$bSignup=0;
	
	$passwrong=0;
	if ($password!=$rpwd)
	{
		$passwrong=1;
	}
	if(!empty($email)  && !empty($username) && !empty($password) && !empty($number) && !empty($fullname) && $password==$rpwd)
	{
	
	$sql = mysql_query("select * from users where username = '$username' or number = '$number' ") or die(mysql_error());
	if(!mysql_num_rows($sql))
	{
	
			 $this->load->Model('Main');	 
			 $query = $this->Main->Signup1($username,$membertype,$email,$password,$number,$fullname,$affid);
			
			 if($query == true)
			 {
			 
				$Subject ="Welcome to sounit.com group texting.";
				$body1 = "Thank you for choosing Sounit. <br><br> We look forward to serve for free your group texting needs. <br><br> For your records <br><br> Your Username =  <strong>$username</strong> <br> Your Password = <strong>$pwd</strong>  <br><br> Thank you,<br>  Sounit team";

				$head = "MIME-Version: 1.0\r\n".
				"Content-type: text/html; charset=UTF-8\r\n".
				"From: Sounit.com <admin@Sounit.com>\r\n".
				"Date: ".date("r")."\r\n";	
				$sent=mail($email, $Subject,$body1,$head);	
				 
				mysql_query("insert into wsoftsms_out (recipient, text, create_date) value('1".$number."', 'welcome to www.sounit.com group texting', '".date("Y-m-d")."');") or die(mysql_error());
			
				$this->load->view('home_success1');
				$bSignup=1;
			 }
			 else
			 {
				echo "<script type='text/javascript'>"
						."alert('Error');"
						//."location.href = '".base_url()."'" 
						."</script>";	
			 }
	}
	else
	{
					echo "<script type='text/javascript'>"
						."alert('Error:Username or Number already in use. Please user differnt email address or mobile number.');"
						//."location.href = '".base_url()."'" 
						."</script>";	

	}
	}
	else
	{
		if($passwrong)
		{
		   echo "<script type='text/javascript'>"
				."alert('Fields `Password` and `Retype Password` should coincide.');"
				."</script>";	
		}
		else 
		{
	 	    echo "<script type='text/javascript'>"
				."alert('All fields are required to be completed');"
				."</script>";	
		}
	}
	
    if(!$bSignup)
    {
        $data['membertype'] = $this->input->post('membertype');
	    $this->load->view('newuser',$data);
	}
	

	}
	
	
	//Find Group 
	
	function find_group($id = 0)
	{
	
	//$this->output->enable_profiler(TRUE);
	 //Load Group Model //
	 $this->load->Model('Group');
	 
	 $this->load->library('pagination');
	 
	 $name = $this->input->post('textarea');
	 $query = $this->Group->get_all_groups($name);
	 
	 $data['query'] = $query;

	 
	 //Load View
	 $this->load->view('redirect_login');
	 $this->load->view('header');
	 $this->load->view('find_group',$data);
	 $this->load->view('footer');
	
	
	}
	

    //Login//

	function login()
	{
	
			   $this->load->Model('Main');		 
			   $email = $this->input->post('email');
			   $password = $this->input->post('password');			   
			  // $login =  $this->Main->login($email,$password);
			 // echo "select * from users where username = '$email' and password = '".md5($password)."'";
			  $sql = mysql_query("select * from users where (username = '$email' or email = '$email' or number = '$email'  ) and password = '".md5($password)."'") or die(mysql_error());
			  $row = mysql_fetch_array($sql);
			  if(mysql_num_rows($sql))
			   {
						$data = array( 
						 'id' => $row['id'],
						 'username' => $row['username'],
						 'email' => $row['email'],
						 'logged_in' => TRUE,
						 'photo' => $row['photo']
						 );
 						$this->session->set_userdata($data);
			   			if($row['username'])
				 		  	redirect('welcome/account');
						else
					     	redirect('welcome/settings');
			   }
			  else
			   {
			
				   echo "<script type='text/javascript'>"
							."alert('Please enter correct Username & Password');"
							."location.href = '".base_url().index_page()."'" 
							."</script>";	
						
			   
			   }
	
	}
	
	
 // Groups//
 
 
 
 
 
 
 function joinGroup($id)
	{
	$this->load->Model('Group');
	$userID  = $this->session->userdata('id');
	$query  = $this->Group->Join($id,$this->session->userdata('email'),0);
	//$this->group($id);
	header("location:".base_url()."welcome/group/$id/$userID");
	}
   

 
 
 
  function group($id)
  {
   $data['id'] = $id;
   $userid = $this->uri->segment(4);
   	//Debug
	
	//$this->output->enable_profiler(TRUE);
//Load Main Groups //
	 $this->load->Model('Group');
	 
	 

 if($this->Group->getDetails($id) == TRUE)
 {	
 
 //Check if  user is allocated to the group//
		 if($this->Group->CheckJoin($this->session->userdata('id'),$id) == FALSE)
		 {
		 
				 if($this->Group->CheckIfGroupIsPublic($id,$this->session->userdata('email')) ==  TRUE)
				 //if(TRUE)
				 {
				 
				 
						  $group_name = $this->Group->GroupInfo($id);
						 
						 $data['group_name'] = $group_name;
						 $data['id'] = $id;
						 
						 //if join isset
						 $join = $this->input->post('join');
				
								if(isset($join))
								{
								 
								
								// echo "Auto join";
								 //$query  = $this->Group->Join($id,$this->session->userdata('email'),0);
								 
								
								 
								}
				
				
						  $this->load->view('redirect_login');
						  $this->load->view('header');
						  $this->load->view('group_join',$data);
						  $this->load->view('footer');
				  
				 }
				 else
						 {
						 
				 
						 $group_name = $this->Group->GroupInfo($id);
						 
						 $data['group_name'] = $group_name;
						 $data['id'] = $id;
						 
						 //if join isset
						 $join = $this->input->post('join');
				
				
								if($join)
								{
											 $pending1 = NULL;
											 $sql = mysql_query("select * from members where group_id = '$id' and member_uid = '".$this->session->userdata('id')."'") or die(mysql_error());								
											 if(!mysql_num_rows($sql))
												 {
													  $query  = $this->Group->Join($id,$this->session->userdata('email'),1);
													  $this->load->view('redirect_login');
													  $this->load->view('header');
													  $this->load->view('group_join_pending',$data);
													  $this->load->view('footer');
			
												 }
											 else
												{
													 $r = mysql_fetch_array($sql);
													 $pending1 = $r['pending1'];
													 if($pending1)
														{
														  $this->load->view('redirect_login');
														  $this->load->view('header');
														  $this->load->view('group_join_pending',$data);
														  $this->load->view('footer');
														}
														
												}
								
								 
								}
								else
								{
											  $this->load->view('redirect_login');
											  $this->load->view('header');
											
											 $sql = mysql_query("select * from members where group_id = '$id' and member_uid = '".$this->session->userdata('id')."'") or die(mysql_error());								
											 if(!mysql_num_rows($sql))
												 {											
													  $this->load->view('group_join',$data);
												 }
											 else
											 	{
												 $this->load->view('group_join_pending',$data);
												}
											
											
											  $this->load->view('footer');
								
								
								}
				
				
				  
						 
						 } 
		  
		  
		 }
		 else
		 {
				 $group_name = $this->Group->GroupInfo($id);
				 
				 $data['group_name'] = $group_name;
				 $data['group_id']  = $id;
				 
				 
				 
				$this->session->unset_userdata('group_id');
				$this->session->set_userdata('group_id',$id);
				
				 
				 
				  $this->load->view('redirect_login');
				  $this->load->view('header');
				  $this->load->view('group',$data);
				  $this->load->view('footer');
		 }
 }
 else
 { 
  redirect('error');
 } 
 
  }	
 
 
 
 
 
 
 //Group delete //
 
 function  group_delete()
 {
	 $this->load->Model('Group');
	 $id = $this->session->userdata('group_id');
	 $delete = $this->input->post('delete');
	 $val = $this->input->post('delete');
	 if($val == 'Delete Group')
	 	{
				if(isset($delete))
				{
				 $query  = $this->Group->Destory($id,$this->session->userdata('id'));
				 redirect('welcome/account');
				}
		}

	 else
	 	{
				 redirect("welcome/editgroup/$id/");
		}
		
 }

	function editgroup($id)
	{
		 $data['id'] = $id;
		 $this->load->view('header');
		 $this->load->view('edit_group',$data);
		 $this->load->view('footer');

	}
	
	function edit_group_details()
	{
		$id = $this->input->post('id');
		$type= $this->input->post('type');
		$memberID = $this->session->userdata('id');
		
		
        $config['upload_path'] = './uploads/groups/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']	= '100000';
        $config['max_width']  = '1000';
        $config['max_height']  = '1000';
        
        $this->load->library('upload', $config);
        $sImage='';
        if ( ! $this->upload->do_upload())
		{
		    $error = array('error' => $this->upload->display_errors(),'pic' => $data_array['file_name']);
		}	
		else
		{
            $data_array = $this->upload->data();
            //$this->Main->changePicture($this->session->userdata('id'),$data_array['file_name']);
            $error = array('error' => $this->upload->display_errors(),'pic' => $data_array['file_name']);
        }

        if ($data_array['file_name']!='') {
            $sImage='/uploads/groups/'.$data_array['file_name'];
            $sql = mysql_query("update groups set type = '$type',logo = '$sImage' where id = '$id'") or die(mysql_error());
        }
        else 
        {
       		$sql = mysql_query("update groups set type = '$type' where id = '$id'") or die(mysql_error());
        }
		
		header("location:".base_url()."welcome/group/$id/$memberID");
	
	}

 //Group delete //

 function group_leave()
 {

   	//Debug
	
//	$this->output->enable_profiler(TRUE);
  //Load Main Groups //
	 $this->load->Model('Group');
 //Group ID//
 
 $id = $this->session->userdata('group_id');
 
  //if leave isset
 $leave = $this->input->post('leave');

if(isset($leave))
{
 
 $query  = $this->Group->Leave($id,$this->session->userdata('id'));
 
redirect('welcome/account');
 
}

 
 
 
 }


function approve_member()
{
	$this->load->Model('Group');
	$groupID = $this->uri->segment(3);
	$id1 = $this->uri->segment(4);
	$rs2 = mysql_query(" update members set pending1 = '0' where member_uid='$id1' and group_id = '$groupID' ")or die(mysql_error()); 
	$userID = $this->session->userdata('id');
	header("location:".base_url()."welcome/group/$groupID/$userID/");

}

function declined_member()
{
	$this->load->Model('Group');
	$groupID = $this->uri->segment(3);
	$id1 = $this->uri->segment(4);
	$rs2 = mysql_query(" delete from members where member_uid='$id1' and group_id = '$groupID' ")or die(mysql_error()); 
	$userID = $this->session->userdata('id');
	header("location:".base_url()."welcome/group/$groupID/$userID/");
}

//Group Get Updates//
 function group_get_updates($id)
 {
   //Load Main Groups //
$this->load->Model('Message');
	 
 $data['list_msgs'] = $this->Message->view_group_txt($id);
 
// $this->load->view('header');
 $this->load->view('messages',$data);
// $this->load->view('footer');
 
 }
 
 //Group Get Updates//
 function group_get_more_updates($id)
 {


if(is_numeric($this->uri->segment(5)))
{
  $from  = $this->uri->segment(5);
}
else
{
  $from  =  $this->input->post('lastmsg');
}
    	//Debug
	 $this->load->Model('Message');
	 
 
	 
 $data['list_msgs'] = $this->Message->view_group_txt($id,$from);
 
// $this->load->view('header');
 $this->load->view('more_updates',$data);
// $this->load->view('footer');
 
 }
 
   //Group update //
  
  function group_update()
  {
	$this->load->Model('Main');	 
	$this->load->Model('Message');	 
	$txt =  $this->input->post('update');
	$group_id = $this->input->post('group_id');
	$userID = $this->session->userdata('id');
	
	$sql = mysql_query("select * from users where id = '$userID'") or die(mysql_error());
	$row = mysql_fetch_array($sql);
	$number = $row['number'];
	$lastMsg = $row['lastMsg'];
	$time = time();
	$diff = time() - $lastMsg;
	if($diff >= 120)
		{
		     if($this->Main->check_send_sms_limit())
    	     {
    		      $sql = mysql_query("update users set lastMsg = '$time'  where id = '$userID'") or die(mysql_error());
                    /*	$newSql = "insert into wsoftsms_out (recipient, text, create_date) value";
                    	$recp = 0;
                    	$sql = mysql_query("select U.username as Username, U.id as userID,number as Phno from members as M, users as U where U.id = M.member_uid and M.group_id = '$group_id' and pending1 = 0") or die(mysql_error());
                    	while($row = mysql_fetch_array($sql))
                    		{
                    			if($row['userID'] != $userID)
                    				{
                    					 $recp ++;
                    					
                    					 $Phno = "1".$row['Phno'];
                    					 $newSql .= " ('$Phno', '$txt', '".date("Y-m-d H:i:s")."') , ";
                    				}
                    		}
                    		
                    		$newSql =  trim($newSql," , ");
                    		$newSql .= ";";
                    		if($recp)
                    			{
                    					$dbhost = '67.174.149.93:3306';
                    					$dbuser = 'wsoftsms';
                    					$dbpass = '9g5zac9rse';
                    					$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
                    					$dbname = 'wsoftsmsdb';
                    					mysql_select_db($dbname);			
                    					$sql = mysql_query($newSql) or die(mysql_error());	
                    					mysql_close($conn);
                    			
                    			}*/
	
                	$url = base_url()."sms/incoming/0/GL$group_id%23".urlencode($txt)."/$number/";
                	$f = fopen ("$url", "r");

                	//$msg_update =  $this->Message->post($this->session->userdata('id'),$group_id,$txt);
	                 $msg_update = 1;
                	if($msg_update == TRUE)
                	{
                	echo "Posted";
                	}
                	else
                	{
                	echo"Cannot post update";
                	}
    	      }
    	      else 
    	      {
    	          echo 'Please upgrade you account if you want send more SMS.';
                  exit();
    	      }
	
	}
  else
  	{
		$x = 120 - $diff;
		echo "Please wait for $x seconds before posting your next message";
	
	}
  
  }  
 
  //Account//	
	
function isOwner($uID,$gID)
	{
	
		$sql = mysql_query("select * from groups where id = '$gID' and owner_uid = '$uID'") or die(mysql_error());
		if(mysql_num_rows($sql))
			return true;
		else
			return false;
	}
	
function getsendsmscount()
{
    $userID = $this->session->userdata('id');
    if ($userID) 
    {
         $d=01;
         $mnth = date('m');
         $yr = date('Y');
         $dt = strtotime($d.'-'.$mnth.'-'.$yr);

         $sqlConf = mysql_query("SELECT count(*) as cnt FROM messages WHERE for_user_id!=0 AND time_stamp>$dt AND member_uid='$userID'") or die(mysql_error());
         $aSMSCount=mysql_fetch_array($sqlConf,MYSQL_ASSOC);
    	 echo $aSMSCount['cnt'];
    }

}

function sendprivatemsg()
{
      $userID = $this->session->userdata('id');
      $iForUser = $this->uri->segment(3);
      $this->load->Model('Message');
      $this->load->Model('Main');
      
      if($this->input->post('foruser_id'))
      {
        $iForUser =$this->input->post('foruser_id');
      }
      
      $data['foruser_id']=$iForUser;
      $sql = mysql_query("SELECT id FROM members WHERE member_uid='$iForUser' AND group_id IN (select id from groups where owner_uid = '$userID')") or die(mysql_error());
	  if(mysql_num_rows($sql))
	  {
	      if($this->input->post('foruser_id') && $this->input->post('msg')!='')
          {
            if($this->Main->check_send_sms_limit())
    	      {
    	        
                $text=mysql_real_escape_string($this->input->post('msg'));
                $sql = mysql_query("INSERT INTO `messages` (`id`,`txt`,`member_uid`,`for_user_id`,`group_id`,`time_stamp`) VALUES (NULL,'".$text."','$userID','$iForUser','0','".time()."');") or die(mysql_error());
                
                echo 'User get message in next few minuts.';
                exit();
              }
              else 
              {
                  echo 'Please upgrade you account if you want send more SMS.';
                  exit();
              }
          }
	      
          $sql = mysql_query("SELECT * FROM `messages` WHERE member_uid='$userID' AND for_user_id='$iForUser' ORDER BY `time_stamp` DESC") or die(mysql_error());
          while ($row=mysql_fetch_array($sql,MYSQL_ASSOC))
          {
            $aMessHistory[]=$row;    
          }
	      
          //print_r($aMessHistory); exit();
	      $data['aMessHistory']=$aMessHistory;
          $this->load->view('header');
          $this->load->view('sendprivate',$data);
          $this->load->view('footer');
	  }
	  else 
	  {
	   die('You cant sent messag for this user');   
	  }
}

function account()
	{
             $userID = $this->session->userdata('id');
        	 $this->load->Model('Group');
             $this->load->Model('Message');
        	 
             /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
                     $gid=$this->Group->getMyDefGroup($userID);        
                     $data['id'] = $gid;

                     if($gid && $this->Group->getDetails($gid) == TRUE)
                     {	
        				 $group_name = $this->Group->GroupInfo($gid);
        				 $data['group_name'] = $group_name;
        				 $data['group_id']  = $gid;
        				 
        				$this->session->unset_userdata('group_id');
        				$this->session->set_userdata('group_id',$gid);
        				//$this->load->view('group',$data);
                     }
             
             /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
             
             $groups = $this->Group->JoinedList($this->session->userdata('id'));
        
        
             if($groups == FALSE)
             {
             $id[] = "";
              $html = $id; 
             }
             else
             {
            
             foreach($groups->result() as $row)
             {
             
            //print_r($row);exit();
               if($this->isOwner($userID,$row->group_id))
               {
                    $id[] = "<a href=".base_url().index_page()."/welcome/group/".$row->group_id."  style=\"text-decoration:none;\">". "<li>".$this->Group->GroupInfo($row->group_id)." &nbsp;<font color=\"#999999\" style=\"font-style:italic\">[Owner]</font></a> <a href=".base_url().index_page()."/welcome/setdefgroup/".$row->group_id."  style=\"text-decoration:none;\">Set as Default</a><li>";
               }
               
              else if($row->pending1)
            	   $id[] = "<a href=".base_url().index_page()."/welcome/group/".$row->group_id."  style=\"text-decoration:none;\">". "<li>".$this->Group->GroupInfo($row->group_id)." &nbsp;<font color=\"#999999\" style=\"font-style:italic\">[Pending]</font></a><li>";
              
              else
            	   $id[] = "<a href=".base_url().index_page()."/welcome/group/".$row->group_id." style=\"text-decoration:none;\">". "<li>".$this->Group->GroupInfo($row->group_id)."</a><li>";
               
               
               $html = $id;
               $group_ids[] = $row->group_id;
             }
            
            
            
             }
            	if(empty($group_ids))
            	{
            	$group_ids[] = 0;
            	}
            	
            	 $data['list_msgs'] = $this->Message->view_user_all_groups_txt($group_ids);
            	 $data['html'] = $html ;
        	 
        	    //$this->load->view('redirect_login');
        		$this->load->view('header');
        		$this->load->view('account',$data);
        		$this->load->view('footer');
	
}
	function setdefgroup()
	{
	    $iUser=$this->session->userdata('id');
	    $iGroup = (int)$this->uri->segment(3);
	    mysql_query("UPDATE `groups` SET is_def=0 WHERE owner_uid='$iUser'") or die(mysql_error());
	    mysql_query("UPDATE `groups` SET is_def=1 WHERE id='$iGroup' AND owner_uid='$iUser'") or die(mysql_error());
	    header('Location:'.base_url().'welcome/account');
	}
	//This update account all groups //
	
	function get_all_msgs()
	{
	
	 //Group Get Updates//


if(is_numeric($this->uri->segment(5)))
{
  $from  = $this->uri->segment(5);
}
else
{
  $from  =  $this->input->post('lastmsg');
}	//Debug
	
//	$this->output->enable_profiler(TRUE);
	
//Load Main Groups //
	 $this->load->Model('Group');
//Load Message Groups//
     $this->load->Model('Message');

//Get Group JoinedList //

 $groups = $this->Group->JoinedList($this->session->userdata('id'));
 if($groups == FALSE)
 {
	  $id[] = "";
	  $html = $id; 
 }
 else
 {
	 foreach($groups->result() as $row)
	 {
	  $group_ids[] = $row->group_id;
	 }
 }
 
 if(empty($group_ids))
 {
	$group_ids[] = 0;
 }
	 	 $data['list_msgs'] = $this->Message->view_user_all_groups_txt($group_ids,$from);
	
        $this->load->view('redirect_login');
		$this->load->view('get_all_msgs',$data);

	

	
	}
	
	
	
	
	
	//This update account all groups //
	
	function get_all_more_msgs()
	{
	
	
	
	 //Group Get Updates//


if(is_numeric($this->uri->segment(5)))
{
  $from  = $this->uri->segment(5);
}
else
{
  $from  =  $this->input->post('lastmsg');
}	
	//Debug
	
//	$this->output->enable_profiler(TRUE);
	
//Load Main Groups //
	 $this->load->Model('Group');
//Load Message Groups//
     $this->load->Model('Message');

//Get Group JoinedList //

$groups = $this->Group->JoinedList($this->session->userdata('id'));

 if($groups == FALSE)
 {
 $id[] = "";
  $html = $id; 
 }
 else
 {
 foreach($groups->result() as $row)
 {
  $group_ids[] = $row->group_id;
 }



 }
	
	 $data['list_msgs'] = $this->Message->view_user_all_groups_txt($group_ids,$from);
	 
        
		$this->load->view('get_all_more_msgs',$data);

	

	
	}
	

	

	
  //Logout //
    function logout()
	{
	
	 $data = array( 
	 'id' => '',
	 'username' =>'',
	 'email' => '',
	 'logged_in' =>false,
	 'photo' => ''
	 );
	 
	 $this->session->set_userdata($data);
		
	redirect('welcome');
	
	}
 
 //Settings //
    function settings()
	{
	
		$error=array();
		$this->load->Model('Main');
	 
      	$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '100000';
		$config['max_width']  = '1000';
		$config['max_height']  = '1000';
		
		$this->load->library('upload', $config);
		$pic =  $this->session->userdata('photo');
		    
			$this->load->model('gmodel');
			if($this->input->post('pass'))
				$d['password'] = md5($this->input->post('pass'));
				
			if($this->input->post('username'))
				{
					$this->load->model('zll');
					if(!$this->zll->check_dup_username($this->input->post('username')))
						{
							$d['username'] = $this->input->post('username');
						}
					else
						{
		  							 $error = array('error' => "Username already exists please choose another.");
									 echo "";
						}
				}
			
				if($this->input->post('email'))
				{
					$this->load->model('zll');
					if(!$this->zll->check_dup_email($this->input->post('email'),$this->session->userdata('id')))
						{
							$d['email'] = $this->input->post('email');
						}
					else
						{
		  					$error[] = "Email already exists please choose another.";
							echo "";
						}
				}
			
				if($this->input->post('number'))
				{
					$this->load->model('zll');
					if(!$this->zll->check_dup_number($this->input->post('number'),$this->session->userdata('id')))
						{
							$d['number'] = $this->input->post('number');
						}
					else
						{
		  					 $error[] = "Number already exists please choose another.";
							 echo "";
						}
				}
			$w['id'] = $this->session->userdata('id');

			if(!count($error) && isset($d))
			{
				$update = $this->gmodel->gUpdate('users',$w,$d); 	
			}
		
		if ( ! $this->upload->do_upload())
		{
			$this->load->view('redirect_login');
			$this->load->view('header');
	        $this->load->view('settings', array('error'=>$error,'pic'=>$pic));
			$this->load->view('footer');
		}	
		else
		{
            $data_array = $this->upload->data();
            $this->session->unset_userdata('photo');
            $this->session->set_userdata('photo',$data_array['file_name']);
            $this->Main->changePicture($this->session->userdata('id'),$data_array['file_name']);
            $error = array('error' => $this->upload->display_errors(),'pic' => $data_array['file_name']);
            $this->load->view('redirect_login'); 
            $this->load->view('header');
            $this->load->view('upload_success');
            $this->load->view('settings',$error);
            $this->load->view('footer');
		}
		
	}
	
	
 // Create Group //
 
    function create_group()
	{
		$this->load->Model('Group');
		
		$data['bCanCreateGroup']=$this->Group->canCreateGroup();
		
		$this->load->library('form_validation');
        $config = array(
               array(
                     'field'   => 'name', 
                     'label'   => 'Group Name', 
                     'rules'   => 'required'
                  ),
               array(
                     'field'   => 'type', 
                     'label'   => 'Group Type', 
                     'rules'   => 'required'
                  )
            );

        $this->form_validation->set_rules($config);
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('redirect_login');	
			$this->load->view('header');
			$this->load->view('create_group',$data);
			$this->load->view('footer');
		}
		else
		{
		    
		
		
			$gname = $this->input->post('name');
			$sql = mysql_query("select * from groups where name = '$gname'") or die(mysql_error());
			if(mysql_num_rows($sql))
			{
    			$this->load->view('redirect_login');
    			$this->load->view('header');
    			$this->load->view('group_error');
    			$this->load->view('create_group',$data);
    			$this->load->view('footer');
			}
			else
			{
                $config['upload_path'] = './uploads/groups/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']	= '100000';
                $config['max_width']  = '1000';
                $config['max_height']  = '1000';
                
                $this->load->library('upload', $config);
                $sImage='';
                if ( ! $this->upload->do_upload())
        		{
        		    $error = array('error' => $this->upload->display_errors(),'pic' => $data_array['file_name']);
        		}	
        		else
        		{
                    $data_array = $this->upload->data();
                    //$this->Main->changePicture($this->session->userdata('id'),$data_array['file_name']);
                    $error = array('error' => $this->upload->display_errors(),'pic' => $data_array['file_name']);
                }
    
                if ($data_array['file_name']!='') {
                    $sImage='/uploads/groups/'.$data_array['file_name'];
                }
    			$this->Group->Create($this->input->post('name'),$this->input->post('type'),$this->session->userdata('id'),$sImage);	
    			$data['bCanCreateGroup']=$this->Group->canCreateGroup();
    			$this->load->view('redirect_login');
    			$this->load->view('header');
    			$this->load->view('group_success');
    			$this->load->view('create_group',$data);
    			$this->load->view('footer');
			}
		}
	}


	function user_availability()
	{

	$username = $this->input->post('username');
	
	 $query= $this->db->get_where('users',array('username'=>$username));
	 
	 if($query->num_rows() > 0) 
	 {
	 echo "no";
	 }
	 else
	 {
	 echo"yes";
	 }
	 
	}
	
//Email availability	
	
	function email_availability()
	{
	$email = $this->input->post('email');
	 $query= $this->db->get_where('users',array('email'=> $email));
	 
	 if($query->num_rows() > 0) 
	 {
	 echo "no";
	 }
	 else
	 {
	 echo"yes";
	 }
	  
	}
	
//----------------- forgot password
	function forgot_password()
	{
		$data['msg'] = '';
		$data['pagereq'] = 'forgot_password';
		$this->load->view('mainview',$data);
		
	}
	
	function change_password()
	{
	
	$email = $this->input->post('email');
	$mob = $this->input->post('mob');
	
	if($email)
		{
				$sql = mysql_query("select * from users where email = '$email'") or die(mysql_error());
				if(mysql_num_rows($sql))
				{
																		$row = mysql_fetch_array($sql);
																		$id = $row['id'];
																		$rand = rand(9000,900000);
						$mdfpass = md5($rand);
						$sql = mysql_query("update users set password = '$mdfpass' where id = '$id'") or die(mysql_error());
				
																		$Subject ="Password Recovery";
																		$body1 = "Hello $row[fullname],<br> Your new password : $rand <br> Thanks ";

																		$head = "MIME-Version: 1.0\r\n".
																		"Content-type: text/html; charset=UTF-8\r\n".
																		"From: sounit.com <admin@sounit.com>\r\n".
																		"Date: ".date("r")."\r\n";	
																		$sent=mail($email, $Subject,$body1,$head);	
			$data['msg'] = 'Your new password has been sent to your email ID.';
		$data['pagereq'] = 'forgot_password';
		$this->load->view('mainview',$data);


				}
			else
				{
				$data['msg'] = 'Not found! <br>Please try again.';
				$data['pagereq'] = 'forgot_password';
				$this->load->view('mainview',$data);
				
				}
		
		
		}
		else
		{
		
					$sql = mysql_query("select * from users where number = '$mob'") or die(mysql_error());
					if(mysql_num_rows($sql))
					{
						$row = mysql_fetch_array($sql);
						$id = $row['id'];
					
						$rand = rand(99999,999999);
						$mdfpass = md5($rand);
						$sql = mysql_query("update users set password = '$mdfpass' where id = '$id'") or die(mysql_error());
							
						//$sql = mysql_query("insert into wsoftsms_out (recipient, text, create_date) value('19163203290', 'Hello justin from smsgateway this is a test with justin ! from my pc', '2010-05-17');") or die(mysql_error());
						
						//=====================================================================SEND MESSEGE 
						include(getcwd()."/ip.php");
						$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
						mysql_select_db($dbname);
						
						$MSG = "Hello $row[username], your new passwork is $rand Thanks";
						
						$sql = mysql_query("insert into wsoftsms_out (recipient, text, create_date) value('$mob', '$MSG', '".date("Y-m-d")."');") or die(mysql_error());
						
						//=====================================================================SEND MESSEGE 
					
						$data['msg'] = ' Your new password has been sent to your mobile.';
						$data['pagereq'] = 'forgot_password';
						$this->load->view('mainview',$data);
					
					}
					else
					{
						$data['msg'] = 'Not found! <br>Please try again.';
						$data['pagereq'] = 'forgot_password';
						$this->load->view('mainview',$data);
					
					}
		
		
		}

	
	
	
	


}
//----------------- end forgot password

//-----------------		static pages
function terms_of_service()
{
	$data['pagereq'] = 'terms_of_service';
	$this->load->view('mainview',$data);
	
}

function privacy_policy()
{
$data['pagereq'] = 'privacy_policy';
	$this->load->view('mainview',$data);
}

function why_grouplingo()
{
$data['pagereq'] = 'why_grouplingo';
	$this->load->view('mainview',$data);
}

function how_it_works()
{
$data['pagereq'] = 'how_it_works';
	$this->load->view('mainview',$data);
}


function contact_us()
{
	$data['msg'] = '';
	$data['pagereq'] = 'contact_us';
	$this->load->view('mainview',$data);
}
function sendRequest()
		{
			// Email send code will go here
				$this->load->model('banana_model');
/*				$tableName='siteconfiguration';
				$ss = $this->banana_model->gSelectStar($tableName);
				foreach($ss as $s)
				{
					$adminmailid=$s['paypalid']; 
				}
				*/
				$adminmailid = "admin@sounit.com";
				$userid=$this->session->userdata('userID');
				$firstname= $this->input->post('firstname');
				$result['firstname']=$firstname;
				$data['firstname']=$firstname;
				$email = $this->input->post('email');
				$confirm_email = $this->input->post('confirm_email');	
				$question = $this->input->post('question');	
				$subject = $this->input->post('subject');
				
						
								 $url = base_url()."home/validate/".$userid."/".md5($result['firstname'])."/";
								$patterns[0] = '/{firstname}/';
								$patterns[1] = '/{email}/';
								
								$replacements[0] = $firstname;
								$replacements[1] = $email;
								$sub=$firstname." ".$email." : ".$question;
								$details = preg_replace($patterns, $replacements,$sub);
								//exit;
								$Subject =$subject;
								$head = "MIME-Version: 1.0\r\n".
								"Content-type: text/html; charset=iso-8859-1\r\n".
								"From: ".$firstname." < ".$email." >\r\n".
								"Date: ".date("r")."\r\n";	
								$TO = $adminmailid;
								$sent=mail($TO, $Subject,$details,$head);	
						
								$data['tit']='Contact';
								$data['pagereq']='contact_us';
								$data['msg']='We have received your message. You\'ll recieve a reply soon';
								$data['default']='';
								$data['day'] = date('d',time());
								$data['month'] = date('m',time());
								$data['year'] = date('Y',time());
								$this->load->view('mainview',$data);
		}
//-----------------	end static pages	



		function incoming()
		{
			$id = $this->uri->segment(3);
			
		
		}
function invited_friends()
	{

			$this->load->model('message');
			$this->load->model('zll');
			$this->load->view('redirect_login'); 
			$this->load->view('header');
			$error['msg'] = NULL;
			$this->load->view('invited',$error);
			$this->load->view('footer');

	}

function resend($invID)
	{	
	
			$this->load->model('message');
			$this->load->model('zll');
				$fullname = $number = NULL;
				$id = $this->session->userdata('id');
				$sql = mysql_query("select * from users where id = '$id'") or die(mysql_error());
				while($row = mysql_fetch_array($sql))
					{
						$fullname = $row['fullname'];
						$number = $row['number'];
					}		
					
				error_reporting(E_ALL);			
				//echo "select * from inv where invID = '$invID' ";
				$sql = mysql_query("select * from inv where invID = '$invID' ") or die(mysql_error());
				while($row = mysql_fetch_array($sql))
					{
										$fnumber = $row['mobNo'];
										
										$ins_data = NULL;
										$pass = rand(111111,999999);
										$ins_data['password'] = md5($pass);
										$xwh['number'] = $number;
										$userID = $this->zll->gUpdate('users',$xwh,$ins_data);
																						
										
										
										$txt = "$fullname at $number signed you to sounit.com sign in with phone $fnumber and password = $pass to learn more.";
	
										$url = base_url()."sms/quicktext/$fnumber/".urlencode($txt)."/";
										$f = fopen ("$url", "r");

										$this->load->model('message');
										$this->load->model('zll');
										$this->load->view('redirect_login'); 
										$this->load->view('header');
										$error['msg'] = " You have successfully re-send an invitation. ";
										$this->load->view('invited',$error);
										$this->load->view('footer');

					}

	}
	


function invite_friends()
	{
			$this->load->model('message');
			$this->load->model('zll');
			$error['msg'] = NULL;
			$MSG = "<font color='#000000'><b>Result of invitation</b></font><br>";
			if($this->input->post('abc'))
				{
					
					$sent = 0;
					for($i=1;$i<=10;$i++)
						{
							$fullname = $number = NULL;
							$id = $this->session->userdata('id');
							$sql = mysql_query("select * from users where id = '$id'") or die(mysql_error());
							while($row = mysql_fetch_array($sql))
								{
									$fullname = $row['fullname'];
									$number = $row['number'];
								}
						
							$fname = $this->input->post('fname'.$i);
							$fnumber = $this->input->post('fnumber'.$i);
							$gid = $this->input->post('gid'.$i);
							
							if($fname && $fnumber)
								{
								if($fnumber != $number) // user invite him self
									{
									
										$c = $this->message->check_duplicate_number($fnumber,$number);
										//print_r($c);
										if(!$c) // if user is not into our database
										{
											$ins_data = NULL;
											$pass = rand(99999,999999);
											$ins_data['password'] = md5($pass);
											$ins_data['status'] = 1;
											$ins_data['number'] = $fnumber;
											$ins_data['status'] = 1;
											$ins_data['pp'] = $pass;
											
											$userID = $this->zll->gInsert('users',$ins_data);
	
	
											$ins_data = NULL;
											$ins_data['userID'] = $userID;
											$ins_data['mobNo'] = $fnumber;
											$ins_data['inviteTime'] = time();
											$ins_data['invGroup'] = $gid;
											$ins_data['fname'] = $fname;
											$ins_data['invBy'] = $this->session->userdata('id');										
											$ins = $this->zll->gInsert('inv',$ins_data);
											
											$mem_ins = NULL;
											$mem_ins['group_id'] = $gid;
											$mem_ins['member_uid'] = $userID;
											$mem_ins['pending1'] = 0;
											$mem_ins['about'] = "Invited";
											$ins = $this->zll->gInsert('members',$mem_ins);
	
											
											$txt = "$fullname at $number signed you to sounit.com sign in with phone $fnumber and password = $pass to learn more.";
				
		
											$url = base_url()."sms/quicktext/$fnumber/".urlencode($txt)."/";
											$f = fopen ("$url", "r");
											$sent ++;
											$MSG .= "<font color='#0066FF'><b>$fname at $fnumber was successfully invited. </b></font><br>";
										}
										else // if user is into our group
										{
										
												
												$sql2 = mysql_query("select * from members as M, users as U where M.group_id = '$gid' and U.number = '$fnumber' and M.member_uid = U.id ") or die(mysql_error());
												if(mysql_num_rows($sql2))
													{
														$MSG .= "<font color='#FF0000'><b>$fname at $fnumber is already in group and was invited to to your group. <b></font><br>";														
														
													}
												else
													{
														$mem_ins = NULL;
														$mem_ins['group_id'] = $gid;
														$mem_ins['member_uid'] = $id;
														$mem_ins['pending1'] = 0;
														$mem_ins['about'] = "Invited";
														$ins = $this->zll->gInsert('members',$mem_ins);
														$MSG .= "<font color='#0066FF'><b>$fname at $fnumber was successfully invited. </b></font><br>";
													}									
										}
									}
								else
									{
											$MSG .= "<font color='#FF0000'><b>$fullname you can not invite your self. </b></font><br>";
									}
								}
						}	
					$error['msg'] = $MSG;
				}
				
			$this->load->view('redirect_login'); 
			$this->load->view('header');
			$this->load->view('invite',$error);
			$this->load->view('footer');
	}
	
	function affilates()
	{

	    $id = $this->session->userdata('id');
	    $sqlConf = mysql_query("SELECT * FROM usertype_config WHERE id IN (SELECT membertype FROM users WHERE id='$id')") or die(mysql_error());
	    $aConf=mysql_fetch_array($sqlConf,MYSQL_ASSOC);
	    
		$sql = mysql_query("SELECT u.*,uc.title,uc.signs_up_referred_by_you FROM users as u 
		                    LEFT JOIN usertype_config as uc ON u.membertype=uc.id
       		                WHERE aff_by=".$id) or die(mysql_error());
		$Affilates=array();
		$data=array();
		while($row = mysql_fetch_array($sql,MYSQL_ASSOC))
		{
			$Affilates[] = $row;
   		}		
   		
   		foreach ($Affilates as $key=>$aff)
   		{
       		$sql = mysql_query("SELECT u.*,uc.title,uc.referred, uc.signs_up_referred_by_you FROM users as u
                                LEFT JOIN usertype_config as uc ON u.membertype=uc.id
       		                    WHERE aff_by=".$aff['id']."") or die(mysql_error());
    		while($row = mysql_fetch_array($sql,MYSQL_ASSOC))
    		{
    			$Affilates[$key]['afflevel2'][] = $row;
       		}		
   		}	
   		
   		//print_r($Affilates);exit();
   		$data['aAffilate']=$Affilates;
   		$data['aConf']=$aConf;
   					
	    $this->load->view('header');
		$this->load->view('affilates',$data);
		$this->load->view('footer');
	}

}//end of class

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */