<?php 
require_once('db_connection.php');




class User  
{
    private $db;
  
    
    function __construct($dbconn){
        $this->db = $dbconn;
        
    }
    public function register($username, $password, $email){
        // Hash the password for security
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Prepare the SQL statement to insert a new user
        $stmt = $this->db->prepare("INSERT INTO users (username,email, password, role) VALUES (?, ?, ?, 'user')");
        $stmt->bind_param("sss", $username, $email, $hashedPassword);

        // Execute the statement
        if ($stmt->execute()) {
            // Registration successful
            return true;
        } else {
            // Registration failed
            return false;
        }
    }

    public function login($username, $password){
        // Prepare the SQL statement to fetch the user with the provided username
        $query = "SELECT * FROM users WHERE username = '$username'";
        $result =  mysqli_query($this->db, $query);
        $num_rows = mysqli_num_rows($result);

        if($num_rows == 1){
            return mysqli_fetch_all($result,MYSQLI_BOTH);  
        }
        return  array();
        // User authentication failed
    }

  public function getUserById($id){
         // Prepare the SQL statement to fetch the user with the provided username
         $query = "SELECT * FROM users WHERE id = $id ";
         $result =  mysqli_query($this->db, $query);
         $data =  mysqli_fetch_all($result,MYSQLI_BOTH);  
         return $data;
        
  }


  public function editUsername($username,$id){
    // Prepare the SQL statement to fetch the user with the provided username
    $query = "UPDATE `users` SET `username` = '$username' WHERE `users`.`id` = $id";
    $result =  mysqli_query($this->db, $query);
     $log->createLog(1,'Edit User') ;
    return $result;
   
}
  public function editUser($username,$email,$pass,$id){
    // Prepare the SQL statement to fetch the user with the provided username
    $hashedPassword = password_hash($pass, PASSWORD_DEFAULT);
    $query = "UPDATE `users` SET `username` = '$username', `password` = '$hashedPassword', email = '$email' WHERE `id` = $id" ;
    $result =  mysqli_query($this->db, $query);
    return $result;
   
}

  public function getUsers(){
         // Prepare the SQL statement to fetch the user with the provided username
         $query = "SELECT * FROM users ";
         $result =  mysqli_query($this->db, $query);
         $data =  mysqli_fetch_all($result,MYSQLI_BOTH);  
         return $data;
        
  }

  public function deleteUser($studentId){
       $query = "DELETE FROM users WHERE `users`.`id` = ?";
        $stmt = $this->db->prepare($query);
        $stmt->bind_param("s", $studentId);
        $stmt->execute();
        $result = $stmt->get_result();

        return $result;
        
  }




}