<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Jobs\SendEmailJob;
use App\Mail\Withdrawal;
use App\Models\AdminWithdrawal;
use App\Models\User;
use App\Models\UserDeposits;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class APIController extends Controller
{
    /**
     * WithdrawalBlog Process.
     *
     * @param Request $request
     * @return JsonResponse
     */
    // SavingController
    public function withdrawalComplete(Request $request)
    {

        $req = $request->only('data', 'status', 'transactionHash');

        Log::info("req");
        Log::info($req);
        $hash = $req['data']['transactionHash'] ?? "";
        $userDeposit = UserDeposits::where('reference', $req['data']['reference'])->orWhere('reference', $hash)->first();
        if (!$userDeposit) {
            $userDeposit = AdminWithdrawal::where('reference', $req['data']['reference'])->orWhere('reference', $hash)->first();
        }
        if (!$userDeposit) {
            Log::info("NO REF FOUND PLEASE SECURE SYSTEM" . $req['data']['reference']);
            return response()->json(['status' => true]);
        }
        if (isset($req['status']) && $req['status']) {
            $userDeposit->status = 1;
            $userDeposit->meta_data = $req['data'];
            $userDeposit->reference = $req['data']['transactionHash'];

            $userDeposit->save();
            $msg = "Your Withdrawal request is completed";
            $user = User::find($userDeposit->user_id);
            $details = [
                'name' => $user->name,
                'msg' => $msg,
                'subject' => "Withdrawal Request",
            ];
            $emailSwitch = getEmailSettings('withdrawal');
            if($emailSwitch == 'on'){
                $emailClassRef = new Withdrawal($details);
                SendEmailJob::dispatch($user->email, $emailClassRef);
            }
        } elseif (!$req['status'] && isset($req['transactionHash'])) {
            $userDeposit->reference = $req['transactionHash'];

            $userDeposit->save();
        } else {
            $userDeposit->status = 3;
            $userDeposit->save();
            $msg = "Your Withdrawal request is failed please contact support.";
            $user = User::find($userDeposit->user_id);
            $details = [
                'name' => $user->name,
                'msg' => $msg,
                'subject' => "Withdrawal Request",
            ];
            $emailSwitch = getEmailSettings('withdrawal');
            if($emailSwitch == 'on'){
                $emailClassRef = new Withdrawal($details);
                SendEmailJob::dispatch($user->email, $emailClassRef);
            }

        }

        return response()->json(['status' => true]);
    }
}
