<?php

namespace App\View\Components;

use App\Events\TradeUpdatedEvent;
use App\Helpers\FilterHelper;
use App\Models\Deposit;
use App\Models\Trade;
use App\Models\TradingAccount;
use App\Models\User;
use App\Models\Withdrawal;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Withdrawals extends Component
{
    public $trader_id;
    /**
     * Create a new component instance.
     */
    public function __construct($traderid = null)
    {
        $this->trader_id = $traderid;
    }

    public function handleComponentForms(Request $request)
    {
        if ($request->has('edit_w')) {
            Validator::validate($request->all(), [
                'c_id' => 'required',
                'status' => 'required',
            ]);

            $t = Withdrawal::find($request->c_id);
            if ($t) {
                $t->status = $request->status;
                $t->save();

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

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

            Validator::validate($request, [
                'c_id' => 'required',
            ]);

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

    /**
     * Get the view / contents that represent the component.
     */
    public function render()
    {
        if ($this->trader_id) {
            $trader = TradingAccount::find($this->trader_id);
            $user = $trader->user;
            $records = $trader->withdrawals()->orderBy('id', 'DESC')->get();
        } else {
            $user = null;
            $records = Withdrawal::orderBy("id", "DESC")->get();
        }

        return view('components.withdrawals', [
            'user' => $user,
            'withdrawals' => $records,
        ]);
    }
}
