<?php

namespace App\Livewire\Buttons;

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

class UpdateTopUp extends Component
{

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

    public function mount($uuid)
    {
        $this->uuid = $uuid;
        $token = Session::get('user')['access_token'] ?? null;

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

        // Fetch specific photo slider
        $response = Http::withToken($token)->get(config('services.backend_api.url') . "/api/cms/topUp/{$uuid}");
        if ($response->successful()) {
            $data = $response->json('data');

            $this->fee_code = $data['fee_code'] ?? '';
            $this->name = $data['name'] ?? '';
            $this->amount = $data['amount'] ?? '';
            $this->type = $data['type'] ?? '';

            if (isset($data['type'])) {
                if ($data['type'] === 'PH peso') {
                    $this->type = '1';
                } else {
                    $this->type = '2';
                }

            } else {
                $this->type = '';
            }

        } else {
            $this->addError('users', 'Failed to fetch photo slider.');
        }
    }


    public function submit()
    {

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


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

        $response = Http::withToken($token)->put(config('services.backend_api.url') . '/api/cms/topUp/' . $this->uuid, [
            '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 updated successfully.');
            return redirect('/main/top-up');
        } else {
            $this->addError('top up', 'Failed to update top up.');
        }
    }

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