<?php

namespace NioModules\WdPaypal\Controllers;

use NioModules\WdPaypal\WdPaypalModule;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use NioModules\WdPaypal\Requests\SaveUserAccountRequest;
use NioModules\WdPaypal\Requests\UpdateUserAccountRequest;
use NioModules\WdPaypal\Services\UserAccountService;

class UserAccountController extends Controller
{
    private $accountService;
    public function __construct(
        UserAccountService $accountService
    ) {
        $this->accountService = $accountService;
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @version 1.0.0
     * @since 1.0
     */
    public function form()
    {
        $request = request();
        if ($request->ajax()) {
            return view('WdPaypal::account-form', $this->accountService->form($request));
        }
    }

    /**
     * @param Request $request
     * @version 1.0.0
     * @since 1.0
     */
    public function save(SaveUserAccountRequest $request)
    {
        $this->accountService->save($request->validated());

        if ($request->get('quick_added') == 'yes') {
            return redirect()->route('withdraw.redirect.amount');
        }

        return response()->json(["msg" => __('Your PayPal account successfully added.'), "msg_title" => __('Account Added')]);
    }

    public function edit($hash)
    {
        $method = $this->accountService->getWithdrawMethod();
        $currencies = $method->currencies;
        $fallback = isset($method->currencies[0]) ? $method->currencies[0] : '';
        $default = data_get($method->config, 'meta.currency', $fallback);
        $userAccount = $this->accountService->find($hash);

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

        $actionUrl = route('user.withdraw.account.' . WdPaypalModule::SLUG . '.update', ['id' => $hash]);
        $quickAdd = false;

        return view('WdPaypal::account-form', compact('userAccount', 'currencies', 'default', 'actionUrl', 'quickAdd'));
    }

    public function update($hash, UpdateUserAccountRequest $request)
    {
        $this->accountService->update($hash, $request->validated());

        return response()->json(["reload" => 1500, "msg" => __('The PayPal account successfully updated.'), "msg_title" => __('Account Updated')]);
    }

    public function delete($hash)
    {
        $this->accountService->delete($hash);

        return response()->json(['msg' => __('The account successfully deleted.'), "msg_title" => __('Account Deleted')]);
    }
}
