<?php
class User extends Model
{
    public function all(): array
    {
        return $this->fetchAll('SELECT users.*, roles.name AS role_name FROM users LEFT JOIN roles ON users.role_id = roles.id ORDER BY users.id ASC');
    }

    public function findByEmail(string $email): ?array
    {
        return $this->fetch('SELECT * FROM users WHERE email = :email LIMIT 1', ['email' => $email]);
    }

    public function findById(int $id): ?array
    {
        return $this->fetch('SELECT * FROM users WHERE id = :id LIMIT 1', ['id' => $id]);
    }

    public function create(array $data): bool
    {
        $sql = 'INSERT INTO users (role_id, name, email, password_hash, phone, status) VALUES (:role_id, :name, :email, :password_hash, :phone, :status)';
        return $this->execute($sql, [
            'role_id' => (int)($data['role_id'] ?? 1),
            'name' => $data['name'],
            'email' => $data['email'],
            'password_hash' => $data['password_hash'],
            'phone' => $data['phone'] ?? null,
            'status' => $data['status'] ?? 'Active',
        ]);
    }

    public function updateById(int $id, array $data): bool
    {
        $fields = [];
        $params = ['id' => $id];

        if (isset($data['name'])) {
            $fields[] = 'name = :name';
            $params['name'] = $data['name'];
        }
        if (isset($data['email'])) {
            $fields[] = 'email = :email';
            $params['email'] = $data['email'];
        }
        if (isset($data['phone'])) {
            $fields[] = 'phone = :phone';
            $params['phone'] = $data['phone'];
        }
        if (isset($data['status'])) {
            $fields[] = 'status = :status';
            $params['status'] = $data['status'];
        }
        if (isset($data['password_hash'])) {
            $fields[] = 'password_hash = :password_hash';
            $params['password_hash'] = $data['password_hash'];
        }
        if (isset($data['role_id'])) {
            $fields[] = 'role_id = :role_id';
            $params['role_id'] = (int)$data['role_id'];
        }

        if (empty($fields)) {
            return false;
        }

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

    public function delete(int $id): bool
    {
        return $this->execute('DELETE FROM users WHERE id = :id', ['id' => $id]);
    }
}
