<?php

namespace App\Livewire\Gateway;

use App\Models\UserVirtualAccount;
use App\Services\UserService;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;

class VirtualAccounts extends Component
{
    use LivewireAlert;

    public $bvn;

    public function mount()
    {
        $this->bvn = auth()->user()->bvn;
    }

    public function generate(UserService $userService)
    {
        $this->validate([
            'bvn' => 'required|digits:11',
        ]);

        $res = $userService->generateAccountNumber(auth()->user(), $this->bvn);
        if (($res['status'] ?? null) !== 'success') {
            $this->alert('error', $res['message'] ?? 'Unable to generate virtual account');
            return;
        }

        $data = $res['data'] ?? [];
        $accountNumber = $data['account_number'] ?? $data['accountNo'] ?? $data['accountnumber'] ?? null;
        $bankName = $data['bank_name'] ?? $data['bankName'] ?? ($data['bank']['name'] ?? null);
        $bankCode = $data['bank_code'] ?? $data['bankCode'] ?? ($data['bank']['code'] ?? null);
        if (!is_string($bankCode) || trim($bankCode) === '') {
            $bankCode = '000000';
        }

        if (!is_string($accountNumber) || $accountNumber === '' || !is_string($bankName) || $bankName === '') {
            $this->alert('error', 'Virtual account response is missing required fields');
            return;
        }

        UserVirtualAccount::updateOrCreate(
            ['user_id' => auth()->id()],
            [
                'account_number' => $accountNumber,
                'bank_name' => $bankName,
                'bank_code' => $bankCode,
                'account_name' => $data['account_name'] ?? (auth()->user()->first_name . ' ' . auth()->user()->last_name),
                'external_id' => $data['order_ref'] ?? $data['tx_ref'] ?? auth()->user()->email,
            ]
        );

        $this->alert('success', 'Virtual account generated successfully');
    }

    public function render()
    {
        return view('livewire.gateway.virtual-accounts', [
            'virtualAccount' => auth()->user()->virtualAccount,
        ])->title('Virtual Accounts');
    }
}
