<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class UserManagement extends Component
{
    public $users = [];

    public function mount()
    {
        $this->loadUsers();
    }

    public function loadUsers()
    {
        try {
            $token = Session::get('user')['access_token'] ?? null;

            if (!$token) {
                $this->addError('users', 'No access token found.');
                return;
            }

            $response = Http::withToken($token)
                ->get(config('services.backend_api.url') . '/api/cms/admin');

            // dd($response->json());
            if ($response->successful()) {
                // Properly use collect to handle the response data
            $this->users = collect($response->json()['data'])->map(function ($user) {
                return [
                    'admin_uuid' => $user['admin_uuid'],
                    'username' => $user['username'],
                    'firstname' => $user['firstname'],
                    'lastname' => $user['lastname'],
                    'email' => $user['email'],
                    'role' => $user['role'] == 1 ? 'Admin' : 'Marketing Personnel',
                    'status' => $user['status'] == 'active' ? 'Active' : 'Inactive',
                ];
            });

            } else {
                $this->addError('users', 'Failed to load users.');
            }
        } catch (\Exception $e) {
            $this->addError('users', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.user-management.user-management', [
            'users' => $this->users,  // Pass all users to the table
        ]);
    }
}
