<?php

namespace App\Livewire\Account;

use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Layout('components.layouts.account-inner', ['title' => 'KYC'])]
class Verification extends Component {
    
    use WithFileUploads;

    #[Validate('required|max:4092|mimes:png,jpg,jpeg,gif')]
    public $file;

    public $active_document;

    public function render() {
        $user = auth_user();

        $this->active_document = !
            $user->verification?->id_front
            ? 'id_front'
            : (!$user->verification?->id_back ? 'id_back'
            : (!$user->verification?->proof_of_residence ? 'proof_of_residence' : null));

        return view('livewire.account.verification', [
            'convert' => fn($text) => $this->convert($text),
            'user' => $user
        ]);
    }

    public function updated($prop) {
        $this->validateOnly($prop);
        if ($prop == 'file') {
            
            $user = auth_user();

            $document = $this->file->store('photos', 'public');

            try {
                $user->verification()->updateOrCreate([
                    'user_id' => $user->id,
                ], [
                    $this->active_document => $document,
                ]);
                
                $this->dispatch('refresh');
            } catch (\Throwable $_) {
                $this->dispatchAlert('Something went wrong, please try again later', 'error');
            }
        }
    }

    public function save() {
        $this->validate();

        $user = auth_user();

        if (!$user->verification?->id_front) {
            $this->file->store('photos', 'public');
            $this->active_document = 'Back ID';
        }
    }

    function convert($text) {
        $text = convert_text($text);
        $active = explode(' ', $text);
        return $active[0] == 'Id' ? $active[1] : $text;
    }
}
