<?php

namespace App\Http\Controllers;

use App\Models\Balance;
use App\Models\User;
use App\Models\Coin;
use App\Models\Settings;
use App\Models\StakingHistory;
use App\Models\StakingPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StakingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $data = StakingPlan::latest()->where('status', 1)->paginate(20);

        return view('staking.index', compact('data'))
            ->with('i', (request()->input('page', 1) - 1) * 20);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function history()
    {
        //
        $data = StakingHistory::latest()->where('user_id', Auth::user()->id)->paginate(20);

        return view('staking.history', compact('data'))
            ->with('i', (request()->input('page', 1) - 1) * 20);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        //
        $staking_plan = StakingPlan::get()->where('id', $id)->first();
        $settings = Settings::get();
        if ($staking_plan) {
            $wallet = Balance::get()->where('user_id', Auth::user()->id)->where('coin_id', $staking_plan->coin_id)->first();
            if ($wallet) {
                $balance = $wallet->balance;
            } else {
                $balance = '0.00000000';
            }

            return view('staking.create', compact('balance', 'staking_plan', 'settings'));
        } else {
            return back();
        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $request->validate([
            'h-captcha-response' => 'required',
            'captcha-select' => 'required',
            'amount' => 'required',
            'plan_id' => 'required',
        ]);

        $requestData = $request->all();
        $amount = $requestData['amount'];

        $hcaptcha_secretkey = Settings::where('name', 'hcaptcha_secret')->first();
        $hcaptcha = verifyHcaptcha($hcaptcha_secretkey->value, $requestData['h-captcha-response']);

        if ($hcaptcha == 1) {

            //Verifications
            if ($amount <= 0) {
                return redirect()->back()
                    ->with('error', 'Amount is to less.');
            }

            $plan = StakingPlan::where('id', $requestData['plan_id'])->first();
            $coin = Coin::where('id', $plan->coin_id)->first();
            if ($coin) {
                $wallet = Balance::where('user_id', Auth::user()->id)->where('coin_id', $coin->id)->first();
                if ($wallet) {
                    if ($amount > $wallet->balance) {
                        return redirect()->back()
                            ->with('error', 'Insufficient account balance.');
                    }

                } else {
                    return redirect()->back()
                        ->with('error', 'Insufficient account balance.');
                }
            } else {
                return redirect()->back()
                    ->with('error', 'Currency not found.');
            }

            if($plan){

                if($amount < $plan->min_deposit){
                    return redirect()->back()
                    ->with('error', 'Amount is to less.');
                }

                if($amount > $plan->max_deposit){
                    return redirect()->back()
                    ->with('error', 'Amount is to high.');
                }

            }else{
                return redirect()->back()
                    ->with('error', 'Plan not found.');
            }

            $wallet->balance = $wallet->balance - $amount;
            $wallet->save();
            StakingHistory::create([
                'amount' => $amount,
                'earnings' => '0',
                'days' => $plan->duration,
                'status' => 1,
                'staking_plans_id' => $plan->id,
                'user_id' => Auth::user()->id,
            ]);
            return redirect()->back()
                ->with('success', 'Stake added successfully.');

        } else {
            return redirect()->back()
                ->with('error', 'Captcha error.');
        }

    }

    public function apistaking($key)
    {
        //
        $staking_apikey = Settings::where('name', 'staking_apikey')->first();
        if($key == $staking_apikey->value){

            $users = User::all();
            foreach($users as $key=>$user){
                $staking_history = StakingHistory::get()->where('user_id', $user->id)->where('days>', 0)->where('status', 1);
                foreach($staking_history as $key2=>$staking){
                    if($staking->days == 1){
                        $staking->status = 0;
                    }
                    $wallet = Balance::where('user_id', $user->id)->where('coin_id', $staking->plan->coin_id)->first();

                    $reward = ($staking->amount/100)*$staking->plan->daily_earning;
                    $wallet->balance += $reward;
                    $wallet->save();

                    $staking->earnings += $reward;
                    $staking->days -= 1;
                    $staking->save();
                }
            }

            echo 'ok';

        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
