<?php

include_once 'config.php';

class users_model
{

    public $link;

    public function __construct()
    {
        $db_connection = new dbConnection();
        $this->link = $db_connection->connect();
    }

    public function checkSession($session_id) {
        try {
             $sql = "SELECT COUNT(*) AS session_count FROM hrdc_logins WHERE session_id = :session_id";
            $stmt = $this->link->prepare($sql);
            $stmt->bindParam(':session_id', $session_id, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return $result['session_count'];
        } catch (PDOException $e) {
            error_log("Error checking session: " . $e->getMessage());
            return 0; // Return 0 in case of error
        }
    }

    public function authenticateUser($email) {
        try {
            $sql = 'SELECT * 
                FROM 
                    hrdc_users
                WHERE 
                    username_email = :email';
            $stmt = $this->link->prepare($sql);
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return $user ? $user : false;
        } catch (PDOException $e) {
            error_log("Error authenticating user: " . $e->getMessage());
            return false;
        }
    }


    public function logLogin($session_id, $userid, $username, $login_time, $account, $attempt, $sess_state) {
        $sql = "INSERT INTO hrdc_logins(session_id, userid, username, login_time, account, attempt, active_session)
                VALUES (:session_id, :userid, :username, :login_time, :account, :attempt, :sess_state )";

        $stmt = $this->link->prepare($sql);

        // Binding parameters to avoid SQL injection
        $stmt->bindParam(':session_id', $session_id);
        $stmt->bindParam(':userid', $userid);
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':login_time', $login_time);
        $stmt->bindParam(':account', $account);
        $stmt->bindParam(':attempt', $attempt);
        $stmt->bindParam(':sess_state', $sess_state);

        // Execute the query
        return $stmt->execute();
    }

    public function getNumberofUsers() {
        try {
            $sql = "SELECT COUNT(*) as total FROM hrdc_users WHERE user_state = 1 AND ID !=1";
            $stmt = $this->link->prepare($sql);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            return $row['total'];
        } catch (PDOException $e) {
            error_log("User count error: " . $e->getMessage());
            return 0;
        }
    }

    public function cancelActive($username){
        $sql = "UPDATE hrdc_logins SET active_session = 0 WHERE username = :username";
        $stmt = $this->link->prepare($sql);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
    }


    public function logoutUpdates($logout_time, $session_id){
        $sql = "UPDATE hrdc_logins SET logout_time = :logout_time WHERE session_id = :session_id";
        $stmt = $this->link->prepare($sql);
        $stmt->bindParam(':logout_time', $logout_time, PDO::PARAM_STR);
        $stmt->bindParam(':session_id', $session_id, PDO::PARAM_STR);
        
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
    }

    public function getsystemusers() {
        try {
            $sql = "SELECT *,
                CASE
                    WHEN user_state = 1 THEN 'Active'
                    ELSE 'Inactive'
                END AS user_state
            FROM 
                hrdc_users
            WHERE 
                ID != 1
            ORDER BY 
                user_fullname ASC";
            $stmt = $this->link->prepare($sql);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error fetching system users: " . $e->getMessage());
            return [];
        }
    }

    /**
     * Add a new system user to the database.
     *
     * @param string $fullname The full name of the user.
     * @param string $username_email The email/username of the user.
     * @param string $password The password of the user (should be hashed before storing).
     * @param string $user_registered The date and time the user was registered.
     * @param string $user_role The role assigned to the user.
     * @param string $created_by The user who created this account.
     * @param string $user_state The state or status of the user (e.g., active, inactive).
     * @param string $avatar The avatar image path or URL of the user (optional).
     * 
     * @return bool True on success, false on failure.
     */
    public function addSystemUser($fullname, $username_email, $password, $user_registered, $user_role, $created_by, $user_state) {
        $query = "INSERT INTO hrdc_users (user_fullname, username_email, user_pass, user_registered, user_role, created_by, user_state) 
                  VALUES (:fullname, :username_email, :password, :user_registered, :user_role, :created_by, :user_state)";

        $stmt = $this->link->prepare($query);

        // Bind the parameters
        $stmt->bindParam(':fullname', $fullname);
        $stmt->bindParam(':username_email', $username_email);
        $stmt->bindParam(':password', password_hash($password, PASSWORD_DEFAULT)); // Hash the password
        $stmt->bindParam(':user_registered', $user_registered);
        $stmt->bindParam(':user_role', $user_role);
        $stmt->bindParam(':created_by', $created_by);
        $stmt->bindParam(':user_state', $user_state);

        return $stmt->execute();
    }

    /**
     * Get user by email.
     *
     * @param string $email The email to check.
     * @return mixed The user data if the email exists, false otherwise.
     */
    public function getUserByEmail($email) {
        // Prepare the SQL query to check if the email exists
        $query = "SELECT * FROM hrdc_users WHERE username_email = :email";
        
        // Prepare and execute the statement
        $stmt = $this->link->prepare($query);
        $stmt->bindParam(':email', $email);
        $stmt->execute();

        // Check if any row was returned
        return $stmt->fetch(PDO::FETCH_ASSOC); // Returns the user data if found, or false if not
    }
    





}