<?php

namespace App\Livewire\Buttons;

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


class ViewUser extends Component
{

    public $uuid;
    public $username, $firstname, $lastname, $email, $status, $role, $created_at, $updated_at, $created_by, $updated_by;

    public function mount($uuid)
    {
        $this->uuid = $uuid;

        $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/{$uuid}");

        if ($response->successful()) {
            $user = $response->json('data');

            $this->username = $user['username'] ?? '';
            $this->firstname = $user['firstname'] ?? '';
            $this->lastname = $user['lastname'] ?? '';
            $this->email = $user['email'] ?? '';
            $this->status = $user['status'] ?? '';
            $this->role = $user['role'] ?? '';
            $this->created_at = isset($user['created_at']) ? Carbon::parse($user['created_at'])->format('F j, Y g:i A') : '';
            $this->updated_at = isset($user['updated_at']) ? Carbon::parse($user['updated_at'])->format('F j, Y g:i A') : '';

            $this->created_by = $user['created_by'] ?? '';
            $this->updated_by = $user['updated_by'] ?? '';
        } else {
            $this->addError('users', 'Failed to fetch user data.');
        }
    }

    public function render()
    {
        return view('livewire.buttons.view-user');
    }
}
