<?php 
// newgroup.php
	//session_start();
	chdir('../');
	include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');
	/* **************** HEADER FROM MAIN (REQUIRED FOR MENU) **************/
	include($_SERVER['DOCUMENT_ROOT'] . '/menu.php');
	$userDetails = menuUserDetails($_SESSION['front_user_id']);
	/* ***************** END HEADER FROM MAIN *****************************/

	// current page variable
	$current_page = 'newgroup';

	try {
		$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
		$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$obj_users = new Users($pdo);
	} catch(PDOException $e) {
		die("Connection failed: " . $e->getMessage());
	}

	$obj_users = new Users($pdo);
	
	if(!$obj_users->checkUserLoginOrNot()){
	    header('Location: '.BASEURL.'login.php');
	} 
	
	// Logout logic
	if (isset($_GET['logout'])) {
		// Destroy the session
		session_unset();
		session_destroy();
		header("Location: ../login.php"); // Redirect to the login page
		exit();
	}
	
	if($_SESSION['user_type']!='super' && $_SESSION['user_type']!='admin'){ 
		session_destroy();
		header('Location: '.BASEURL.'login.php');
		exit();
	}
	
	if($_SESSION['user_type'] == 'super') {
	    $usertype = 'super';
	} else if($_SESSION['user_type'] == 'admin') {
	    $usertype = 'admin';
	}

$group_name = "";
$group_admin = "";
$group_email = "";
$group_pass = "";
$expiration_date = "";
$group_institution_address = "";
$group_notes = "";

$message = ''; // Initialize message variable

// Check for message in session
if(isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

$date2 = date('Y-m-d h:i:s');
	
if(isset($_GET["id"]) && !empty($_GET["id"])) {  // when $_GET["id"] is set the page was requested from Edit a group
    $groupId = (int)$_GET['id'];

    $groupWhere = " WHERE id = :groupId ";
    
    $groups = "SELECT 
			   id, 
			   group_name,
			   group_admin, 
			   group_email, 
			   group_status,
			   group_notes,
			   group_pass,
			   group_pass_clear,
			   expiration_date,
			   group_institution_address,
			   group_registered,
			   pro_status
			   FROM wp_groups
			   $groupWhere";
    try {
        $stmt = $pdo->prepare($groups);
        $stmt->execute([':groupId' => $groupId]);
        
        if ($stmt->rowCount() < 1) {
            throw new Exception("Group query failed.");
        }
        
        $oneRow = $stmt->fetch(PDO::FETCH_ASSOC);
        $group_name = $oneRow['group_name'];
        $group_admin = $oneRow['group_admin'];
        $group_email = $oneRow['group_email'];
        $group_pass = $oneRow['group_pass_clear'];
        $expiration_date = $oneRow['expiration_date'];
        $group_institution_address = $oneRow['group_institution_address'];
        $group_notes = $oneRow['group_notes'];
		$pro_status = $oneRow['pro_status'];
    } catch (Exception $e) {
        ReportError($e);
        exit();
    }
}

if(isset($_POST['submitedit'])) {  // edit a group
    // note that name is not updated
    $passwordClear = $_POST['group_pass'];
    
    $password = $_POST['group_pass'];
    $salt = sha1(md5($password));
    $password = md5($password.$salt);
	      
	      //::
	      //:: next we will be updating the admin email in wp_users. just in case the emails are out
	      //:: of synch in wp_users and wp_groups then it will not be possible to find the email of the
	      //:: admin in wp_users to change it. For example, suppose the admin email in wp_groups is
	      //:: admin1@admin.com and the email for the group admin is admin2@admin.com in wp_uses. this
	      //:: could happen. then the old email will not be found in wp_users. what to do?
	      //:: 1. first try to find the old email in wp_uses
	      //:: 2. if that fails try to find a row or rows that match on group and have user_type = admin
	      //:: 3. if there is none, that is a problem
	      //:: 4. if there is more than one, that is a problem
	      //:: 5. if there is one then update that row with the new admin email
	      //::
	      
//:: 
      //:: now update the user_email in wp_users in case the admin's email has been changed
      //::
      if (strtolower($_POST['group_email_hidden']) != strtolower($_POST['group_email'])) {
          //::
          //:: 1. first try to find the old email in wp_uses
          //::
          $group_old_email = strtolower($_POST['group_email_hidden']); 
          $group_new_email = strtolower($_POST['group_email']); 
          
          $getUserEmail = "SELECT
                            user_email
                        FROM wp_users
                        WHERE
                            user_email = :old_email";
          //echo "getUserEmail: ".$getUserEmail; exit;
          
          try {
              $stmt = $pdo->prepare($getUserEmail);
              $stmt->execute([':old_email' => $group_old_email]);
              
              if (!$stmt) {
                  throw new Exception("Find Email has failed.");
              }
          } catch (Exception $e) {
              ReportError($e);
              exit();
          } 
              
          if ($stmt->rowCount() < 1) { //email cannot be found
              //::
              //:: 2. if that fails try to find a row or rows that match on group and have user_type = admin
              //::
              $getUserEmailByGroupAndAdmin = "SELECT
                                                  user_email
                                              FROM wp_users
                                              WHERE
                                                  user_group = :group_name
                                                AND
                                                  (user_type = 'admin' OR user_type = 'super')";
              //echo "getUserEmailByGroupAndAdmin: ".$getUserEmailByGroupAndAdmin; exit;
              
              try {
                  $stmt = $pdo->prepare($getUserEmailByGroupAndAdmin);
                  $stmt->execute([':group_name' => $group_name]);
                  
                  if (!$stmt) {
                      throw new Exception("Find Email by group and admin has failed.");
                  }
              } catch (Exception $e) {
                  ReportError($e);
                  exit();
              }
              //echo "num rows: ".$stmt->rowCount(); exit;
              if ($stmt->rowCount() < 1) { //email cannot be found on group and admin
                  try {
                      throw new Exception("No admin user is registered.");
                  } catch (Exception $e) {
                      ReportError($e);
                      exit();
                  }
              } else if ($stmt->rowCount() > 1) { //there are two or more admins
                  try {
                      throw new Exception("There is more than one admin for this group.");
                  } catch (Exception $e) {
                      ReportError($e);
                      exit();
                  }
              } else { // the email that matches the old email has been found on group and admin
                  $updateUserEmail = "UPDATE wp_users
                                  SET
                                       user_email = :new_email
                                  WHERE
                                        user_group = :group_name
                                      AND
                                        (user_type = 'admin' OR user_type = 'super')";
                  //echo "updateUserEmail no 1: ".$updateUserEmail; exit;
                          
                  try {
                      $stmt = $pdo->prepare($updateUserEmail);
                      $result = $stmt->execute([
                          ':new_email' => $group_new_email,
                          ':group_name' => $group_name
                      ]);
                      
                      if (!$result) {
                          throw new Exception("Update Users Email has failed.");
                      }
                  } catch (Exception $e) {
                      ReportError($e);
                      exit();
                  }
              }
          } else { // the old email was found
              $updateUserEmail = "UPDATE wp_users
                                  SET
                                       user_email = :new_email
                                  WHERE user_email = :old_email";
              //echo "updateUserEmail no 2: ".$updateUserEmail; exit;
                          
              try {
                  $stmt = $pdo->prepare($updateUserEmail);
                  $result = $stmt->execute([
                      ':new_email' => $group_new_email,
                      ':old_email' => $group_old_email
                  ]);
                  
                  if (!$result) {
                      throw new Exception("Update Users Email has failed.");
                  }
              } catch (Exception $e) {
                  ReportError($e);
                  exit();
              }
          }
      }
    
      $editGroup = "UPDATE wp_groups
                    SET group_admin = :admin,
                       group_pass = :pass,
                       group_pass_clear = :pass_clear,
                       group_email = :email,
                       group_institution_address = :address,
                       expiration_date = :inst_name,
                       group_notes = :notes
                  WHERE id = :id";
      //echo "password update ".$editGroup; exit;
              
      try {
          $stmt = $pdo->prepare($editGroup);
          $result = $stmt->execute([
              ':admin' => $_POST['group_admin'],
              ':pass' => $password,
              ':pass_clear' => $passwordClear,
              ':email' => strtolower($_POST['group_email']),
              ':address' => $_POST['group_institution_address'],
              ':inst_name' => $_POST['expiration_date'],
              ':notes' => $_POST['group_notes'],
              ':id' => $groupId
          ]);
          
          if (!$result) {
              throw new Exception("Edit Group has failed.");
          }
      } catch (Exception $e) {
          ReportError($e);
          exit();
      }
    
      //::
      //:: update all the users in the group with the new password
      //::
      $updateUserPwd = "UPDATE wp_users
                       SET
                        user_pass = :password
                       WHERE user_group = :group_name";
      //echo "password update ".$updateUserPwd; exit;
              
      try {
          $stmt = $pdo->prepare($updateUserPwd);
          $result = $stmt->execute([
              ':password' => $password,
              ':group_name' => $group_name
          ]);
          
          if (!$result) {
              throw new Exception("Update Users has failed.");
          }
      } catch (Exception $e) {
          ReportError($e);
          exit();
      }
      
      header('location: index.php');
  }
			
if(isset($_POST['submitnew'])){    // ------------------------ New Group ----------------------------
  
    $passwordClear = $_POST['group_pass'];
  
    $password = $_POST['group_pass'];
    $salt = sha1(md5($password));
    $password = md5($password.$salt);
    
    $groupEmail = $_POST['group_email'];
    $groupName = $_POST['group_name'];
    
    $date2 = date('Y-m-d h:i:s');
    
    //::
    //:: first check does the email of the administrator already exist
    //::
    $check = "SELECT
                user_email
             FROM wp_users
             WHERE user_email = :groupEmail";
             
    try{
        $stmt = $pdo->prepare($check);
        $stmt->execute([':groupEmail' => $groupEmail]);
        
        if ($stmt->rowCount() > 0 ) {
            throw new Exception ("User Email ".$groupEmail." already exists.");
        }
    }   
    catch (Exception $e){
        ReportError($e);
        exit();
    }
    //::
    //:: Now does the group already exist
    //::
    $check = "SELECT
                group_name
             FROM wp_groups
             WHERE group_name = :groupName";
             
    try{
        $stmt = $pdo->prepare($check);
        $stmt->execute([':groupName' => $groupName]);
        
        if ($stmt->rowCount() > 0 ) {
            throw new Exception ("Group Name ".$groupName." already exists.");
        }
    }   
    catch (Exception $e){
        ReportError($e);
        exit();
    }
    //::
    //:: ok everything is go to insert the new group admin to the users table
    //:: in other words register the group admin as a user
    //::
    $registrationQuery = "INSERT INTO wp_users
                        (
                        user_email,
                        user_pass,
                        user_group,
                        user_type,
                        user_status,
                        user_registered
                        )
                        VALUES
                        (
                        :group_email,
                        :password,
                        :group_name,
                        'admin',
                        1,
                        :date2
                        )";
                        //echo $registrationQuery; exit;
    try{
        $stmt = $pdo->prepare($registrationQuery);
        $result = $stmt->execute([
            ':group_email' => strtolower($_POST['group_email']),
            ':password' => $password,
            ':group_name' => $_POST['group_name'],
            ':date2' => $date2
        ]);
        
        if(!$result){
            throw new Exception ("Autoregistration of Group Admin has failed.");
        }
    }   
    catch (Exception $e){
        ReportError($e);
        exit();
    }   
    //::
    //:: now insert the new group
    //::
    $newGroup = "INSERT INTO wp_groups
                (
                group_admin,
                group_pass,
                group_pass_clear,
                group_email,
                group_name,
                group_institution_address,
                expiration_date,
                group_notes,
                group_registered,
                group_status,
				pro_status
                )
                VALUES
                (
                :group_admin,
                :password,
                :passwordClear,
                :group_email,
                :group_name,
                :group_institution_address,
                :expiration_date,
                :group_notes,
                :date2,
                'Active',
				:pro_status
                )";
                //echo $newGroup; exit;
    try{
        $stmt = $pdo->prepare($newGroup);
        $result = $stmt->execute([
            ':group_admin' => $_POST['group_admin'],
            ':password' => $password,
            ':passwordClear' => $passwordClear,
            ':group_email' => strtolower($_POST['group_email']),
            ':group_name' => $_POST['group_name'],
            ':group_institution_address' => $_POST['group_institution_address'],
            ':expiration_date' => $_POST['expiration_date'],
            ':group_notes' => $_POST['group_notes'],
            ':date2' => $date2,
			':pro_status' => isset($_POST['pro_status']) ? $_POST['pro_status'] : 'No'
        ]);
        
        if(!$result){
            throw new Exception ("Creation of New Group has failed.");
        }
    }   
    catch (Exception $e){
        ReportError($e);
        exit();
    } 
	
	// update the admin user's group_id field and password fields
	$newGroupId = $pdo->lastInsertId(); // Get the ID of the group we just created

	// Update the admin user's group_id and ensure password fields are updated
	$updateAdminFields = "UPDATE wp_users 
						 SET group_id = :group_id,
							 user_pass_clear = :user_pass_clear
						 WHERE user_email = :group_email 
						 AND user_type = 'admin'";

	try {
		$stmt = $pdo->prepare($updateAdminFields);
		$result = $stmt->execute([
			':group_id' => $newGroupId,
			':user_pass_clear' => $passwordClear,
			':group_email' => $_POST['group_email']
		]);
		
		if (!$result) {
			throw new Exception("Updating admin user's group_id and password fields has failed.");
		}
	} catch (Exception $e) {
		ReportError($e);
		exit();
	}

$_SESSION['message'] = "<h3>New group created successfully.</h3><br>" . 
    "<b>Group Name:</b> " . htmlspecialchars($_POST['group_name']) . "<br>" . 
    "<b>Admin:</b> " . htmlspecialchars($_POST['group_admin']) . "<br>" . 
    "<b>Email:</b> " . htmlspecialchars($_POST['group_email']) . "<br>" . 
    "<b>Password:</b> " . htmlspecialchars($passwordClear) . "<br>" . 
    "<b>Pro Status:</b> " . htmlspecialchars(isset($_POST['pro_status']) ? $_POST['pro_status'] : 'No') . "<br>";

// Add expiration date if set
if (!empty($_POST['expiration_date'])) {
    $_SESSION['message'] .= "<b>Expiration Date:</b> " . htmlspecialchars($_POST['expiration_date']) . "<br>";
}

// Add institution address if set
if (!empty($_POST['group_institution_address'])) {
    $_SESSION['message'] .= "<b>Institution Address:</b> " . htmlspecialchars($_POST['group_institution_address']) . "<br>";
}

// Add notes if set
if (!empty($_POST['group_notes'])) {
    $_SESSION['message'] .= "<b>Notes:</b> " . htmlspecialchars($_POST['group_notes']) . "<br>";
}

    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

include ($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php');
	
?>
	 
<?php /* ****************** BEGIN NEWGROUP PAGE ********************/ ?>

	 <script type="text/javascript">
	      function validateNew() {
		    var egroupname = document.getElementById('group-name');   
		    var egroupemail = document.getElementById('group-email');  
		    var egrouppass = document.getElementById('group-pass');  
		    
		    var retval = true;
		    
		    if (egroupname.value.length < 1) {
			    alert("Group Name is a required field.");
			    retval = false;
		    }  else if (egroupemail.value.length < 1) {
			    alert("Group Email is a required field.");
			    retval = false;          
		    }  else if (egrouppass.value.length < 1) {
			    alert("Group Password is a required field.");
			    retval = false;
		    }
		    
		    return retval;
	      }
	      
	      function validateEdit() {
		    var egroupname = document.getElementById('group-name');   
		    var egroupemail = document.getElementById('group-email');  
		    var egrouppass = document.getElementById('group-pass');  
		    
		    var retval = true;
		    
		    if (egroupname.value.length < 1) {
			    alert("Group Name is a required field.");
			    retval = false;
		    }  else if (egroupemail.value.length < 1) {
			    alert("Group Email is a required field.");
			    retval = false;          
		    } 
		    
		    return retval;
	      }
	 </script>
	 
	<div class="content">
        <?php
        if (!empty($message)) {
            $messageClass = (strpos($message, 'successfully') !== false) ? 'success' : 'error';
            echo '<div class="alert-message ' . $messageClass . '">' . htmlspecialchars_decode($message) . '</div>';
        }
        ?>
			<h2><?php if (isset($groupId)) {
		      echo "<h2>Edit Group</h2>";
			      } else {
		      echo "<h2>Create New Group</h2>";
			      } ?></h2><br>
		   
		       <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
			    <?
		 if (isset($groupId)) {
		      echo "<input id='group-email-hidden' name='group_email_hidden'  value='$group_email' type='hidden' />";
		 }
			    ?>
			 
			<table class="home-table">
		       <tr>
			     <td class="newgrouplabel">
				       Group Name:
			     </td>
			     <td class="newgroupdata">
				    <?
					  if (isset($groupId)) {
				echo "<input id='group-name' name='group_name' disabled='disabled' value='$group_name' type='text' />";
					  } else {
				echo "<input id='group-name' name='group_name'  value='$group_name' type='text' />";
					  }
				    ?>
			     </td>
			     <td style="color:red;font-style:italic;">
					* Required Field
			     </td>
		       </tr>
		       
			   <tr>
					<td class="newgrouplabel">
						   Pro Status:
					</td>
					<td class="newgroupdata">
						<select id="pro-status" name="pro_status">
							<option value="No" selected>No</option>
							<option value="Pro">Pro</option>
						</select>
					</td>
					<td>
					</td>
			   </tr>
		  
		       <tr>
			     <td class="newgrouplabel">
				     Group Admin Name:
			     </td>
			     <td class="newgroupdata">
				     <input id="group-admin" name="group_admin" value="<?= $group_admin ?>" type="text" />
			     </td>
			     <td>
			     </td>
		       </tr>
		       
		       <tr>
			     <td class="newgrouplabel">
				     Group Admin Email:
			     </td>
			     <td class="newgroupdata">
				     <input id="group-email" name="group_email" value="<?= $group_email ?>" type="text" />
			     </td>
			      <td style="color:red;font-style:italic;">
					* Required Field
			     </td>
 		       </tr>
		       
		       <tr>
			     <td class="newgrouplabel">
				     Group Password:
			     </td>
			     <td class="newgroupdata">
				     <input id="group-pass" name="group_pass" value="<?= $group_pass ?>" type="text" />
			     </td>
			      <td style="color:red;font-style:italic;">
					* Required Field
				    <?
					//    if (isset($groupId)) {
					//	  echo '* Enter a password if you intend to change the password';
					//    } else {
					//	  echo '* Required Field';
					//    }
				    ?>
			     </td>
		       </tr>
		       
		       <tr>
			     <td class="newgrouplabel">
				     Expiration Date:
			     </td>
			     <td class="newgroupdata">
				     <input type="date" id="group-institution-name" name="expiration_date" value="<?= $expiration_date ?>">
			     </td>
			      <td>
			     </td>
		       </tr>
		       
		       <tr>
			     <td class="newgrouplabel" style="vertical-align:text-top;">
				       Institution Address:
			     </td>
			     <td class="newgroupdata">
				       <textarea id="group-institution-address" name="group_institution_address"  type="textarea" cols="38" rows="5"/><?= $group_institution_address ?></textarea>
			     </td>
			      <td>
			     </td>
		       </tr>
			   
		       <tr>
			     <td class="newgrouplabel" style="vertical-align:text-top;">
				       Group Notes:
			     </td>
			     <td class="newgroupdata">
				       <textarea id="group-notes" name="group_notes" type="textarea"  cols="38" rows="5"/><?= $group_notes ?></textarea>
			     </td>
			      <td>
			     </td>
		       </tr>
		       
		       <tr>
			     <td>
			     </td>
			     <td>
				    <?
					    if (isset($groupId)) {
				  echo '<input id="submit-button" value="Record Changes" name="submitedit" type="submit" style="width:26em;"  onclick="javascript: return validateEdit()" />';
					    } else {
				  echo '<input id="submit-button" value="Record New Group" name="submitnew" type="submit" style="width:26em;" onclick="javascript: return validateNew()" />';
					    }
				    ?>
			     </td>
			      <td>
			     </td>
		       </tr>
			</table>
		</form>
	</div>  
			 
<?php include ($_SERVER['DOCUMENT_ROOT'] . '/admin/footer.php'); ?>
</body>
</html>