<?php

namespace App\Livewire\Buttons;

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

class CreateTopUp extends Component
{

    public $fee_code;
    public $name;
    public $amount;
    public $type;

    public function generateFeeCode()
    {
        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)
                ->get(config('services.backend_api.url') . '/api/cms/generateFeeCode');

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

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

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


    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/topUp', [
            'fee_code'   => $this->fee_code,
            'name'   => $this->name,
            'amount'   => $this->amount,
            'type'      => $this->type,
        ]);

        // 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', 'Top Up created successfully.');
            return redirect('/main/top-up');
        } else {
            $this->addError('top up', 'Failed to create user.');
        }
    }

    public function cancel()
    {
        return redirect()->to('/main/top-up');
    }
    public function render()
    {
        return view('livewire..buttons.create-top-up');
    }
}
