<?php

namespace App\Http\Controllers\Instructor;

use App\{
    Models\User,
    Models\Withdraw,
    Models\Currency,
    Models\Generalsetting
};
use Auth;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class WithdrawController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

  	public function index()
    {
        $user = Auth::user();
        $withdraws = Withdraw::where('register_id',0)->where('user_id','=',$user->id)->latest('id')->get();
        $sign = Currency::where('register_id',0)->where('is_default','=',1)->first();        
        return view('instructor.withdraw.index',compact('withdraws','sign'));
    }

    public function create()
    {
        $sign = Currency::where('register_id',0)->where('is_default','=',1)->first();
        return view('instructor.withdraw.withdraw' ,compact('sign'));
    }


    public function store(Request $request)
    {

       
        $gs = Generalsetting::find(1);
        $user = Auth::user();

        $from = User::findOrFail($user->id);

        $withdrawcharge = $gs;
        $charge = $withdrawcharge->withdraw_fee;

        if($request->amount > 0){

            $amount = $request->amount;

            if ($from->balance >= $amount){
                $fee = (($withdrawcharge->withdraw_charge / 100) * $amount) + $charge;
                $finalamount = $amount - $fee;
                if ($from->balance >= $finalamount){
                $finalamount = number_format((float)$finalamount,2,'.','');

                $from->balance = $from->balance - $amount;
                $from->update();

                $newwithdraw = new Withdraw();
                $newwithdraw['user_id'] = $user->id;
                $newwithdraw['method'] = $request->methods;
                $newwithdraw['acc_email'] = $request->acc_email;
                $newwithdraw['iban'] = $request->iban;
                $newwithdraw['country'] = $request->country;
                $newwithdraw['acc_name'] = $request->acc_name;
                $newwithdraw['address'] = $request->address;
                $newwithdraw['swift'] = $request->swift;
                $newwithdraw['reference'] = $request->reference;
                $newwithdraw['amount'] = $finalamount;
                $newwithdraw['fee'] = $fee;
                $newwithdraw->save();

                return response()->json(__('Withdraw Request Sent Successfully.')); 
            }else{
                return response()->json(array('errors' => [ 0 => __('Insufficient Balance.') ])); 

            }
            }else{
                return response()->json(array('errors' => [ 0 => __('Insufficient Balance.') ])); 

            }
        }
            return response()->json(array('errors' => [ 0 => __('Please enter a valid amount.') ])); 

    }
}