<?php

include_once 'config.php';

class users_model
{
    public $link;

    public function __construct()
    {
        $db_connection = new dbConnection();
        $this->link = $db_connection->connect();
    }
    
    public function authenticateUser($username) {
        try {
            $sql = 'SELECT * FROM  users WHERE username = :username';
            $stmt = $this->link->prepare($sql);
            $stmt->bindParam(':username', $username, 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 getuserDetails($username) {
        $query = "SELECT
                    fullname,
                    phone_number,
                    email,
                    u.password as current_password,
                
                CASE 
                    WHEN avatar IS NULL THEN 'default_avatar.png'
                    ELSE avatar
                END AS avatar
            FROM 
                users u
               WHERE
               		u.username = :username";
        
        $stmt = $this->link->prepare($query);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();
        
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function getNumberofUsers() {
        try {
            $sql = "SELECT COUNT(*) as total FROM users WHERE user_state = 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;
        }
    }

}