<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Admin\AdminRechargeManagementController;
use App\Models\RechargeSummery;
use App\Models\UpiTransaction;
use App\Models\User;
use App\Models\Website;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use function PHPUnit\Framework\isNull;

class TransactionController extends Controller
{
    //SUBMIT PAYMENT CALLBACKS START
    public function SubmitGatewayPaymentUPIMoney(Request $request)
    {
        // Log::error($request->all());
        if (!isset($request->apitxnid)) {
            return response()->failed('Transaction ID is required');
        }
        $amount = $request->amount;
        $client_txn_id  = $request->apitxnid;

        $transactino_check = UpiTransaction::where('client_txn_id', trim($client_txn_id))
            ->with('user')
            ->first();
        if ($transactino_check === NULL) {
            return 'Transaction Not Found';
        }

        if ($request->status != 'success') {
            return 'Transaction Failed';
        }

        $user = $transactino_check->user;
        if ($user === NULL) {
            return response()->failed('User Not Found');
        }

        $user->amount = $user->amount + $amount;
        $user->update();

        $wallet_summary = new RechargeSummery();
        $wallet_summary->user_id = $transactino_check->user_id;
        $wallet_summary->status = 1;
        $wallet_summary->amount = $amount;
        $wallet_summary->type = 'ONLINE_PAYMENT_UPI_MONEY';
        $wallet_summary->save();

        return 'Transaction Done';
    }

    public function SubmitGatewayPayment(Request $request)
    {
        if (!isset($request->client_txn_id)) {
            return 'Transaction ID is required';
        }

        $amount = $request->amount;
        $client_txn_id  = $request->client_txn_id;
        $customer_email = $request->customer_email;
        $customer_mobile = $request->customer_mobile;
        $customer_name = $request->customer_name;
        $customer_vpa = $request->customer_vpa;
        $upi_txn_id = $request->upi_txn_id;

        $transactino_check = UpiTransaction::where('client_txn_id', trim($client_txn_id))
            ->first();
        if ($transactino_check === NULL) {
            return 'Transaction Not Found';
        }

        $user = $transactino_check->user;
        if ($user === NULL) {
            return 'User Not Found';
        }

        if ($request->status != 'success') {
            return 'Failed Payment';
        }

        $user_id = $transactino_check->user_id;

        // Check and give the first-time recharge bonus
        $isFirstTimeBonusGiven = AdminRechargeManagementController::giveFirstTimeBonus($user_id, $amount);

        // If the first-time bonus was not applicable, simply increment the user's amount
        if (!$isFirstTimeBonusGiven) {
            $user = User::where(['id' => $user_id])->first();
            $user->increment('amount', $amount);
        }

        // Check and give referral bonus if applicable
        if ($user && $user->rcode != null) {
            $bonusController = new AdminRechargeManagementController();
            $bonusController->giveBonus($user->rcode, $amount, $user->id);
        }

        $wallet_summary = new RechargeSummery();
        $wallet_summary->user_id = $transactino_check->user_id;
        $wallet_summary->status = 1;
        $wallet_summary->amount = $amount;
        $wallet_summary->type = 'ONLINE_PAYMENT_UPI_GATEWAY';
        $wallet_summary->save();

        return 'Transaction Done';
    }
    //SUBMIT PAYMENT CALLBACKS END


    //GET PAYMENT URI/URL API START
    public function RedirectUrl($amount)
    {
        $customer_name = 'John Doe';
        $customer_email = Auth::user()->mobile . '@gmail.com';
        $customer_mobile = Auth::user()->mobile;
        $client_txn_id = $this->generateRandomString(9);
        $upi_gateway_api = Website::find(1)->upi_gateway_api;
        $upi_trans = new UpiTransaction();
        $upi_trans->user_id = Auth::user()->id;
        $upi_trans->client_txn_id = $client_txn_id;
        $upi_trans->save();
        $fields = [
            "key" => $upi_gateway_api,
            "client_txn_id" => $client_txn_id,
            "amount" => $amount,
            "p_info" => env('APP_NAME') . "Website Payment",
            "customer_name" => $customer_name,
            "customer_email" => $customer_email,
            "customer_mobile" => $customer_mobile,
            "redirect_url" => env('APP_URL') . "/user/rechargeRecord",
            "udf1" => "user defined field 1",
            "udf2" => "user defined field 2",
            "udf3" => "user defined field 3",
        ];
        $http_request = Http::withHeaders([
            "Content-Type" => "application/json",
        ])->post("https://merchant.upigateway.com/api/create_order", $fields);
        $response = $http_request->json();
        Log::error($response);
        if (!$http_request->ok()) {
            return response()->json(['status'   =>  'error', 'message'    =>  "Something went wrong!"]);
        } else {
            if (!$response['status']) {
                return response()->json(['status'   =>  'error', 'message'    =>  $response['msg']]);
            }
            return response()->json(['status'   =>  'success', 'url' => $response["data"]["payment_url"]]);
        }
    }

    public function RedirectUrlUPIMoney($amount)
    {

        $customer_name = 'John Doe';
        $customer_email = Auth::user()->mobile . '@gmail.com';
        $customer_mobile = Auth::user()->mobile;
        $client_txn_id = $this->generateRandomString(9);
        $upi_gateway_api = Website::find(1)->upi_gateway_api;

        $upi_trans = new UpiTransaction();
        $upi_trans->user_id = Auth::user()->id;
        $upi_trans->client_txn_id = $client_txn_id;
        $upi_trans->save();

        $call_back_url = env('APP_URL') . '/api/submit-gateyway-payment-upi-money';
        $fields = [
            'token' => env('GATEWAY_UPI_MONEY_API_TOKEN'),
            'type' => 'upi',
            'mobile' => $customer_mobile,
            'name' => $customer_name,
            'email' => $customer_email,
            'callback' => $call_back_url,
            'apitxnid' => $client_txn_id,
            'amount' => $amount,
        ];

        try {
            $http_request = Http::withHeaders([
                "Content-Type" => "application/json",
            ])->get("https://upimoney.co.in/api/payin/transaction", $fields);
            $response = $http_request->json();


            if (!$http_request->ok()) {
                $message = "Something went wrong!";
                return response()->json(['status'   =>  'error', 'message'    =>  $message]);
            } else {
                if (
                    isset($response['status']) && ($response['status'] == 'ERR' || $response['status'])
                ) {
                    if (isset($response['message'])) $message = $response['message'];
                    elseif (isset($response['msg'])) $message = $response['msg'];
                    else $message = "Something went wrong!";
                    return response()->json(['status'   =>  'error', 'message'    =>  $message]);
                } elseif (
                    isset($response['statuscode']) && ($response['statuscode'] == 'ERR')
                ) {
                    if (isset($response['message'])) $message = $response['message'];
                    elseif (isset($response['msg'])) $message = $response['msg'];
                    else $message = "Something went wrong!";
                    return response()->json(['status'   =>  'error', 'message'    =>  $message]);
                }

                $payment_link = $response['upiString']['payment_url'];
                return response()->json(['status'   =>  'success', 'url' => $payment_link]);
            }
        } catch (\Exception $e) {
            return response()->json(['status'   =>  'error', 'message'    =>  $e->getMessage()]);
        }
    }
    //GET PAYMENT URI/URL API END

    function generateRandomString($length = 10)
    {
        $characters = '0123456789';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function Transactions()
    {
        $user_data = User::where(['id' => Auth::user()->id])->with(['commissions', 'bonuses', 'interests'])->first();
        return view('userDashboard.transactions', compact('user_data'));
    }
}
