<?php

namespace App\Http\Controllers;

use App\Http\Component\AppController;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Deposit;
use Illuminate\Support\Facades\Auth;
use App\Http\Services\WalletServices;
use App\Models\Withdrawal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TransactionController extends AppController
{
    private $wallet;
    private $activeTemplate;

    public function __construct(
        WalletServices $wallet
    )
    {
        $this->activeTemplate = activeTemplate();
        $this->wallet = $wallet;
    }

    public function transaction($type = 'all')
    {
        $pageTitle = "Transaction records";
        if($type == 'deposit') $pageTitle = "Recharge records";
        if($type == 'withdraw') $pageTitle = "Withdrawal records";
        if($type == 'bonus') $pageTitle = "Invite Bonus records";
        if($type == 'reward') $pageTitle = "Rewards records";
        if($type == 'redeem') $pageTitle = "Gift Redeem records";
        if($type == 'commission') $pageTitle = "Referral Bonus";
        if($type == 'income') $pageTitle = "Interest returns";
		$user = auth()->user(); $tranSum = 0;

		$transactions = Transaction::where('status', '!=', 0)->where('user_id', $user->id);
		if( !in_array($type, ['all','others']) ){
			$transactions = $transactions->where('type', $type);
			$tranSum = $transactions->sum('amount');
		}
		if( $type == 'others' ){
			$transactions = $transactions->whereIn('type', ['bonus','reward','redeem','invest','commission']);
		}
		$transactions = $transactions->where(['currency' => session()->get('currency')])->orderBy('id','desc')->paginate(getPaginate());

        $emptyMessage = "No Data Found!";
        return view($this->activeTemplate.'user.transaction.history', compact('pageTitle','transactions', 'type', 'emptyMessage','user','tranSum'));
    }

    /*
     * Deposit History
     */
    public function depositHistory()
    {
        $pageTitle = 'Recharge History';
        $emptyMessage = 'No history found.';
		$user = auth()->user();
        $logs = $user->deposits()->with(['gateway'])->where(['user_id' => Auth::id(), 'currency' => session()->get('currency')])->orderBy('id','desc')->paginate(getPaginate());
		$cancelled = Deposit::where('status', 3)->where('user_id', $user->id)->sum('amount');
		
        return view($this->activeTemplate.'user.deposit.history', compact('pageTitle', 'emptyMessage', 'logs', 'user', 'cancelled'));
    }

    public function withdrawLog()
    {
        $pageTitle = "Withdraw History";
		$user = auth()->user();
        $withdrawal = Withdrawal::where(['user_id' => $user->id, 'currency' => session()->get('currency')]);
        $withdraws = $withdrawal->orderBy('id','desc')->paginate(getPaginate());
        $emptyMessage = "No Data Found!";
		return view($this->activeTemplate.'user.withdraw.log', compact('pageTitle','withdraws', 'emptyMessage','user','withdrawal'));
    }


    public function exchangeRate(Request $request){
        // Validate
        $validator = Validator::make($request->all(),[
            'amount' => 'required|numeric|min:1',
            'from_currency' =>'required|string|in:NGN,USDT',
            'to_currency' =>'required|string|in:NGN,USDT'
        ]);

        // Failed to validate
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            $notify[] = ['error', implode(' ', $errors)];
            return $this->handleResponse($request, implode(' ', $errors), 401, $notify);
        }

        $user = User::find(\auth()->user()->id);

        $userBalance = $this->wallet->getExchangeRate($user, $request->amount, $request->from_currency, $request->to_currency);

        if($userBalance instanceOf \Exception) {
            $notify[] = ['error', $userBalance->getMessage()];
            return $this->handleResponse($request, $userBalance->getMessage(), 401, $notify);
        }

        return $this->handleResponse($request, 'Successful', 200, $userBalance);

    }

}
