<?php
namespace App\Models;

use App\Core\Model;

class User extends Model
{
    public function getAll()
    {
        $stmt = $this->query("SELECT id, username, full_name, email, role, status, last_login, created_at FROM users ORDER BY username");
        return $stmt->fetchAll();
    }

    public function find($id)
    {
        $stmt = $this->query("SELECT id, username, full_name, email, role, status FROM users WHERE id = ?", [$id]);
        return $stmt->fetch();
    }

    public function findByUsername($username)
    {
        $stmt = $this->query("SELECT * FROM users WHERE username = ?", [$username]);
        return $stmt->fetch();
    }

    public function create($data)
    {
        $data['password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT);
        unset($data['password']);
        return $this->insert('users', $data);
    }

    public function update($table, $data, $where = 'id = ?', $whereParams = [])
    {
        if (isset($data['password']) && !empty($data['password'])) {
            $data['password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT);
            unset($data['password']);
        }

        return parent::update($table, $data, $where, $whereParams);
    }

    public function delete($table, $where = 'id = ?', $params = [])
    {
        return parent::delete($table, $where, $params);
    }

    public function verifyPassword($user, $password)
    {
        return password_verify($password, $user['password_hash']);
    }
}