<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\PaymentMethod;
use App\Models\Usdt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use function GuzzleHttp\Promise\all;

class OnepayController extends Controller
{
    public function index()
    {
        return view('app.main.recharge.index');
    }

    public function depositSubmit(Request $request)
    {
//        $validate = Validator::make($request->all(), [
//            'aca' => 'required',
//            'amount' => 'required',
//            'oid' => 'required',
//            'tid' => 'required',
//        ]);
//
//        if ($validate->fails()) {
//            return response()->json(['status'=> false, 'errors'=> $validate->errors()]);
//        }

        try {
            $oid = base64_decode($request->oid);

            //Deposit check
            $depositCheckWithOid = Deposit::where('order_id', $oid)->first();
            if ($depositCheckWithOid){
                return response()->json(['status'=> false, 'message'=> 'ordered']);
            }

            $model = new Deposit();
            $model->user_id = $request->ui;

            $model->method_name = mb_convert_encoding(base64_decode($request->pm), 'UTF-8', 'UTF-8');
            $model->number = mb_convert_encoding(base64_decode($request->aca), 'UTF-8', 'UTF-8');
            $model->order_id = mb_convert_encoding($oid, 'UTF-8', 'UTF-8');
            $model->transaction_id = mb_convert_encoding(base64_decode($request->tid), 'UTF-8', 'UTF-8');
            $model->amount = mb_convert_encoding(base64_decode($request->amount), 'UTF-8', 'UTF-8');
            $model->final_amount = mb_convert_encoding(base64_decode($request->amount), 'UTF-8', 'UTF-8');
            $model->date = date('d-m-Y H:i:s');
            $model->status = mb_convert_encoding('pending', 'UTF-8', 'UTF-8');
            $model->save();

            return response()->json(['status'=> true, 'message'=> 'success']);
        }catch (\Exception $exception){
            return response()->json(['status'=> false, 'message'=> $exception->getMessage()]);
        }
    }

    public function return_number($type)
    {
        $number = DB::table('payment_methods')->where('type', $type)->where('status', 'active')->inRandomOrder()->first();
        if ($number){
            $number = $number->number;
            return response()->json(['status'=> true, 'number'=> $number, 'message'=> $type. 'Available']);
        }else{
            return response()->json(['status'=> false, 'message'=> $type. 'Not processable']);
        }
    }
}
