<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Withdrawal;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class AdminWithdrawalManagementController extends Controller
{
    public function WithdrawalManagement()
    {
        $withdrawals = Withdrawal::with(['user'])->latest()->paginate(10);
        return view('adminDashboard.withdrawal-management', compact('withdrawals'));
    }

    public function WithdrawalInfo(Request $request)
    {
        $request->validate([
            'id' => 'required'
        ]);
        $withdrawal = Withdrawal::where(['id' => $request->id])->with(['bank'])->first();
        $user = User::where(['id' => $withdrawal->user_id])->first();
        $total_interest = $user->userTotalInterests();
        $total_bonus = $user->totalBonusesAmount();
        $total_commission = $user->userTotalCommissions();
        $total_recharge = $user->getTotalRecharge();
        $total_withdrawal = $user->userTotalwithdrawal();
        $total_betting = $user->userBettingWonAmount();
        $total_bet = $user->userTotalBet();

        if ($withdrawal) {
            return response()->json(['status' => 'success', 'withdrawal' => $withdrawal->bank, 'withdrawal_status' => $withdrawal->status, 'rejection_reason' => $withdrawal->rejection_reason, 'total_bonus' => $total_bonus, 'total_interest' => $total_interest, 'total_commission' => $total_commission, 'total_recharge' => $total_recharge, 'total_withdrawal' => $total_withdrawal, 'total_betting' => $total_betting, 'total_bet' => $total_bet]);
        } else {
            return response()->json(['status' => 'error']);
        }
    }

    public function AgreeWithdrawal($id)
    {
        Withdrawal::find($id)->update(['status' => 3]);
        return redirect()->back();
    }

    //API WITHRAWAL START HERE
    private function acceptRequestApiUPIMoney($id)
    {
        $withdrawal = Withdrawal::where('id', $id)
            ->with('user', 'bank')
            ->first();
        $user = $withdrawal->user;
        $bank = $withdrawal->bank;

        $client = new Client();
        $url = 'https://upimoney.co.in/api/payout/transaction';
        $data = [
            'token' => env('GATEWAY_UPI_MONEY_API_TOKEN'),
            'type' => 'bank',
            'name' => $bank->name,
            'bank' => $bank->bank_name,
            'account' => $bank->account,
            'ifsc' => $bank->ifsc,
            'mode' => 'IMPS',
            'mobile' => $user->mobile,
            'email' => $user->mobile . '@gmail.com',
            'address' => 'delhi',
            'apitxnid' => Str::random(12),
            'amount' => $withdrawal->payout
        ];

        try {
            $response = $client->post($url, [
                'json' => $data
            ]);

            $body = $response->getBody()->getContents();
            $parsedResponse = json_decode($body, true);
            Log::info($parsedResponse);

            if (isset($parsedResponse['statuscode'])) {
                $statuscode = $parsedResponse['statuscode'];
                if (isset($parsedResponse['message']))
                    $api_message = $parsedResponse['message'];
                else $api_message = "No Message Found";


                if ($statuscode == 'ERR') {
                    $message = "API Error: " . $api_message;
                    return $message;
                } elseif ($statuscode == 'TXN') {
                    $status = $parsedResponse['status'];
                    if ($status == 'inprocess') {
                        if ($withdrawal && $withdrawal->status == 2) {
                            User::where(['id' => $withdrawal->user_id])->decrement('amount', $withdrawal->amount);
                        }
                        $withdrawal->status = 1;
                        $withdrawal->save();
                        $message = "Payment Request sent to API. Message from API: " . $api_message;
                        return $message;
                    } else {
                        $message = "Unknown Status, Please Contact Support, Status Code is: " . $status;
                        return $message;
                    }
                } else {
                    $message = "API Error, Invalid Status message, Status Code is: " . $statuscode;
                    return $message;
                }
            } else {
                $message = "API Error, Invalid Status message, Status Code is: ";
                return $message;
            }
        } catch (\Exception $e) {
            $error = $e->getMessage();
            $message = "API Error: " . $error;
            return $message;
        }
    }


    public function ApproveWithdrawalApi($id)
    {
        if (!env('ENABLE_PAYOUT')) return redirect()->back()->with('success', 'Payout is disabled');
        if (env('PAYOUT_API_NAME') === 'upi_money') {
            $message = $this->acceptRequestApiUPIMoney($id);
            return back()->with('success', $message);
        } else {
            return back()->with('success', 'Payout API is not configured');
        }
    }
    //API WITHRAWAL END HER

    public function ApproveWithdrawal($id)
    {
        $withdrawal = Withdrawal::find($id);
        if ($withdrawal && $withdrawal->status == 2) {
            User::where(['id' => $withdrawal->user_id])->decrement('amount', $withdrawal->amount);
            $withdrawal->status = 1;
            $withdrawal->save();
        } elseif ($withdrawal && $withdrawal->status != 1) {
            Withdrawal::find($id)->update(['status' => 1]);
        }
        return redirect()->back();
    }

    public function DisapproveWithdrawal(Request $request)
    {
        $request->validate([
            'reject_id' => 'required',
            'reason' => 'required'
        ]);
        $withdrawal = Withdrawal::find($request->reject_id);
        if ($withdrawal && $withdrawal->status == 2) {
            $withdrawal->rejection_reason = $request->reason;
            $withdrawal->save();
        } elseif ($withdrawal) {
            User::where(['id' => $withdrawal->user_id])->increment('amount', $withdrawal->amount);
            $withdrawal->rejection_reason = $request->reason;
            $withdrawal->status = 2;
            $withdrawal->save();
        }
        return redirect()->back();
    }

    public function DeleteWithdrawal($id)
    {
        $withdrawal = Withdrawal::find($id);
        if ($withdrawal && ($withdrawal->status == 0 || $withdrawal->status == 3)) {
            User::where(['id' => $withdrawal->user_id])->increment('amount', $withdrawal->amount);
        }
        $withdrawal->delete();
        return redirect()->back();
    }

    public function WithdrawalHistory(Request $request)
    {
        $request->validate([
            'user_mobile' => 'required'
        ]);
        $withdrawals = Withdrawal::with(['user'])->whereRelation('user', 'mobile', 'like', '%' . $request->user_mobile . '%')->latest()->limit(100)->get();
        foreach ($withdrawals as $key => $withdrawal) {
            $withdrawals[$key]->created = date_format($withdrawal->created_at, "Y-m-d H:i:s");
        }
        return response()->json(['status' => 'success', 'withdrawals' => $withdrawals]);
    }
}
