<?php

namespace App\Repositories\Backend\Credit;

use App\Models\Auth\{User, UserDetail};
use App\Models\CreditLedger;
use App\Models\Auth\SocialAccount;
use App\Exceptions\GeneralException;
use App\Events\Backend\Auth\User\UserSocialDeleted;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

/**
 * Class SocialRepository.
 */
class CreditRepository
{
     /**
     * @param int    $param
     *
     * @return mixed
     */
    public function getUserParticularCredit($param)
    {
        $userResult = null;
        $user= User::where('email',$param)->first(); 
        if($user) {
        $userResult = UserDetail::with(['user'])->where('user_id',$user->id)->first();
    }
        return $userResult;
    }

    /**
     * @param array $data
     *
     * @throws \Exception
     * @throws \Throwable
     * @return User
     */
    public function create(array $data)
    {
        
        if (!Hash::check($data['transactionpassword'], auth()->user()->password)) {
            throw new GeneralException(__('exceptions.backend.access.credit.errorauthPassword'));
        }

        if ((auth()->user()->userDetails[0]->credit <= $data['amount'])&&($data['credittype']=='transfer')) {
            throw new GeneralException(__('exceptions.backend.access.credit.erroramount'));
        }
         return DB::transaction(function () use ($data) {
            $user = CreditLedger::create([
                'debit_userId' => auth()->user()->id,
                'credit_userId' => $data['userId'],
                'creditType' => $data['credittype'],
                'password' => $data['transactionpassword'],
                'amount' => $data['amount'],
                'created_by' => auth()->user()->id,
            ]);
        if($data['credittype']=='transfer') {
        $debit = (int)auth()->user()->userDetails[0]->credit - $data['amount'];
        $authuserDetails = UserDetail::with(['user'])->where('user_id',auth()->user()->id)->first();
        $authuserDetails->credit = $debit;
        $authuserDetails->save();
        
        $currentuserDetails = UserDetail::with(['user'])->where('user_id',$data['userId'])->first();
        $credit = (int)$currentuserDetails->credit + $data['amount'];
        $currentuserDetails->credit = $credit;
        $currentuserDetails->save();
        }

        if($data['credittype']=='adjust') {
            $debit = (int)auth()->user()->userDetails[0]->credit + $data['amount'];
            $authuserDetails = UserDetail::with(['user'])->where('user_id',auth()->user()->id)->first();
            $authuserDetails->credit = $debit;
            $authuserDetails->save();
            
            $currentuserDetails = UserDetail::with(['user'])->where('user_id',$data['userId'])->first();
            $credit = (int)$currentuserDetails->credit - $data['amount'];
            $currentuserDetails->credit = $credit;
            $currentuserDetails->save();
            }

    });
        return $user;
    }
}
