<?php
require_once __DIR__ . '/../config/database.php';
class User {
    private $pdo;
    public function __construct(){ $this->pdo = Database::getInstance(); }

    public function getByUsername($username) {
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE username = ?');
        $stmt->execute([$username]); return $stmt->fetch();
    }

    public function all() {
        $stmt = $this->pdo->query('SELECT * FROM users ORDER BY created_at DESC');
        return $stmt->fetchAll();
    }

    public function get($id) {
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$id]); return $stmt->fetch();
    }

    public function create($username, $password, $fullname='', $role='user') {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $this->pdo->prepare('INSERT INTO users (username,password,fullname,role) VALUES (?,?,?,?)');
        return $stmt->execute([$username, $hash, $fullname, $role]);
    }

    public function update($id, $username, $password, $fullname='', $role='user') {
        if (!empty($password)) {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $this->pdo->prepare('UPDATE users SET username=?, password=?, fullname=? WHERE id=?');
            return $stmt->execute([$username, $hash, $fullname, $id]);
        } else {
            $stmt = $this->pdo->prepare('UPDATE users SET username=?, fullname=?, role=? WHERE id=?');
            return $stmt->execute([$username, $fullname, $role, $id]);
        }
    }

    public function delete($id) {
        $stmt = $this->pdo->prepare('DELETE FROM users WHERE id = ?');
        return $stmt->execute([$id]);
    }
}
?>