<?php

namespace App\Http\Controllers\Web\Current\Admin;

use App\Events\TradeUpdatedEvent;
use App\Events\UserUpdatedEvent;
use App\Helpers\FilterHelper;
use App\Helpers\SettingsHelper;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessUserAccountBalance;
use App\Models\Asset;
use App\Models\TopTrader;
use App\Models\Trade;
use App\Models\TradeBot;
use App\Models\TradePrediction;
use App\Models\TradingAccount;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Inertia\Inertia;

use App\Services\ExpoService;

use App\Models\User;
use App\Models\UserCopyTrader;
use App\Models\UserNote;
use App\Models\UserTradeBot;
use App\Models\UserWalletTransaction;
use App\Notifications\UserNotification;
use Exception;

class UserController extends Controller
{
    private $priv;

    public function __construct() {}

    public function index(Request $request)
    {
        if ($request->has('delete_staff')) {
            if ($request->staff_id == 1) {
                return redirect()
                    ->back()
                    ->with('poperror', "You cannot delete top admin");
            }

            $record = User::find($request->staff_id);
            if ($record) {
                $record->delete();

                return redirect()
                    ->back()
                    ->with('popsuccess', "Staff Deleted");
            }
        }

        $users = User::orderBy("id", "desc")->get();
        $u = $users->map(function ($user) {
            return [
                "id" => $user->id,
                "uuid" => $user->uuid,
                "firstname" => $user->firstname,
                "lastname" => $user->lastname,
                "email" => $user->email,
                "mobile" => $user->mobile,
                "state" => $user->state,
                "ref_code" => $user->ref_code,
                "wallet_balance" => $user->wallet_balance,
            ];
        });

        return view("admin.users", [
            "page_title" => 'Users',
            "users" => $users
        ]);
    }

    public function view_user($user_id, Request $request)
    {
        $user = User::where("id", $user_id)->orWhere("username", $user_id)->first();
        if ($user) {

            if ($request->has('delete_user')) {
                $user->delete();

                return redirect()
                    ->back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->has('quick_login')) {
                $user->quick_token = str()->uuid();
                $user->save();

                $url = env('WEBAPP_URL')."/quiczalogin/$user->quick_token";

                header("Location: $url");
                exit();
            }

            if ($request->has('toggle_block')) {
                if ($user->is_blocked == 1) {
                    $user->is_blocked = 0;
                } else {
                    $user->is_blocked = 1;
                }
                $user->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return redirect()
                    ->back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->has('toggle_verified')) {
                if ($user->is_verified == 1) {
                    $user->is_verified = 0;
                } else {
                    $user->is_verified = 1;
                }
                $user->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return redirect()
                    ->back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->has('toggle_copy')) {
                if ($user->can_copy == 1) {
                    $user->can_copy = 0;
                } else {
                    $user->can_copy = 1;
                }
                $user->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return redirect()
                    ->back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->has('toggle_open_account')) {
                if ($user->can_open_account == 1) {
                    $user->can_open_account = 0;
                } else {
                    $user->can_open_account = 1;
                }
                $user->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return redirect()
                    ->back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->has('edit_trader')) {

                $this->validate($request, [
                    'trader_id' => 'required',
                    'balance' => 'required',
                ]);

                $t = TradingAccount::find($request->trader_id);


                if ($t) {
                    $t->balance = FilterHelper::amount($request->balance);
                    $t->save();

                    try {
                        UserUpdatedEvent::broadcast($user->id, []);
                    } catch (\Exception) {
                    }

                    return back()->with('Success', "Operation Successful");
                } else {
                    return back()->with('error', "Account not found");
                }
            }

            if ($request->has('create_mul_predictions')) {

                $this->validate($request, [
                    'market' => 'required',
                    'min_amount' => 'required',
                    'max_amount' => 'required',
                    'trade_type' => 'required',
                    'num_of_predictions' => 'required',
                ]);

                $min_amount = FilterHelper::amount($request->min_amount);
                $max_amount = FilterHelper::amount($request->max_amount);

                for ($i = 0; $i < $request->num_of_predictions; $i++) {
                    $amount = mt_rand($min_amount, $max_amount);
                    $asset = Asset::where("market", $request->market)->get()->random(1)->first();
                    $rand = rand(1, 100);

                    if ($rand < 50) {
                        $trade_action = "up";
                    } else {
                        $trade_action = "down";
                    }

                    TradePrediction::create([
                        "uuid" => mt_rand(111_111, 999_999),
                        "market" => $request->market,
                        "symbol" => $asset->symbol,
                        "amount" => $amount,
                        "order_type" => 'market',
                        "trade_type" => $request->trade_type,
                        "trade_action" => $trade_action,
                        "trade_time" => $request->trade_time,
                        "entry_price" => FilterHelper::randomMinMax($asset->low_point, $asset->high_point),
                        "result" => 'win',
                        "user_id" => $user->id,
                    ]);
                }

                return redirect()
                    ->back()
                    ->with('success', "Operation Successful");
            }

            if ($request->has('add_copy_trading')) {

                $this->validate($request, [
                    'toptrader_id' => 'required',
                    'rule' => 'required',
                    'amount' => 'required',
                    'status' => 'required',
                ]);

                $t = new UserCopyTrader();
                $t->toptrader_id = $request->toptrader_id;
                $t->user_id = $request->user_id;
                $t->rule = $request->rule;
                $t->status = $request->status;
                $t->amount = FilterHelper::amount($request->amount);
                $t->save();

                return back()->with('Success', "Operation Successful");
            }

            if ($request->has('edit_copy_trading')) {

                $this->validate($request, [
                    'c_id' => 'required',
                    'rule' => 'required',
                    'amount' => 'required',
                    'status' => 'required',
                ]);

                $t = UserCopyTrader::find($request->c_id);


                if ($t) {
                    $t->rule = $request->rule;
                    $t->status = $request->status;
                    $t->amount = FilterHelper::amount($request->amount);
                    $t->save();

                    return back()->with('Success', "Operation Successful");
                } else {
                    return back()->with('error', "Record not found");
                }
            }

            if ($request->has('delete_copy_trading')) {

                $this->validate($request, [
                    'c_id' => 'required',
                ]);

                $t = UserCopyTrader::find($request->c_id);


                if ($t) {
                    $t->delete();

                    return back()->with('Success', "Operation Successful");
                } else {
                    return back()->with('error', "Record not found");
                }
            }

            return view("admin.view_user", [
                'page_title' => "$user->firstname Profile",
                'user' => $user,
                'toptraders' => TopTrader::orderBy("id", "DESC")->get(),
            ]);
        } else {

            return redirect()->route("admin.user");
        }
    }

    public function view_trader($trader_id, Request $request)
    {
        $trader = TradingAccount::where("id", $trader_id)->orWhere("uuid", $trader_id)->first();

        if ($trader) {
            $user = $trader->user;

            if ($request->has('toggle_active')) {
                if ($trader->is_active == 1) {
                    $trader->is_active = 0;
                } else {
                    $trader->is_active = 1;
                }
                $trader->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return redirect()
                    ->back()
                    ->with('success', "Operation Successful");
            }

           

            if ($request->has('edit_account')) {

                $this->validate($request, [
                    'balance' => 'required',
                    'account_type' => 'required',
                    'currency' => 'required',
                ]);

                $trader->balance = FilterHelper::amount($request->balance);
                $trader->type = $request->account_type;
                $trader->currency = $request->currency;
                $trader->save();

                try {
                    UserUpdatedEvent::broadcast($user->id, []);
                } catch (\Exception) {
                }

                return back()->with('Success', "Operation Successful");
            }

            if ($request->has('add_bot')) {

                $this->validate($request, [
                    'bot_id' => 'required',
                ]);

                $chk = UserTradeBot::where("trader_id", $trader->id)->first();
                if ($chk) {
                    return back()->with('error', "Bot already added");
                }

                $b = new UserTradeBot();
                $b->user_id = $user->id;
                $b->trader_id = $trader->id;
                $b->tradebot_id = $request->bot_id;
                $b->l_key = strtoupper(str()->random(8));
                $b->save();

                return back()->with('success', "Operation Successful");
            }

            if ($request->has('delete_bot')) {

                $this->validate($request, [
                    'bot_id' => 'required',
                ]);

                $b = UserTradeBot::find($request->bot_id);
                if ($b) {
                    $b->delete();
                    return back()->with('success', "Done");
                } else {
                    return back()->with('error', "Bot Not Found");
                }
            }

            return view("admin.view_trader", [
                'page_title' => "$user->fullname's Trading Account",
                'user' => $user,
                'trader' => $trader,
                "currencies" => FilterHelper::getCurrencyArray(),
                "bots" => TradeBot::all(),
                "users" => User::all(),
            ]);
        } else {

            return redirect()->route("admin.user");
        }
    }
}
