<?php

namespace NioModules\WdPaypal\Services;

use App\Helpers\NioHash;
use App\Models\UserAccount;
use App\Models\WithdrawMethod;
use Illuminate\Validation\ValidationException;
use NioModules\WdPaypal\WdPaypalModule;

class UserAccountService
{
    public function getWithdrawMethod()
    {
        return WithdrawMethod::where('slug', WdPaypalModule::SLUG)->first();
    }

    public function form($request)
    {
        $method = $this->getWithdrawMethod();

        if (filled($method)) {
            $fallback = isset($method->currencies[0]) ? $method->currencies[0] : '';

            return [
                'actionUrl' => route('user.withdraw.account.'.WdPaypalModule::SLUG.'.save'),
                'currencies' => $method->currencies,
                'default' => data_get($method->config, 'meta.currency', $fallback),
                'quickAdd' => $request->get('quick_added', false),
            ];
        }

        throw ValidationException::withMessages(['unavailable' => __('Method not found.')]);
    }

    public function save($input)
    {
        $input = array_map('strip_tags_map', $input);
        $name = !empty($input['wdm-label']) ? $input['wdm-label'] : 'AC-'.substr(sprintf('%04s', auth()->user()->id), -4, 4).'-'.rand(1001, 9999);
        $config = [ 'email' => $input['wdm-email'], 'currency' => $input['wdm-currency'] ];

        $account = new UserAccount();
        $account->fill([
            'user_id' => auth()->user()->id,
            'slug' => WdPaypalModule::SLUG,
            'name' => $name,
            'config' => $config
        ]);
        $account->save();

        return $account;
    }

    public function find($hash)
    {
        $id = NioHash::toID($hash);

        return UserAccount::where('id', $id)
            ->where('slug', WdPaypalModule::SLUG)
            ->where('user_id', auth()->user()->id)
            ->first();
    }

    public function update($hash, $input)
    {
        $input   = array_map('strip_tags_map', $input);
        $account = $this->find($hash);

        if (blank($account)) {
            throw ValidationException::withMessages([ 'acc' => [0 => __('Invalid Account'), 1 => __('Sorry, account may invalid or not found.')] ]);
        }

        $config  = [ 'email' => $input['wdm-email'], 'currency' => data_get($account, 'config.currency') ];

        $account->update([
            'user_id' => auth()->user()->id,
            'slug' => WdPaypalModule::SLUG,
            'name' => $input['wdm-label'],
            'config' => $config
        ]);

        return $account;
    }

    public function delete($hash)
    {
        $account = $this->find($hash);

        if (blank($account)) {
            throw ValidationException::withMessages([ 'acc' => [0 => __('Invalid Account'), 1 => __('Sorry, account may invalid or not found.')] ]);
        }
        $account->delete();
    }
}
