<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\AccountCurrency;
use App\Models\Loan;
use App\Models\Validate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class LoanController extends Controller
{
    public function index(){
        $short = AccountCurrency::where('symbol',getUserCurrency())->first()->short_name;
        return view('user.apply-loan', compact('short'));
    }

    public function store(Request $request){

        $validated = $request->validate(Validate::$LoanForm);

        if(!$validated){
            throw ValidationException::withMessages($validated);
        }

        $loans = Loan::where(['user_id'=>auth()->user()->id,'status'=>PENDING_LOAN])->get();

        if(auth()->user()->strength == LIMITED_STRENGTH && count($loans) >= config('settings.global_max_loan_request')){

           throw ValidationException::withMessages([__('You have applied for '.config('settings.global_max_loan_request').' consecutive loan application(s). Kindly wait for one or more application to be approved or upgrade your by <a href="'.route('user.open-ticket').'">opening a new ticket</a>')]);

        }elseif(auth()->user()->strength == LIMITED_STRENGTH && $request->amount > config('settings.global_max_loan_amount')){

            throw ValidationException::withMessages([__('You can not request for any amount greater than '.getUserCurrency().config('settings.global_max_loan_amount').', kindly upgrade your account by <a href="'.route('user.open-ticket').'">opening a new ticket</a>')]);

        }else{

            Loan::create([
                'loan_id' => Loan::generateLoanID(),
                'user_id' => auth()->user()->id,
                'amount' => $request->amount,
                'purpose' => $request->purpose,
            ]);

            return back()->with('success', __('Loan application submitted successfully. Please wait for approval.'));
        }
    }

    public function show(){

        $loans = Loan::where('user_id',auth()->user()->id)->orderBy('created_at','DESC')->get();

        return view('user.loans', compact('loans'));
    }
}
