<?php

namespace App\Repositories;

final class UserRepository extends BaseRepository
{
    public function all(): array
    {
        $params = [];
        $sql = 'SELECT id, name, email, role, active, created_at FROM users';
        if (!empty($_GET['role'])) {
            $sql .= ' WHERE role = :role';
            $params['role'] = $_GET['role'];
        }
        $sql .= ' ORDER BY created_at DESC, id DESC';
        return $this->paginate($sql, $params);
    }

    public function create(array $data): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO users (name, email, password_hash, role, active)
             VALUES (:name, :email, :password_hash, :role, :active)'
        );
        $stmt->execute([
            'name' => $data['name'],
            'email' => $data['email'],
            'password_hash' => password_hash($data['password'], PASSWORD_BCRYPT),
            'role' => $data['role'],
            'active' => (int) ($data['active'] ?? 1),
        ]);

        return $this->find((int) $this->db->lastInsertId());
    }

    public function update(int $id, array $data): ?array
    {
        $fields = [];
        $params = ['id' => $id];
        foreach (['name', 'email', 'role', 'active'] as $field) {
            if (array_key_exists($field, $data)) {
                $fields[] = "$field = :$field";
                $params[$field] = $field === 'active' ? (int) $data[$field] : $data[$field];
            }
        }
        if (!empty($data['password'])) {
            $fields[] = 'password_hash = :password_hash';
            $params['password_hash'] = password_hash($data['password'], PASSWORD_BCRYPT);
        }
        if (!$fields) {
            return $this->find($id);
        }

        $stmt = $this->db->prepare('UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = :id');
        $stmt->execute($params);
        return $this->find($id);
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT id, name, email, role, active, created_at FROM users WHERE id = :id');
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }
}
