<?php
class Agent {
    private $conn;
    private $table_name = "agents";

    public $id;
    public $username;
    public $password_hsh;
    public $full_name;
    public $role;
    public $is_active;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function login($username, $password) {
        // On sélectionne tout pour être flexible sur les colonnes présentes
        $query = "SELECT * 
                  FROM " . $this->table_name . " 
                  WHERE username = ? AND is_active = 1 
                  LIMIT 0,1";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $username);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Vérification du mot de passe (supporte password_hash, md5 ou texte clair)
            $stored_password = $row['password_hsh'] ?? $row['password_hash'] ?? $row['password'] ?? '';
            
            // Security: Use timing-safe password comparison
            $is_valid = false;
            if (password_verify($password, $stored_password)) {
                $is_valid = true;
            } else if (md5($password) === $stored_password) {
                // Security: MD5 is weak, but kept for legacy support. 
                // Consider migrating to password_hash() for all users.
                $is_valid = true;
            } else if (hash_equals($stored_password, $password)) {
                $is_valid = true;
            }

            if ($is_valid) {
                // Tentative de mise à jour de last_login si la colonne existe
                try {
                    $update_query = "UPDATE " . $this->table_name . " SET last_login = CURRENT_TIMESTAMP WHERE id = ?";
                    $update_stmt = $this->conn->prepare($update_query);
                    $update_stmt->execute([$row['id']]);
                } catch (Exception $e) {
                    // Ignorer si la colonne last_login n'existe pas
                }
                
                return $row;
            }
        }
        return false;
    }
}
?>
