<?php

namespace WowLive\Models;

class User {
    private $conn;
    private $table_name = "usuarios";

    public $id;
    public $username;
    public $password;
    public $nome;
    public $email;
    public $data_criacao;

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

    public function authenticate($username, $password) {
        $query = "SELECT id, username, password, nome, email FROM " . $this->table_name . " WHERE username = :username LIMIT 1";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':username', $username);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            $row = $stmt->fetch();
            
            if (password_verify($password, $row['password'])) {
                $this->id = $row['id'];
                $this->username = $row['username'];
                $this->nome = $row['nome'];
                $this->email = $row['email'];
                return true;
            }
        }
        
        return false;
    }

    public function create() {
        $query = "INSERT INTO " . $this->table_name . " (username, password, nome, email) VALUES (:username, :password, :nome, :email)";
        
        $stmt = $this->conn->prepare($query);
        
        // Hash da senha
        $hashed_password = password_hash($this->password, PASSWORD_DEFAULT);
        
        $stmt->bindParam(':username', $this->username);
        $stmt->bindParam(':password', $hashed_password);
        $stmt->bindParam(':nome', $this->nome);
        $stmt->bindParam(':email', $this->email);

        return $stmt->execute();
    }

    public function findById($id) {
        $query = "SELECT id, username, nome, email, data_criacao FROM " . $this->table_name . " WHERE id = :id LIMIT 1";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            $row = $stmt->fetch();
            $this->id = $row['id'];
            $this->username = $row['username'];
            $this->nome = $row['nome'];
            $this->email = $row['email'];
            $this->data_criacao = $row['data_criacao'];
            return true;
        }
        
        return false;
    }
}

