<?php
namespace App\Http\Controllers\User;
ini_set('max_execution_time', 100);
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Transaction;
use App\Models\Validate;
use App\Models\Withdrawal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class WithdrawalController extends Controller
{
    public function bank(){
        if(config('settings.enable_withdrawals')==1){
           return view('user.bank-withdrawal');
        }
        return redirect(route('user.dashboard'));

    }
    public function transfer(){
        if(config('settings.enable_withdrawals')==1){
            return view('user.transfer-withdrawal');
        }
        return redirect(route('user.dashboard'));

    }
    public function crypto(){
        if(config('settings.enable_withdrawals')==1){
            return view('user.crypto-withdrawal');
        }
        return redirect(route('user.dashboard'));
    }

    public function createCrypto(Request $request){
        $validator = Validator::make($request->all(),Validate::$CryptoWithdrawalForm);
        if($validator->fails()){
            throw ValidationException::withMessages($validator->errors()->toArray());
        }elseif(rawUserBalance() < $request->amount){
            throw ValidationException::withMessages([__('Insufficient balance. Please top up your account and try again.')]);
        }elseif($request->amount < config('settings.global_min_withdrawal')){
            throw ValidationException::withMessages([__('You can not withdraw any amount below '.getUserCurrency().config('settings.global_min_withdrawal'))]);
        }elseif($request->amount > config('settings.global_max_withdrawal') && auth()->user()->strength=='limited'){
            throw ValidationException::withMessages([__('You need to upgrade your account to enable you withdraw any amount greater than '.getUserCurrency().config('settings.global_max_withdrawal').' Kindly contact our customer service for upgrade.')]);
        }else{
            $account = Account::where('user_id',auth()->user()->id)->first();
            $account->previous_balance = $account->balance;
            $account->previous_balance_date = date('Y-m-d H:i:s');
            $account->balance -= $request->amount;
            $account->save();
            $wth = Withdrawal::create([
                'user_id'=>auth()->user()->id,
                'category'=>$request->category,
                'currency'=>$request->currency,
                'wallet_address'=>$request->wallet_address,
                'bank_name'=>NULL,
                'account_name'=>NULL,
                'account_number'=>NULL,
                'amount'=>$request->amount,
                'remark'=>ucwords($request->remark)
            ]);
            $tx = Transaction::create([
                'user_id'=>auth()->user()->id,
                'tx_id'=>Transaction::generateTxId(),
                'type' => 'withdrawal',
                'category' => $request->category,
                'bank_name'=>ucwords($request->currency),
                'receiver_name'=>substr($request->wallet_address,0,6).'**'.substr($request->wallet_address,-4),
                'receiver_account'=>ucwords($request->currency),
                'remark'=>ucwords($request->remark),
                'amount'=>$request->amount,
                'status'=>PENDING_TX
            ]);
            // TODO: Send withdrawal pending email
            return redirect()->back()->with('success',__('Your withdrawal request of '.getUserCurrency().$request->amount.' has been received.'));
        }
    }

    public function createNormal(Request $request){
        $validator = Validator::make($request->all(),Validate::$WithdrawalForm);
        if($validator->fails()){
            throw ValidationException::withMessages($validator->errors()->toArray());
        }elseif(rawUserBalance() < $request->amount){
            throw ValidationException::withMessages([__('Insufficient balance. Please top up your account and try again.')]);
        }elseif($request->amount < config('settings.global_min_withdrawal')){
            throw ValidationException::withMessages([__('You can not withdraw any amount below '.getUserCurrency().config('settings.global_min_withdrawal'))]);
        }elseif($request->amount > config('settings.global_max_withdrawal') && auth()->user()->strength=='limited'){
            throw ValidationException::withMessages([__('You need to upgrade your account to enable you withdraw any amount greater than '.getUserCurrency().config('settings.global_max_withdrawal').' Kindly contact our customer service for upgrade.')]);
        }else{
            $account = Account::where('user_id',auth()->user()->id)->first();
            $account->previous_balance = $account->balance;
            $account->previous_balance_date = date('Y-m-d H:i:s');
            $account->balance -= $request->amount;
            $account->save();
            $wth = Withdrawal::create([
                'user_id'=>auth()->user()->id,
                'category'=>$request->category,
                'currency'=>NULL,
                'wallet_address'=>NULL,
                'bank_name'=>$request->bank_name,
                'account_name'=>$request->account_name,
                'account_number'=>$request->account_number,
                'amount'=>$request->amount,
                'remark'=>ucwords($request->remark)
            ]);
            $tx = Transaction::create([
                'user_id'=>auth()->user()->id,
                'tx_id'=>Transaction::generateTxId(),
                'type' => 'withdrawal',
                'category' => $request->category,
                'bank_name'=>ucwords($request->bank_name),
                'receiver_name'=>ucwords(strtolower($request->account_name)),
                'receiver_account'=>$request->account_number,
                'remark'=>ucwords($request->remark),
                'amount'=>$request->amount,
                'status'=>PENDING_TX
            ]);
            // TODO: Send withdrawal pending email
            return redirect()->back()->with('success',__('Your withdrawal request of '.getUserCurrency().$request->amount.' has been received.'));
        }
    }
}
