<?php
include_once("_nemo.list.cls.php");
include_once("_nemo.password.cls.php");

/*
ALTER TABLE `sysUser` drop FOREIGN KEY `sysUser.strSecurityGroup`;
ALTER TABLE `sysUser` ADD CONSTRAINT `sysUser.strSecurityGroup` FOREIGN KEY (`refSecurityGroupID`) REFERENCES `sysSecurityGroup` (`SecurityGroupID`) ON UPDATE CASCADE ON DELETE CASCADE;

* 20161025 - added sublist function getPracticeUserList() for user list in practice details view - neils
* 20171103 - changed save to use password framework - maanie
*/

class User extends NemoList
{
   private $ID = 0;

   public function __construct($DataKey)
   {
      parent::__construct($DataKey);
   }

   public function getList()
   {
      $this->ListSQL("SELECT sysUser.UserID,
                              sysUser.strUser AS User,
                              sysSecurityGroup.strSecurityGroup AS 'Security Group',
                              sysUser.strEmail AS Email,
                              MAX(sysLogin.strDateTime) AS 'Date Last Logged In',
                              sysUser.blnActive AS Active,
                              sysUser.strLastUser AS 'Last User',
                              sysUser.dtLastEdit AS 'Last Edit'
                     FROM sysUser
                           INNER JOIN sysSecurityGroup ON sysUser.refSecurityGroupID = sysSecurityGroup.SecurityGroupID
                           LEFT JOIN sysLogin ON sysUser.strEmail = sysLogin.strUsername
                     GROUP BY sysUser.strUser
                     ORDER BY sysUser.strUser");

      return $this->renderTable("User List");
   }

   public function getCourseCoordinatorListCourse($CourseID)//this list is shown on the course details and shows the coordinators for the selected course
   {
      $this->ListSQL("SELECT sysUser.UserID,
                              sysUser.strUser AS User,
                              sysUser.strEmail AS Email,
                              MAX(sysLogin.strDateTime) AS 'Date Last Logged In',
                              sysUser.blnActive AS Active,
                              sysUser.strLastUser AS 'Last User',
                              sysUser.dtLastEdit AS 'Last Edit'
                     FROM sysUser
                           LEFT JOIN sysLogin ON sysUser.strEmail = sysLogin.strUsername
                           INNER JOIN tblCourseCoordinator ON tblCourseCoordinator.refUserID = sysUser.UserID
                     WHERE blnCoordinator = 1 AND tblCourseCoordinator.refCourseID = $CourseID
                     GROUP BY sysUser.strUser
                     ORDER BY sysUser.strUser");

      return $this->renderTable("Coordinator List");
   }

   public function getCourseCoordinatorListUser($CourseID)//this list is shown when adding coordinators to a course. It shows all coordinators excluding the ones that are already added to the course.
   {
      $sql = "SELECT sysUser.UserID,
                              sysUser.strUser AS User,
                              sysUser.strEmail AS Email,
                              MAX(sysLogin.strDateTime) AS 'Date Last Logged In',
                              sysUser.blnActive AS Active,
                              sysUser.strLastUser AS 'Last User',
                              sysUser.dtLastEdit AS 'Last Edit'
                     FROM sysUser
                           LEFT JOIN sysLogin ON sysUser.strEmail = sysLogin.strUsername
                     WHERE blnCoordinator = 1 AND sysUser.UserID NOT IN (SELECT refUserID FROM tblCourseCoordinator WHERE refCourseID = $CourseID)
                     GROUP BY sysUser.strUser
                     ORDER BY sysUser.strUser";
      //echo $sql;
      $this->ListSQL($sql);

      return $this->renderTable("Coordinator List");
   }

//20171103 - changed save to use password framework - maanie
   public static function Save(&$UserID, $nemo)
   {
      global $xdb, $arrSys, $TR, $SP, $HR, $PHP_SELF, $DATABASE_SETTINGS, $SystemSettings;
      $db = new NemoDatabase("sysUser", $UserID, null, 0);

      $xdb = nCopy($db);

      $db->SetValues($_POST);
      //$db->Fields[strPasswordMD5] = md5($_POST[strPassword]);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      if($UserID == 0){
         $db->Fields[strFirstUser] = $nemo->SystemSettings[USER]->USERNAME;
         $db->Fields[dtFirstEdit] = date("Y-m-d H:i:s");
      }

      //update WA - CELESTIS ONLY!
      /*
      mysql_select_db($DATABASE_SETTINGS[$SystemSettings[SERVER_NAME]]->database2);
      $xdb->doQuery("UPDATE tblUser SET
                   strEmail = ". $xdb->qs($_POST[strEmail]) ."
                   , strPassword = ". $xdb->qs($_POST[strPassword]) ."
                   , strPasswordMD5 = '". md5($_POST[strPassword]) ."'
                  WHERE strEmail = ". $xdb->qs($xdb->Fields[strEmail]));

      mysql_select_db($DATABASE_SETTINGS[$SystemSettings[SERVER_NAME]]->database);
      */

      //print_rr($_FILES);
      if($_FILES['Profile:PicturePath']['name'] != "" && $UserID != 0)
      {//current: cel_a/wa/_ need to go to cel_a/training/profilepictures/
         chmod($_FILES['Profile:PicturePath']['tmp_name'] , 0777);
         $strFileName = str_pad($UserID, 5,"0", STR_PAD_LEFT) ."_". $_FILES["Profile:PicturePath"]["name"];

         $strPath = $SystemSettings[ProfileImageDirAdmin]; //$strPath = "../../celestis_academy/training/profliepictures/";

         $db->Fields["Profile:PicturePath"] = $strFileName;

         move_uploaded_file($_FILES['Profile:PicturePath']['tmp_name'], $strPath . $strFileName);

      }

      $result = $db->Save();
      if($UserID == 0) 
      {
         $UserID = $db->ID[UserID];
   
         if($result->Error != 1) // ONLY SEND EMAIL FOR A NEW USER IF THERE ARE NO ERRORS
         {
            $EmailSentMessage .= User::ResetPassword($UserID);
         }
      }

      //print_rr($result);
      if($result->Error == 1){
         return $result->Message;
      }else{
         return "Details Saved. " . $EmailSentMessage;
      }
   }

   public static function Delete($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         //$xdb->doQuery("DELETE FROM sysUser WHERE UserID = ". $xdb->qs($key));
         $xdb->doQuery("UPDATE sysUser SET blnActive = 0 WHERE UserID = ". $xdb->qs($key));
      }
         return "Records Deleted.";
      }
   }

   public static function AddCoordinatorsToCourse($chkSelect, $CourseID)
   {
      global $xdb;

      if(count($chkSelect) > 0){
         foreach($chkSelect as $key => $value)
         {
            //echo "INSERT IGNORE INTO tblCourseCoordinator(refCourseID, refUserID) VALUES(". $xdb->qs($CourseID) .",". $xdb->qs($key) .")";
            $xdb->doQuery("INSERT IGNORE INTO tblCourseCoordinator(refCourseID, refUserID) VALUES(". $xdb->qs($CourseID) .",". $xdb->qs($key) .")");
         }
         return false;
      }else{
         return "No Learners selected.";
      }
   }

   public static function RemoveCoordinatorsFromCourse($chkSelect, $CourseID)
   {
      global $xdb;

      if(count($chkSelect) > 0){
         foreach($chkSelect as $key => $value)
         {
            $xdb->doQuery("DELETE FROM tblCourseCoordinator WHERE refUserID = ". $xdb->qs($key)." AND refCourseID = ". $xdb->qs($CourseID));
         }
         return "Assessment Deleted.";
      }else{
         return "No Assessments selected.";
      }
   }

   public static function SendResetEmail($hash, $strEmail)
   {
      global $xdb, $TR, $SP, $HR, $DT, $SystemSettings;

      $rst = $xdb->doQuery("SELECT * FROM sysUser WHERE strEmail = '$strEmail'");
      $row = $xdb->num_rows($rst);
      $rowDetails = $xdb->fetch_object($rst);

      if($row == 1)
      {
         include_once("_nemo.email.cls.php");

         ## ADD RECORD TO RESET PASSWORD TABLE
         $nemoEmail = new NemoEmail($strEmail , "" , 0);
         $nemoEmail->LoadEmailTemplate("Reset Password");

         $arrValues[DisplayName] = $rowDetails->strUser;
         $arrValues[Link] = "<a href='".$SystemSettings[BASE_URL]."resetPassword.php?strEmail=$strEmail&ResetKey=$hash'>Reset Password</a>";

         $strBaseURL = str_replace("/webadmin", "", $SystemSettings[BASE_URL]);
         $arrValues[Logo] = "<a href='".$strBaseURL."index.php"."'><img src='".$strBaseURL.$SystemSettings[EmailLogoPFI]."' ></a>";

         $nemoEmail->Substitute($arrValues);

         $nemoEmail->addHeader("FROM", $SystemSettings["SMTP Send As"]);
         //$nemoEmail->addHeader("BCC", $SystemSettings["SMTP BCC"]);
         //$nemoEmail->Bcc = $SystemSettings["SMTP BCC"];
         $nemoEmail->From = $SystemSettings["SMTP Send As"];

         $nemoEmail->Send();
      }
      else
      {
         ## DO NOTHING
      }
   }

   public static function ResetPassword($UserID)
   {
      $np = new NemoPassword();
      $np->createPassword(Obfuscate());
      $np->savePassword("User", $UserID, "2010-01-01", 0); // 2010-01-01 = Default Aged date

      //20160926 - added email sending process for a new user to reset there password - maanie
      User::SendResetEmail($np->hash, $_POST[strEmail]);

      return "Password reset email has been sent to " . $_POST[strEmail];
   }
}
?>
