<?php


namespace NioModules\CryptoWallet\Controllers;

use App\Rules\TnxRef;
use App\Models\UserTempMeta;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use NioModules\CryptoWallet\Requests\ReferenceRequest;
use NioModules\CryptoWallet\Services\TransactionConfirmationService;

class TransactionConfirmationController extends Controller
{
    private $tnxConfirmationService;

    public function __construct(TransactionConfirmationService $tnxConfirmationService) {
        $this->tnxConfirmationService = $tnxConfirmationService;
    }

    public function depositComplete()
    {
        $tempMeta = UserTempMeta::where('user_id', auth()->id())
                                ->where('meta_key', 'deposit_details')
                                ->first();
        $depositDetails = data_get($tempMeta, 'meta_value');

        if (filled($tempMeta) && filled($depositDetails)) {
            if (data_get($depositDetails, 'flush') == true) {
                $tempMeta->delete();
            } else {
                $depositDetails['flush'] = true;
                $tempMeta->meta_value = $depositDetails;
                $tempMeta->save();
            }
            $depositDetails['tranx'] = (object) $depositDetails['tranx'];
            
            return view('CryptoWallet::payment-address', $depositDetails);
        }

        return redirect()->route('dashboard');
    }

    public function saveReference()
    {
        $request = request();
        $validatedData = $request->validate([
            'reference' => 'required',
            'tnx' => 'required',
        ]);

        $transaction = $this->tnxConfirmationService->findTransaction($validatedData['tnx']);
        $request['reference'] = data_get($request->validate(['reference' => new TnxRef($transaction)]), 'reference');

        if ($transaction->user_id == auth()->user()->id) {
            $this->tnxConfirmationService->saveReference($request, $transaction);

            return response()->json(['msg' => __('Thank you for confirming payment.'), 'redirect' => route('deposit.complete', [
                'status' => 'success',
                'tnx' => the_hash($transaction->id),
            ])]);
        } else {
            throw ValidationException::withMessages(['reference' => __('An error occurred. Please try again.')]);
        }
    }
}
