<?php

namespace App\Livewire\Buttons;

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

class CreateUser extends Component
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $status = 'active';
    public $role = 'admin';
    public $default_password = '';

    public function generatePassword()
    {
        try {
            // Get the access token from the session
            $token = Session::get('user')['access_token'] ?? null;

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

            // Make the request to generate the password
            $response = Http::withToken($token)
                ->post(config('services.backend_api.url') . '/api/cms/generatePassword');

            // Check if the request was successful
            if ($response->successful()) {
                // Retrieve the password from the response
                $this->default_password = $response->json()['data']['password'];
            } else {
                $this->addError('users', 'Failed to generate password.');
            }
        } catch (\Exception $e) {
            // Handle any exceptions that occur during the request
            $this->addError('users', 'Error: ' . $e->getMessage());
        }
    }

    public function submit()
    {

        $token = Session::get('user')['access_token'] ?? null;
        

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

        $response = Http::withToken($token)->post(config('services.backend_api.url') . '/api/cms/admin', [
            'username'   => $this->username,
            'firstname'  => $this->firstname,
            'lastname'   => $this->lastname,
            'email'      => $this->email,
            'status'     => $this->status,
            'role'       => $this->role,
            'password'   => $this->default_password,
        ]);

        // dd($response->json());


        //handle backend response
        if ($response->status() === 422) {
            $errors = $response->json('data');
            foreach ($errors as $field => $messages) {
                $this->addError($field, $messages[0]);
            }
            return;
        }

        if ($response->successful()) {
            session()->flash('success', 'User created successfully.');
            return redirect('/main/user-management');
        } else {
            $this->addError('users', 'Failed to create user.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/user-management');
    }

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