API
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\ApiHelper;
use App\Helpers\BraintreeHelper;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Model\UserLogin;
use App\Model\UserReferralCodes;
use App\Model\UserPackagesSubscriptionHistories;
use App\Model\SubscriptionHistories;
use App\Model\SubscriptionPlan;
use App\Model\Notification;
use App\Model\UserMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Auth Controller
|--------------------------------------------------------------------------
|
| This controller handles login,social login, registration and forgot password features.
*/
public function refferal_Code($length)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
}
/**
* Register user.
*
* @param Request $request
*
* @return json
*/
public function signUp(Request $request)
{
$signUpValidion = [
//'name' => 'required|max:60',
'email' => 'required|unique:users',
'mobileNumber' => 'nullable',
'password' => 'required',
'deviceType' => 'required|in:Ios,Android,Web',
"deviceToken" => "required",
// "sportPackageId" => "required",
// "referralCodeBy" => "required"
// "socialId" => "required",
// "socialType" => "required|in:facebook,google,twitter",
];
if(empty($request->socialId))
{
$signUpValidion['name'] = 'required|max:60';
}
if(!empty($request->mobileNumber))
{
$signUpValidion['mobileNumber'] = 'unique:users';
}
$this->validate($request, $signUpValidion);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->userType = 'User';
$user->referralCode = self::refferal_Code(12);
$user->mobileNumber = $request->mobileNumber;
$user->password = bcrypt($request->password);
$user->showPassword = $request->password;
if(!empty($request->socialId))
{
$generatePassword = substr(str_shuffle('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'), 0, 8);
$user->password = bcrypt($generatePassword);
$user->showPassword = $generatePassword;
}
$user->deviceType = $request->deviceType;
$user->deviceToken = $request->deviceToken;
$user->isActive = 1;
$user->socialId = empty($request->socialType) ? null : $request->socialId;
$user->socialType = empty($request->socialType) ? null : $request->socialType;
$user->isEmailVerified = empty($request->socialType) ? 0 : 1;
if(!empty($request->referralCodeBy)){
$referralCodeUsersId = ApiHelper::getUserByReferralCode($request->referralCodeBy);
}else{
$referralCodeUsersId = null;
}
if(!empty($referralCodeUsersId) || empty($request->referralCodeBy)){
$otp = rand(1000, 9999);
$user->otp = empty($request->socialType) ? $otp : null;
\DB::beginTransaction();
if ($user->save()) {
$sportPackageId = ApiHelper::getsportPackageId();
$planData = ApiHelper::getSubscriptionPlanByfullPackages();
if(!empty($planData)){
$subscriptionhistories = ApiHelper::createsubscriptionhistories($sportPackageId,$referralCodeUsersId,$request->referralCodeBy,$user,$planData);
if($subscriptionhistories){
$userDetail = ApiHelper::getUserById($user->id)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
if(empty($request->socialType)){
$cmd = 'cd ' . base_path() . ' && php artisan mail:sendsignupotpCommand ' . $userDetail->id . ' ';
exec($cmd . ' > /dev/null &');
\DB::commit();
if($request->deviceType =='Web'){
$user = \Auth::loginUsingId($userDetail->id);
return redirect('user/otp');
}
return $this->toJson(['otp' => $userDetail->otp], trans('api.register.success'));
}
$user = \Auth::loginUsingId($userDetail->id);
$tokenResult = $user->createToken('Bettingtips')->accessToken;
if(!empty($request->socialId))
{
$cmd = 'cd ' . base_path() . ' && php artisan mail:sendFreeTrialInfoCommand ' . $userDetail->id . ' ';
exec($cmd . ' > /dev/null &');
}
\DB::commit();
return $this->toJson([
'userDetail' => $userDetail,
'accessToken' => $tokenResult,
], trans('api.register.success'));
}
}
DB::rollback();
if($request->deviceType =='Web'){
return redirect()->route('signup')->with('error',trans('api.register.plan_not_found'));
}
return $this->toJson(null, trans('api.register.plan_not_found'), 0);
}
if($request->deviceType =='Web'){
return redirect()->route('signup')->with('error',trans('api.register.error'));
}
return $this->toJson(null, trans('api.register.error'), 0);
}
if($request->deviceType =='Web'){
return redirect()->route('signup')->with('error',trans('api.register.invalid_referral_code_by_code'));
}
return $this->toJson(null, trans('api.register.invalid_referral_code_by_code'), 0);
}
/**
* Verify OTP Api
*
* @param Request $request
*
* @return Response Json
*
*/
public function verifyOTP(Request $request)
{
$authUser = \Auth::guard('api')->user();
$this->validate($request, [
'email' => 'required',
'otp' => 'required',
'deviceType' => 'required|in:Ios,Android',
'fcmToken' => 'required',
'deviceToken' => 'required',
]);
$param['email'] = $request->email;
$userDetail = ApiHelper::getUserByEmailOrMobile('email', $param)->first();
if (!empty($userDetail)) {
\DB::beginTransaction();
// Check otp is valid
if ($userDetail->otp == $request->otp) {
$userDetail->otp = null;
$userDetail->isEmailVerified = 1;
if ($userDetail->save()) {
//$customerData = BraintreeHelper::creatCustomer($userDetail);
$tokenResult = $request->header('Authorization');
if (empty($authUser)) {
$user = \Auth::loginUsingId($userDetail->id);
$tokenResult = $user->createToken('Bettingtips')->accessToken;
$this->userLogin($request, $userDetail);
$user->fcmToken = $request->fcmToken;
$user->save();
$cmd = 'cd ' . base_path() . ' && php artisan mail:sendFreeTrialInfoCommand ' . $user->id . ' ';
exec($cmd . ' > /dev/null &');
}
\DB::commit();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
return $this->toJson([
'userDetail' => $userDetail,
'accessToken' => $tokenResult,
], trans('api.otp_verify.success'));
}
DB::rollback();
return $this->toJson(null, trans('api.otp_verify.error'), 0);
}
return $this->toJson(null, trans('api.otp_verify.invalid'), 0);
}
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
/**
* Verify email Api
*
* @param Request $request
*
* @return Response Json
*
*/
public function verifyEmail(Request $request)
{
$authUser = \Auth::guard('api')->user();
$this->validate($request, [
'email' => 'required|unique:users',
'otp' => 'required'
]);
if (!empty($authUser)) {
\DB::beginTransaction();
// Check otp is valid
if ($authUser->otp == $request->otp) {
$authUser->otp = null;
$authUser->email = $request->email;
$authUser->isEmailVerified = 1;
if ($authUser->save()) {
$param['email'] = $authUser->email;
$userDetail = ApiHelper::getUserByEmail('email', $param)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
\DB::commit();
return $this->toJson([
'userDetail' => $userDetail
], trans('api.otp_verify.success'));
}
return $this->toJson(null, trans('api.otp_verify.error'), 0);
}
return $this->toJson(null, trans('api.otp_verify.invalid'), 0);
}
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
/**
* Login user in our system.
*
* @param object $request
*
* @return json
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
'deviceType' => 'required|in:Ios,Android',
'fcmToken' => 'required',
'deviceToken' => 'required',
]);
// check Email or Mobile No unique
$param['email'] = $request->email;
$userDetail = ApiHelper::getUserByEmailOrMobile('email', $param)->first();
//$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
if (empty($userDetail)) {
return $this->toJson(null, trans('api.login.invalid'), 0);
}
if ($userDetail->isActive != 1) {
return $this->toJson(null, trans('api.login.inactive'), 0);
}
if (\Hash::check($request->password, $userDetail->password)) {
$credentials = request(['email', 'password']);
$user = \Auth::loginUsingId($userDetail->id);
if ($userDetail->isEmailVerified != 1) {
$otp = rand(1000, 9999);
$userDetail->otp = $otp;
$userDetail->save();
$cmd = 'cd ' . base_path() . ' && php artisan mail:sendloginotpCommand ' . $userDetail->id . ' ';
exec($cmd . ' > /dev/null &');
}
$isVerified = (int) ($userDetail->isEmailVerified == 1);
$tokenResult = '';
$userDetail = ApiHelper::getUserByEmailOrMobile('email', $param)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
if ($isVerified) {
$tokenResult = $user->createToken('Bettingtips')->accessToken;
$this->userLogin($request, $user);
$user->fcmToken = $request->fcmToken;
$user->save();
return $this->toJson([
'userDetail' => $userDetail,
'accessToken' => $tokenResult,
], trans('api.login.success'), 1);
}
return $this->toJson([
'userDetail' => $userDetail,
'accessToken' => "",
], trans('api.login.success'), 1);
}
return $this->toJson(null, trans('api.login.invalid'), 0);
}
/**
* Login user by social.
*
* @param object $request
*
* @return json
*/
public function socialLogin(Request $request)
{
$this->validate($request, [
"socialId" => "required",
"socialType" => "required|in:facebook,google,twitter,apple",
'deviceType' => 'required|in:Ios,Android',
]);
$param['email'] = $request->email;
$param['socialId'] = $request->socialId;
$param['socialType'] = $request->socialType;
$userDetail = ApiHelper::getUserBysocialId('socialId', $param)->first();
if($userDetail){
$isVerified = (int) ($userDetail->isEmailVerified == 1);
$tokenResult = '';
if ($isVerified) {
$user = \Auth::loginUsingId($userDetail->id);
$tokenResult = $user->createToken('Bettingtips')->accessToken;
$user->fcmToken = $request->fcmToken;
$user->deviceType = $request->deviceType;
$user->save();
$userDetail->deviceType = $request->deviceType;
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
return $this->toJson([
'userDetail' => $userDetail,
'isExist' => 1,
'accessToken' => $tokenResult,
], trans('api.login.success'), 1);
}
}
return $this->toJson([
'userDetail' => [],
'isExist' => 0,
], trans('api.login.notfound'), 1);
}
/**
* Resend OTP
*
* @param Request $request
*
* @return Response Json
*
*/
public function resendOTP(Request $request)
{
$this->validate($request, [
'email' => 'required',
]);
$param['email'] = $request->email;
$userDetail = ApiHelper::getUserByEmailOrMobile('email', $param)->first();
if (!empty($userDetail)) {
$otp = rand(1000, 9999);
$userDetail->otp = $otp;
$userDetail->save();
$cmd = 'cd ' . base_path() . ' && php artisan mail:sendforgotpassword ' . $userDetail->id . ' ';
exec($cmd . ' > /dev/null &');
return $this->toJson([
'otp' => $userDetail->otp,
], trans('api.otp_verify.sent_otp', ['type' => 'email']), 1);
}
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
/**
* Resend OTP For Edit Email in profile
*
* @param Request $request
*
* @return Response Json
*
*/
public function resendOTPForEditEmail(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
]);
$user = Auth::guard('api')->user();
$userDetail = ApiHelper::getUserById($user->id)->first();
if (!empty($userDetail)) {
$otp = rand(1000, 9999);
$userDetail->otp = $otp;
$userDetail->save();
$cmd = 'cd ' . base_path() . ' && php artisan mail:resendotp ' . $request->email . ' ' . $userDetail->id . ' ';
exec($cmd . ' > /dev/null &');
return $this->toJson([
'otp' => $userDetail->otp,
], trans('api.otp_verify.sent_otp', ['type' => 'email']), 1);
}
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
/**
* Reset Password
*
* @param Request $request
*
* @return Response Json
*
*/
public function resetPassword(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
'confirmPassword' => 'required|same:password',
]);
$param['email'] = $request->email;
$userDetail = ApiHelper::getUserByEmailOrMobile('email', $param)->first();
if (!empty($userDetail)) {
$userDetail->password = bcrypt($request->password);
$userDetail->showPassword = $request->password;
$userDetail->save();
return $this->toJson(null, trans('api.reset_password.success'), 1);
}
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
/**
* Logout user
*
*/
public function logout1()
{
$user = Auth::guard('api')->user();
$userToken = Auth::user()->token();
if (empty($user)) {
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
User::where([
'id' => $user->id
])->update(['fcmToken' => null]);
$userToken->revoke();
\Session::flush();
return $this->toJson(null, trans('api.logout.success'));
}
/**
* Logout user
*
*/
public function logout()
{
$user = Auth::guard('api')->user();
if (empty($user)) {
return $this->toJson(null, trans('api.logout.success'));
}
$userToken = Auth::guard('api')->user();
if(!empty($user))
{
$userToken = $user->token();
User::where([
'id' => $user->id
])->update(['fcmToken' => null]);
$userToken->revoke();
}
\Session::flush();
return $this->toJson(null, trans('api.logout.success'));
}
/**
* Change Password
*
* @param Request $request
*
* @return Response Json
*
*/
public function changePassword(Request $request)
{
$this->validate($request, [
'oldPassword' => 'required',
'newPassword' => 'required',
'confirmPassword' => 'required|same:newPassword',
]);
$user = Auth::guard('api')->user();
if (empty($user)) {
return $this->toJson(null, trans('api.auth.user_not_found'), 0);
}
if (\Hash::check($request->oldPassword, $user->password)) {
$user->password = bcrypt($request->newPassword);
$user->save();
return $this->toJson(null, trans('api.auth.change_password'), 1);
}
return $this->toJson(null, trans('api.auth.invalid_current_password'), 0);
}
/**
* Login user in our system.
*
* @param Request $request
*
* @return json
*/
public function getUserDetail(Request $request)
{
$user = \Auth::user();
$userDetail = ApiHelper::getUserById($user->id)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
$isVerified = (int) ($user->isMobileVerify == 1 || $userDetail->isEmailVerified == 1);
$notificationCount = Notification:: where(['userId' => $user->id,'isRead' => 0])->count();
$messageCount = UserMessage:: where(['userId' => $user->id,'isRead' => 0])->count();
$todayDate = Carbon::now()->format('Y-m-d');
$expirePlanDate = SubscriptionHistories:: where(['userId'=> $user->id])->max('subscriptionExpiryDate');
$freeTrialDate = SubscriptionHistories :: selectRaw('subscriptionExpiryDate,subscriptionValidity')->where(['userId'=> $user->id,'isTrial' => 1])->first();
$freeTrialExpireCount = $this->dateDiffInDays($todayDate, $freeTrialDate['subscriptionExpiryDate']);
$isTrialExpired = ApiHelper::getIstrialExpired($user->id);
$tokenResult = '';
if ($isVerified) {
$tokenResult = $user->createToken('Bettingtips')->accessToken;
}
if(empty($request->version) || empty($userDetail))
{
$userToken = Auth::user()->token();
if(!empty($userToken))
{
$userToken->revoke();
}
\Session::flush();
$message = empty($request->version) ? 'Kindly update your app' : 'Your session has been expired';
return $this->toJson([], $message, 0);
}
return $this->toJson([
'isSocialLogin' => $userDetail->socialType == null ? 0 : 1,
'isVerified' => $isVerified,
'messageCount' => $messageCount,
'notificationCount' => $notificationCount,
'isTrialExpired' => $isTrialExpired,
'isPlanExpired' => $todayDate <= $expirePlanDate ? 0 : 1,
'freeTrialExpireCount' => $freeTrialExpireCount >= 0 ? $freeTrialExpireCount : 0,
'freeDays' => $freeTrialDate['subscriptionValidity'],
'userDetail' => $userDetail,
'accessToken' => $tokenResult,
'androidAppVersion' => "5",
'iosAppVersion' => "1.2"
], trans(''), 1);
}
/**
* Get Login user details in our system.
*
* @param Request $request
*
* @return json
*/
public function getProfileDetail(Request $request)
{
$user = \Auth::user();
$userDetail = ApiHelper::getUserById($user->id)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
$messageCount = UserMessage:: where(['userId' => $user->id,'isRead' => 0])->count();
$notificationCount = Notification:: where(['userId' => $user->id,'isRead' => 0])->count();
$isVerified = (int) ($user->isMobileVerify == 1 || $userDetail->isEmailVerified == 1);
$expirePlanDate = SubscriptionHistories:: where(['userId'=> $user->id])->max('subscriptionExpiryDate');
$freeTrialDate = SubscriptionHistories :: selectRaw('subscriptionExpiryDate,subscriptionValidity')->where(['userId'=> $user->id,'isTrial' => 1])->first();
$todayDate = Carbon::now()->format('Y-m-d');
$dateDiff = $this->dateDiffInDays($todayDate, $freeTrialDate['subscriptionExpiryDate']);
$isTrialExpired = ApiHelper::getIstrialExpired($user->id);
if($userDetail){
return $this->toJson([
'isSocialLogin' => $userDetail->socialType == null ? 0 : 1,
'isVerified' => $isVerified,
'messageCount' => $messageCount,
'notificationCount' => $notificationCount,
'isPlanExpired' => $todayDate <= $expirePlanDate ? 0 : 1,
'isTrialExpired' => $isTrialExpired,
'freeTrialExpireCount' => $dateDiff >= 0 ? $dateDiff : 0,
'freeDays' => $freeTrialDate['subscriptionValidity'],
'userDetail' => $userDetail
], trans('api.profile.success'), 1);
}
return $this->toJson([], trans('api.profile.error'), 0);
}
/**
* date DiffIn Days for check expire trial plan
*
* @param Request $date1 today date
* @param Request $date2 expire date
*/
function dateDiffInDays($date1, $date2)
{
if($date1 < $date2){
$diff = strtotime($date2) - strtotime($date1);
return (int)($diff / 86400);
}else if($date1 > $date2){
return 0;
}else if($date1 == $date2){
return 1;
}
}
// Not requred for Value-Plus
/**
* User login process.
*
* @param Request $request
* @param Request $user
*
* @return json
*/
private function userLogin(Request $request, $user)
{
// Logout from all other device
UserLogin::where([
'userId' => $user->id,
'isLogin' => 1,
])->update(['isLogin' => 0]);
$userLogin = new UserLogin();
$userLogin->userId = $user->id;
$userLogin->isLogin = '1';
$userLogin->fill($request->all());
$userLogin->save();
}
/**
* Change Pin
*
* @param Request $request
*
* @return Response Json
*
*/
public function changePin(Request $request)
{
$this->validate($request, [
'pin' => 'required|max:4',
]);
$user = Auth::guard('api')->user();
if ($request->pin == $user->pin) {
return $this->toJson(null, trans('api.pin.same'), 0);
}
$user->pin = $request->pin;
if ($user->save()) {
$userDetail = ApiHelper::getUserById($user->id)->first();
$userDetail = ApiHelper::getUserWithIsPayment($userDetail);
return $this->toJson([
'userDetail' => $userDetail,
], trans('api.pin.success'), 1);
}
return $this->toJson(null, trans('api.pin.error'), 0);
}
}
2
++++++++++++++++++++++++++++++++++++++++++++++++
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\ApiHelper;
use Illuminate\Support\Facades\Auth;
use App\Helpers\ImageHelper;
use App\Model\User;
use App\Model\UserSubscriptionHistories;
class UserController extends Controller
{
/**
* Edit user profile.
*
* @param Request $request
*
* @return json
*/
public function editProfile(Request $request)
{
$user = Auth::guard('api')->user();
if(!empty($request->mobileNumber)){
$this->validate($request, [
'name' => 'max:60',
'email' => 'unique:users,email,'.$user->id,
'mobileNumber' => 'unique:users,mobileNumber,'.$user->id,
]);
}else{
$this->validate($request, [
'name' => 'max:60',
'email' => 'unique:users,email,'.$user->id
]);
}
if($request->email != $user->email){
$otp = rand(1000, 9999);
$user->otp = $otp;
$cmd = 'cd ' . base_path() . ' && php artisan mail:resendotp "' . $request->email . '" "' . $user->id . '" ';
exec($cmd . ' > /dev/null &');
}
$user->name = $request->name;
$user->mobileNumber = $request->mobileNumber;
if ($user->save()) {
$userDetail = ApiHelper::getUserById($user->id)->first();
return $this->toJson(['userDetail' => $userDetail], trans('api.edit_profile.success'), 1);
}
return $this->toJson(null, trans('api.edit_profile.error'), 0);
}
/**
* Upload media
*
* @param Request $request
*
* @return json
*/
public function uploadProfilePhoto(Request $request)
{
$user = Auth::guard('api')->user();
$this->validate($request, [
'media' => 'required|image',
]);
// Check for image is available or not
if($request->hasFile('media'))
{
$request->module = 'profiles';
$destinationPath = public_path('images/' . $request->module);
$filePrefix = $request->module;
$fileName = $this->savePhotoProfile($request->file('media'),'images/profiles',$destinationPath ,'user_profile',100,100);
$path = url('images/'.$request->module.'/'.$fileName);
if ($request->module == 'profiles') {
$user->profilePic = $fileName;
$user->save();
}
return $this->toJson(['profilePic' => $path], trans('api.common.upload_media_success'), 1);
}
return $this->toJson(null, trans('api.common.upload_media_error'), 0);
}
/**
* Save admin image.
*
* @param $image,
* @param $path,
* @param $thumailImagePath,
* @param $prefix,
* @param $height,
* @param $width
*
* @return $imageName
*/
private function savePhotoProfile($image, $path, $thumailImagePath, $prefix, $height, $width)
{
if (!empty($image)) {
$imageName = ImageHelper::imageSave($image, $path, $prefix);
// if (!empty($imageName)) {
// ImageHelper::imageResize($imageName, $path, $thumailImagePath, $height, $width);
// }
return $imageName;
}
return null;
}
private function savePhoto($image,$path,$thumailImagePath,$prefix,$height,$width)
{
if(!empty($image))
{
$imageName= ImageHelper::imageSave($image,$path,$prefix);
if(!empty($imageName))
{
ImageHelper::imageResize($imageName,$path,$thumailImagePath,$height,$width);
}
return $imageName;
}
return null;
}
/**
* Destroy profile image.
*
*
*/
public function removeProfilePhoto()
{
$user = Auth::guard('api')->user();
$profileImage = $user->profilePic;
if($profileImage)
{
User::where('id',$user->id)->update(['profilePic' => Null]);
$profilePath = url(config('constant.PROFILES')).'/default.jpg';
return $this->toJson(['profilePic' => $profilePath], trans('api.profile.profilePicDeleted'), 1);
}
return $this->toJson([], trans('api.profile.profilePicNotFound'), 0);
}
/**
* get User Subscription History list
*
* @param Request null
*
* @return Response Json
*
*/
public function getUserSubscriptionHistory()
{
$user = Auth::guard('api')->user();
$historyList = UserSubscriptionHistories::selectRaw("id,planType,planName,packageName,planAmount,DATE_FORMAT(createdAt,'%D %b %Y, %h:%i %p') as createdAt")->where(['userId'=>$user->id,'isTrial' => 0])->orderBy('id', 'DESC')->get();
if($historyList->isNotEmpty())
{
return $this->toJson(['historyList' => $historyList], trans('api.history.history_found'), 1);
}
return $this->toJson([], trans('api.history.history_not_found'), 0);
}
}
3
+++++++++++++++++++++++++++++++++++++++++++++++
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\Game;
use App\Model\Package;
use App\Model\GameTip;
use App\Model\PackagesAsignToGame;
use Carbon\Carbon;
use App\Model\userGameHistory;
use App\Model\UserPackagesSubscriptionHistories;
use App\Helpers\ApiHelper;
use Illuminate\Support\Facades\DB;
class TipsController extends Controller
{
/**
* get UpcomingGameDetail , LatestGameDetail , SpecificGameDetail.
*
* @param Request $request
*
* @return json
*/
public function getHome(Request $request)
{
$this->validate($request, [
'limit' => 'required',
]);
$nowDate = Carbon::now()->format('Y-m-d');
$gameDetailUpcoming = $this->getUpcomingAndLatestGameData()->where('games.isActive',1)->where('games.launchDate','>',$nowDate)->orderBy('games.launchDate','asc')->limit($request->limit)->get();
$gameDetailLatest = $this->getUpcomingAndLatestGameData()->having('isSubscribed', 1)->having('totalTips', '>', 0)->orderBy('tipDate','desc')->limit($request->limit)->get();
$authUser = \Auth::guard('api')->user();
$data = $this->getspecificGameData();
//$data = [];
$mySport = collect($data)->sortByDesc('id')->where('isSubscribed', 1)->values()->slice(0,$request->limit);
$all = collect($data)->sortBy('id')->slice(0,$request->limit)->values()->toArray();
$popular = collect($data)->sortByDesc('totalUsersCount')->slice(0,$request->limit)->values()->toArray();
$frequent = collect($data)->sortByDesc('id')->slice(0,$request->limit)->values()->toArray();
return $this->toJson([
'UpcomingGameDetail' => $gameDetailUpcoming,
'LatestGameDetail' => $gameDetailLatest,
'SpecificGameDetail' => ['mySport'=> $mySport,'all' => $all, 'popular' => $popular,'frequent' => $frequent ],
], trans('api.gametips.homedetail'), 1);
/*if(!$gameDetailUpcoming->isEmpty() || !$gameDetailLatest->isEmpty() || !$mySport->isEmpty() || !empty($all) || !$popular->isEmpty() || !$frequent->isEmpty())
{
}*/
return $this->toJson(null, trans('api.gametips.homeerror'), 0);
}
/**
* getUpcoming And Latest GameData.
*
*
* @return json
*/
public function getUpcomingAndLatestGameData()
{
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$todayDate = Carbon::now()->format('Y-m-d');
return Game::selectRaw('games.id as id,games.gameName as gameName,
games.gameFullName as gameFullName,
IF(user_game_history.isSubscribed = 1,1,0) as isSubscribed,
IF(user_game_history.isKeepNotification = 1,1,0) as isKeepNotification,
IF(games.launchDate = "'.$todayDate.'",1,0) as isLatest,
CONCAT("' . $gameImagePath . '/",games.gameImage) as gameImage,
games.totalUsersCount AS totalUsersCount,
games.gameTotalTips AS totalTips,
games_tips.createdAt as tipDate,
0 as percentage,
DATE_FORMAT(games.launchDate,"%D %M") as gameDate')
->where('isActive','1')
->whereNull('games_tips.deletedAt')
->leftJoin('user_game_history', function ($join) use($authUser){
$join->on('games.id', 'user_game_history.gameId')
->where('user_game_history.userId', $authUser->id);
})
->leftJoin('games_tips', function ($join) {
$join->on('games_tips.gameId', '=', 'games.id');
})
->groupBy('games.id');
}
/**
* get specific GameData.
*
*
* @return json
*/
public function getspecificGameData($search = '', $date = '')
{
$todayDate = Carbon::now()->format('Y-m-d');
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
//->where('user_game_history.userId',$authUser->id) IF(games_tips.createdAt = "'.$todayDate.'",1,0) as isLatest,
$where = '';
$join = '';
$select = '';
$having = '';
if(!empty($search))
{
$search = "'".'%'.$search.'%'."'";
$where = ' left join `packages_asign_to_game` on `packages_asign_to_game`.`id` = `games`.`id`
left join `packages` on `packages_asign_to_game`.`packageId` = `packages`.`id`
where packages.packageName LIKE '.$search.' OR games.gameName LIKE '.$search.' ';
}
if(!empty($date))
{
$select = 'count(DISTINCT(gt.id)) as totalDateTipsCount,';
$join = 'left join `games_tips` AS gt on gt.`gameId` = `games`.`id` AND DATE(gt.createdAt) = "'.$date.'"';
$having = 'HAVING totalDateTipsCount > 0';
}
$data = \DB::select('select games.id,games.gameName,games.gameFullName,
CONCAT("' . $gameImagePath . '/",games.gameImage) as gameImage,
games.totalUsersCount as totalUsersCount,
games.gameTotalTips as totalTips,
IF(`ugh`.`isKeepNotification` = 1,1,0) as isKeepNotification,
'.$select.'
IF(COUNT(DISTINCT(user_messages.id)) > 0, 1, 0) as isLatest,
0 as percentage,
IF(user_game_history.userId = "'.$authUser->id.'",1,0) as isSubscribed from `games`
join `user_game_history` on `games`.`id` = `user_game_history`.`gameId` and `isActive` = 1
left join `user_game_history` AS `ugh` on `games`.`id` = `ugh`.`gameId` and `ugh`.`userId`= "'.$authUser->id.'" and `isActive` = 1
left join `user_messages` on `user_messages`.`gameId` = `games`.`id` and `user_messages`.`isRead` = 0 and `user_messages`.`userId` = "'.$authUser->id.'"
left join `games_tips` on `games_tips`.`gameId` = `games`.`id` AND games_tips.deletedAt IS NULL
'.$join.'
'.$where.'
group by `games`.`id` '.$having.' order by `games`.`id`');
return $data;
}
/**
* get All Upcoming Game.
*
* @param Request $request
*
* @return json
*/
public function getAllUpcomingGame(Request $request)
{
$nowDate = Carbon::now()->format('Y-m-d');
$gameDetailUpcoming = $this->getUpcomingAndLatestGameData()->where('games.launchDate','>',$nowDate)->orderBy('games.id','desc')->get();
if(!$gameDetailUpcoming->isEmpty())
{
return $this->toJson([
'UpcomingGameDetail' => $gameDetailUpcoming
], trans('api.gametips.upcomingdetail'), 1);
}
return $this->toJson(null, trans('api.gametips.upcomingdetailerror'), 0);
}
/**
* get tips with filter.
*
* @param Request $request
*
* @return json
*/
public function getTipswithFilter(Request $request)
{
$this->validate($request, [
'filter' => 'required|in:all,today,yesterday,mysport,popular,frequent'
]);
$joinType = 'leftJoin';
$todayDate = Carbon::now()->format('Y-m-d');
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$date = '';
if($request->filter == 'today')
{
$date = Carbon::now()->format('Y-m-d');
}
else if($request->filter == 'yesterday')
{
$date = Carbon::yesterday()->toDateString();
}
$searchSport='';
if($request->searchSport != '')
{
$searchSport = $request->searchSport;
}
$data = $this->getspecificGameData($searchSport,$date);
//$data = [];
if($request->filter == 'mysport')
{
$gameTipsDetail = collect($data)->where('isSubscribed', 1)->values();
}
else if($request->filter == 'popular')
{
$gameTipsDetail = collect($data)->sortByDesc('totalUsersCount')->values();
}
else if($request->filter == 'frequent')
{
$gameTipsDetail = collect($data)->sortByDesc('id')->values();
}
else if($request->filter == 'all')
{
$gameTipsDetail = collect($data)->sortByDesc('id')->values();
}
else
{
$gameTipsDetail = collect($data)->sortByDesc('id')->values();
}
if(!$gameTipsDetail->isEmpty())
{
return $this->toJson([
'gameTipsDetail' => $gameTipsDetail,
], trans('api.gametips.detail'), 1);
}
return $this->toJson(null, trans('api.gametips.error'), 0);
}
/**
* get game tips
*
* @param Request $request
* @return json
*/
public function getTips(Request $request)
{
$this->validate($request, [
'indexId' => 'required',
'isGreater' => 'required',
'gameId' => 'required'
]);
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$isSubscribedGame = userGameHistory:: select('*')->where('userId',$authUser->id )->where('gameId',$request->gameId )->get();
if(!$isSubscribedGame->isEmpty())
{
$qry = "";
$dateFormat = config('constant.DAY_MONTH_DATE_FORMAT');
if($request->isGreater == 0)
{
$qry = "SELECT games_tips.id,DATE_FORMAT(games_tips.createdAt,'%d %b %Y') as tipsDate,games_tips.createdAt,". ApiHelper::getTipsDateFormate('games_tips.createdAt', 'tipsTime') .",games_tips.tips,games_tips.odds,games_tips.units,1 as isWin,games_tips.IsWin as winLoss,games_tips.profitLosForTips,games_tips.weeklyProfitLos,games_tips.weeklyPot,games_tips.monthlyProfitLos,games_tips.monthlyPot,games_tips.allTimeProfitLos,games_tips.allTimePot,games_tips.tipsImage,games_tips.text,games_tips.gameId,DATE_FORMAT(games_tips.date,'%d %b %Y') as gameTipsDate FROM games_tips
WHERE games_tips.id < $request->indexId
AND games_tips.gameId = $request->gameId
AND games_tips.deletedAt IS NULL
ORDER BY games_tips.id ASC LIMIT 10";
$gameTips = DB::select($qry);
}
else
{
$qry = "SELECT games_tips.id,DATE_FORMAT(games_tips.createdAt,'%d %b %Y') as tipsDate,games_tips.createdAt,". ApiHelper::getTipsDateFormate('games_tips.createdAt', 'tipsTime') .",games_tips.tips,games_tips.odds,games_tips.units,1 as isWin,games_tips.IsWin as winLoss,games_tips.profitLosForTips,games_tips.weeklyProfitLos,games_tips.weeklyPot,games_tips.monthlyProfitLos,games_tips.monthlyPot,games_tips.allTimeProfitLos,games_tips.allTimePot,games_tips.tipsImage,games_tips.text,games_tips.gameId,DATE_FORMAT(games_tips.date,'%d %b %Y') as gameTipsDate FROM games_tips
WHERE games_tips.id > $request->indexId
AND games_tips.gameId = $request->gameId
AND games_tips.deletedAt IS NULL
ORDER BY games_tips.id DESC LIMIT 10";
$gameTips =DB::select($qry);
sort($gameTips);
}
if(!empty($gameTips))
{
return $this->toJson([
'gameTipsDetail' => $gameTips,
], trans('api.gametips.detail'), 1);
}
return $this->toJson(null, trans('api.gametips.error'), 0);
}
return $this->toJson(null, trans('api.gametips.notsubscribederror'), 0);
}
/**
* get Mysport with tips count.
*
* @param Request $request
* @return json
*/
public function getMysport(Request $request)
{
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$todayDate = Carbon::now()->format('Y-m-d');
$mySportDetails = Package::selectRaw('packages.id,packages.packageName,IF(MAX(user_packages_subscription_histories.isNew = 1),1,0) as isNew')
->Join('user_packages_subscription_histories', function ($join) use ($authUser) {
$join->on('user_packages_subscription_histories.sportPackageId', '=', 'packages.id')
->where('user_packages_subscription_histories.userId',$authUser->id);
})
->with(['games'=> function($qry) use($gameImagePath,$todayDate, $authUser){
$qry->selectRaw('packages_asign_to_game.gameId as id ,
packages_asign_to_game.gameId,
packages_asign_to_game.packageId,
CONCAT(games.gameName," ") as gameName,
games.gameFullName,
CONCAT("' . $gameImagePath . '/",games.gameImage) as gameImage,
games.totalUsersCount AS totalUsersCount,
games.gameTotalTips AS totalTips,
IF(user_game_history.isSubscribed = 1,1,0) as isSubscribed,
IF(ugh.isKeepNotification = 1,1,0) as isKeepNotification,
IF(games.launchDate = "'.$todayDate.'",1,0) as isLatest,
0 as percentage')
->leftJoin('games', function ($join) {
$join->on('games.id', '=', 'packages_asign_to_game.gameId');
})
->leftJoin('games_tips', function ($join) {
$join->on('games_tips.gameId', '=', 'games.id');
})
->leftJoin('user_game_history', function ($join) {
$join->on('user_game_history.gameId', '=', 'games.id');
})
->leftJoin('user_game_history as ugh', function ($join) use ($authUser) {
$join->on('games.id', '=', 'ugh.gameId')->where('isActive','1')
->where('ugh.userId', $authUser->id);
})
->groupBy('games.id')
->whereNull('games_tips.deletedAt')
->where('isActive',1)
->get();
}])
->groupBy('user_packages_subscription_histories.sportPackageId')
->orderBy('packages.id','asc')
->get();
if(!empty($mySportDetails))
{
UserPackagesSubscriptionHistories::where('userId',$authUser->id)->update(['isNew' => 0]);
return $this->toJson([
'mySportDetails' => $mySportDetails,
], trans('api.getMysport.detail'), 1);
}
return $this->toJson(null, trans('api.getMysport.error'), 0);
}
/**
* keep Notification status change for game
*
* @param Request $request
* @return json
*/
public function keepNotification(Request $request)
{
$this->validate($request, [
'gameId' => 'required',
'isKeepNotification' => 'required|in:1,0'
]);
$user = \Auth::guard('api')->user();
$isKeepNotification = $request->isKeepNotification;
if(userGameHistory::where(
['userId' => $user->id,'gameId' => $request->gameId]
)->update(['isKeepNotification' => $isKeepNotification]))
{
return $this->toJson(['isKeepNotification' => $isKeepNotification], trans('api.gametips.keepNotificationupdate'), 1);
}
return $this->toJson(null, trans('api.gametips.keepNotificationerror'), 0);
}
/**
* get search Sport
*
* @param Request $request
* @return json
*/
public function searchSport(Request $request)
{
$this->validate($request, [
'searchSport' => 'required'
]);
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$searchPackage = Package::where('packageName','LIKE','%'.$request->searchSport.'%')
->pluck('id')
->toArray();
if($searchPackage){
$searchSportDetails = Package::selectRaw('id,packageName')
->with(['games'=> function($qry) use($gameImagePath){
$qry->selectRaw('packages_asign_to_game.gameId,packages_asign_to_game.packageId,
games.gameName,games.gameFullName,
CONCAT("' . $gameImagePath . '/",games.gameImage) as gameImage,
games.totalUsersCount AS totalUsersCount,
games.gameTotalTips AS totalTips,
IF(user_game_history.isSubscribed = 1,1,0) as isSubscribed,
IF(user_game_history.isKeepNotification = 1,1,0) as isKeepNotification,
0 as percentage')
->leftJoin('games', function ($join) {
$join->on('games.id', '=', 'packages_asign_to_game.gameId');
})
->leftJoin('games_tips', function ($join) {
$join->on('games_tips.gameId', '=', 'games.id');
$join->whereNull('games_tips.deletedAt');
})
->leftJoin('user_game_history', function ($join) {
$join->on('user_game_history.gameId', '=', 'games.id');
})
->groupBy('games.id')
->get();
}])
->whereIn('id',$searchPackage)
->get();
if(!empty($searchSportDetails))
{
return $this->toJson([
'searchSportDetails' => $searchSportDetails,
], trans('api.searchSport.detail'), 1);
}
return $this->toJson(null, trans('api.searchSport.error'), 0);
}
return $this->toJson(null, trans('api.searchSport.error'), 0);
}
/**
* get Compare Sport with tips count.
*
* @param Request $request
* @return json
*/
public function getCompareSport(Request $request)
{
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$todayDate = Carbon::now()->format('Y-m-d');
$comparesportDetails = Package::selectRaw('packages.id,packages.packageName,IF(MAX(user_packages_subscription_histories.isNew = 1),1,0) as isNew')
->Join('user_packages_subscription_histories', function ($join) use ($authUser) {
$join->on('user_packages_subscription_histories.sportPackageId', '=', 'packages.id')
->where('user_packages_subscription_histories.userId',$authUser->id);
})
->with(['games'=> function($qry) use($gameImagePath,$todayDate){
$qry->selectRaw('packages_asign_to_game.gameId as id ,
packages_asign_to_game.gameId,
packages_asign_to_game.packageId,
CONCAT(games.gameName," ") as gameName,
games.gameFullName,
CONCAT("' . $gameImagePath . '/",games.gameImage) as gameImage,
games.totalUsersCount AS totalUsersCount,
games.gameTotalTips AS totalTips,
IF(games.launchDate = "'.$todayDate.'",1,0) as isLatest,
0 as percentage,
0 AS accuracyRate')
->leftJoin('games', function ($join) {
$join->on('games.id', '=', 'packages_asign_to_game.gameId');
})
->leftJoin('games_tips', function ($join) {
$join->on('games_tips.gameId', '=', 'games.id');
})
->leftJoin('games_tips AS gt', function ($join) {
$join->on('gt.gameId', '=', 'games.id')->whereRaw('gt.spreadsheetsId IS NOT NULL');
})
->leftJoin('user_game_history', function ($join) {
$join->on('user_game_history.gameId', '=', 'games.id');
})
->whereNull('gt.deletedAt')
->groupBy('games.id')
->where('isActive',1)
->get();
}])
->groupBy('user_packages_subscription_histories.sportPackageId')
->orderBy('packages.id','asc')
->get();
if(!empty($comparesportDetails))
{
UserPackagesSubscriptionHistories::where('userId',$authUser->id)->update(['isNew' => 0]);
return $this->toJson([
'compareSportDetails' => $comparesportDetails,
], trans('api.compareSportDetails.detail'), 1);
}
return $this->toJson(null, trans('api.compareSportDetails.error'), 0);
}
/**
* get tips with compare
*
* @param Request $request
* @return json
*/
public function getTipsCompare(Request $request)
{
$this->validate($request, [
'indexId' => 'required',
'isGreater' => 'required',
'gameId' => 'required'
]);
$gameImagePath = url(config('constant.GAMEIMAGES'));
$authUser = \Auth::guard('api')->user();
$isSubscribedGame = userGameHistory:: select('*')->where('userId',$authUser->id )->where('gameId',$request->gameId )->get();
if(!$isSubscribedGame->isEmpty())
{
$qry = "";
$dateFormat = config('constant.DAY_MONTH_DATE_FORMAT');
if($request->isGreater == 0)
{
$qry = "SELECT games_tips.id,DATE_FORMAT(games_tips.createdAt,'%d %b %Y') as tipsDate,games_tips.createdAt,". ApiHelper::getTipsDateFormate('games_tips.createdAt', 'tipsTime') .",games_tips.gameId,CONCAT(ROUND(games_tips.pot,2)) as pot,CONCAT(games_tips.accuracyRate,' %') AS accuracyRate,games_tips.tips,games_tips.odds,games_tips.units,1 as isWin,games_tips.IsWin as winLoss,games_tips.profitLosForTips,games_tips.weeklyProfitLos,games_tips.weeklyPot,games_tips.monthlyProfitLos,games_tips.monthlyPot,games_tips.allTimeProfitLos,games_tips.allTimePot,games_tips.tipsImage,games_tips.text,DATE_FORMAT(games_tips.date,'%d %b %Y') as gameTipsDate FROM games_tips
WHERE games_tips.id < $request->indexId
AND games_tips.gameId = $request->gameId
AND games_tips.spreadsheetsId IS NOT NULL
AND games_tips.deletedAt IS NULL
ORDER BY games_tips.id ASC LIMIT 10";
$gameTips = DB::select($qry);
}
else
{
$qry = "SELECT games_tips.id,DATE_FORMAT(games_tips.createdAt,'%d %b %Y') as tipsDate,games_tips.createdAt,". ApiHelper::getTipsDateFormate('games_tips.createdAt', 'tipsTime') .",games_tips.gameId,CONCAT(ROUND(games_tips.pot,2)) as pot,CONCAT(games_tips.accuracyRate,' %') AS accuracyRate,games_tips.tips,games_tips.odds,games_tips.units,1 as isWin,games_tips.IsWin as winLoss,games_tips.profitLosForTips,games_tips.weeklyProfitLos,games_tips.weeklyPot,games_tips.monthlyProfitLos,games_tips.monthlyPot,games_tips.allTimeProfitLos,games_tips.allTimePot,games_tips.tipsImage,games_tips.text,DATE_FORMAT(games_tips.date,'%d %b %Y') as gameTipsDate FROM games_tips
WHERE games_tips.id > $request->indexId
AND games_tips.gameId = $request->gameId
AND games_tips.spreadsheetsId IS NOT NULL
AND games_tips.deletedAt IS NULL
ORDER BY games_tips.id DESC LIMIT 10";
$gameTips =DB::select($qry);
sort($gameTips);
}
if(!empty($gameTips))
{
return $this->toJson([
'compareTipsDetail' => $gameTips,
], trans('api.comparetips.detail'), 1);
}
return $this->toJson(null, trans('api.comparetips.error'), 0);
}
return $this->toJson(null, trans('api.comparetips.notsubscribederror'), 0);
}
}
4
ApiHelper.php
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<?php
namespace App\Helpers;
use App\Model\PackagesAsignToGame;
use App\Model\userGameHistory;
use App\Model\SubscriptionPlan;
use App\Model\SubscriptionHistories;
use App\Model\Notification;
use App\Model\UserPackagesSubscriptionHistories;
use App\Model\UserReferralCodes;
use App\Model\User;
use App\Model\Package;
use Illuminate\Support\Carbon;
class ApiHelper
{
/*
|--------------------------------------------------------------------------
| API Helper
|--------------------------------------------------------------------------
|
| This helper is used for API related controllers.
| In this helper common methods written that is used at multiple locations.
|
*/
/**
* Gets user by id.
*
* @param int $id
*
* @return query result
*/
public static function getUserById($id)
{
$profilePath = url(config('constant.PROFILES'));
return User::where('id',$id)->selectRaw('id,name,deviceType,stripeId,password,email,mobileNumber,isActive,isEmailVerified,isMobileVerified,otp,CONCAT("' . $profilePath . '","/",ifnull(profilePic,"default.jpg")) as profilePic,otp,referralCode,socialType');
}
/**
* add isPayment flag in userDetail
*
* @param array $userDetail
*
* @return userDetail result
*/
public static function getUserWithIsPayment($userDetail)
{
if(!empty($userDetail)){
if($userDetail['deviceType'] === 'Ios'){
$userDetail['isPayment'] = 0;
}else if($userDetail['deviceType'] === 'Android'){
$userDetail['isPayment'] = 0;
}
}
return $userDetail;
}
/**
* Gets user by email or mobile no.
*
* @param string $data
* @param string $column
*
* @return query result
*/
public static function getUserByEmail($column, $data)
{
// check Email or Mobile No unique
$where = $column . ' = "' . $data['email'] . '"';
$profilePath = url(config('constant.AVATARIMAGE'));
return User::whereRaw($where)->selectRaw('id,name,deviceType,stripeId,email,mobileNumber,password,isActive,isEmailVerified,otp,isMobileVerified,CONCAT("' . $profilePath . '","/",ifnull(profilePic,"default.jpg")) as profilePic,referralCode,socialType');
}
/**
* Gets user by socialId and email .
*
* @param string $data
* @param string $column
*
* @return query result
*/
public static function getUserBysocialId($column, $data)
{
// check Email or Mobile No unique
$where = $column . ' = "' . $data['socialId'] . '"';
$profilePath = url(config('constant.AVATARIMAGE'));
return User::whereRaw($where)->selectRaw('id,name,deviceType,stripeId,email,socialId,mobileNumber,password,isActive,isEmailVerified,otp,isMobileVerified,CONCAT("' . $profilePath . '","/",ifnull(profilePic,"default.jpg")) as profilePic,referralCode,socialType');
}
/**
* Gets user by ReferralCode.
*
* @param string $referralCodeBy
*
* @return query result
*/
public static function getUserByReferralCode($referralCodeBy)
{
return User::selectRaw('id,referralCode,userType')
->where('userType', 'User')
->where('referralCode', $referralCodeBy)
->first();
}
/**
* Gets sport Package pluck
*
*
* @return query result
*/
public static function getsportPackageId()
{
return Package::selectRaw('id')
->where('isActive', 1)
->pluck('id');
}
public static function getUserByEmailOrMobile($column, $data)
{
// check Email or Mobile No unique
$where = $column . ' = "' . $data['email'] . '" OR mobileNumber = "'.$data['email'].'"';
$profilePath = url(config('constant.AVATARIMAGE'));
return User::whereRaw($where)->selectRaw('id,name,deviceType,stripeId,email,mobileNumber,password,isActive,isEmailVerified,otp,isMobileVerified,CONCAT("' . $profilePath . '","/",ifnull(profilePic,"default.jpg")) as profilePic,referralCode,socialType');
}
/**
* Gets Subscription plan by plan Full Packages
*
* @param number $numberOfPackages
*
* @return query result
*/
public static function getSubscriptionPlanByfullPackages()
{
// check plan is available
return SubscriptionPlan::where(['isActive'=> 1,'isTrial' => 1])->orderBy('planFullPackages','desc')->first();
// return SubscriptionPlan::selectRaw('id,planName,planDuration,planFullPackages,planWeeklyPrice')
// ->where('isActive', 1)
// ->where('planFullPackages', $numberOfPackages)
// ->first();
}
/**
* This method to sue for get name of packages
*
* @return string
*/
public static function getPackagesName($packagesId)
{
$package = Package::selectRaw('packageName')->whereIn('id', $packagesId)->pluck('packageName');
return str_replace(",",", ",$package->implode(','));
}
/**
* This method create subscription history on user registration time
*
* @param array $sportPackageId
* @param string $referralCodeBy
* @param int $referralCodeUsersId
* @param array $user
* @param array $planData
*
* @return void
*/
public static function createsubscriptionhistories($sportPackageId,$referralCodeUsersId,$referralCodeBy,$user,$planData)
{
$subscriptionhistories = new SubscriptionHistories();
$subscriptionhistories->userId = $user->id;
$subscriptionhistories->planName = $planData->planName;
$subscriptionhistories->planId = $planData->id;
$subscriptionhistories->planAmount= $planData->planWeeklyPrice;
$subscriptionhistories->amount = 0.00;
$subscriptionhistories->discountAmount = 0.00;
$subscriptionhistories->planType = 'Weekly';
$subscriptionhistories->isTrial = 1;
$subscriptionhistories->isCancel = 1;
$subscriptionhistories->subscriptionExpiryDate = Carbon::now()->addDays($planData->planDuration);
$subscriptionhistories->discountType = null;
$subscriptionhistories->paymentType = 'free';
$subscriptionhistories->isRefundRequest = 0;
$subscriptionhistories->paymentStatus = 'success';
$subscriptionhistories->subscriptionValidity = $planData->planDuration;
$subscriptionhistories->packageName = Self::getPackagesName($sportPackageId);
$subscriptionhistories->save();
// start user_packages_subscription_histories
$packagesData = [];
foreach ($sportPackageId as $packageKey => $package) {
$packagesData[] = [
'userId' => $user->id,
'subscriptionHistoriesId' => $subscriptionhistories->id,
'sportPackageId' => $package,
'isTrial' => 1
];
}
UserPackagesSubscriptionHistories::insert($packagesData);
// end user_packages_subscription_histories
// start packages wise user game history
$packageByGameData = PackagesAsignToGame::whereIn('packageId', $sportPackageId)
->pluck('gameId')->toArray();
$gameData = [];
foreach ($packageByGameData as $gameKey => $game) {
$gameData[] = [
'userId' => $user->id,
'subscriptionHistoriesId' => $subscriptionhistories->id,
'gameId' => $game,
'isTrial' => 1,
'isSubscribed' => 1
];
}
userGameHistory::insert($gameData);
// End packages wise user game history
// start referral code
if(!empty($referralCodeUsersId)){
$referralCodeData = [
'referralFrom' => $user->id,
'referralTo' => $referralCodeUsersId->id,
'referralCode' => $referralCodeBy,
'isApplied' => 0
];
UserReferralCodes::insert($referralCodeData);
}
// end referral code
$cmd = 'cd ' . base_path() . ' && php artisan mail:SendInvoiceCommand "' . $subscriptionhistories->id . '' . $user->id . '"';
exec($cmd . ' > /dev/null &');
return $subscriptionhistories;
}
/**
* This method create subscription history on user create payment time
*
* @param array $sportPackageId
* @param string $referralCodeBy
* @param int $referralCodeUsersId
* @param array $user
* @param array $planData
*
* @return void
*/
public static function createTransactionHistory($paymentData,$request,$planData,$planAmountData,$paymentType)
{
if($request->deviceType == 'Web')
{
$user = \Auth::guard('web')->user();
}
else
{
$user = \Auth::guard('api')->user();
}
if($request->planType == 'Monthly'){
$month = Carbon::now()->addMonth();
$planDuration = 30;
}else if($request->planType == 'Weekly'){
$month = Carbon::now()->addDays(7);
$planDuration = 7;
}
$encode_response = json_encode($paymentData);
$subscriptionhistories = new SubscriptionHistories();
$subscriptionhistories->userId = $user->id;
if(!empty($paymentData)){
// commited code used for braintree payment
// $subscriptionhistories->amount = $paymentData->transaction->amount;
// $subscriptionhistories->transactionId = $paymentData->transaction->id;
// $subscriptionhistories->paymentType = $paymentData->transaction->paymentInstrumentType;
$subscriptionhistories->amount = number_format($paymentData['amount'],2,'.', '')/100;
$subscriptionhistories->transactionId = $paymentData['id'];
$subscriptionhistories->paymentType = $paymentData['status'];
}else{
$subscriptionhistories->amount = 0.00;
$subscriptionhistories->transactionId = null;
$subscriptionhistories->paymentType = 'referral';
}
if($paymentType == 'onlyPlan'){
$subscriptionhistories->paymentType = null;
$subscriptionhistories->discountType = null;
} else if($paymentType == 'applyPromoCode'){
$subscriptionhistories->discountType = 'promocode';
$subscriptionhistories->promocodeId = $planAmountData['promocodeId'];
$subscriptionhistories->appliedPromocode = $planAmountData['appliedPromocode'];
} else if($paymentType == 'applyReferralCode'){
$subscriptionhistories->discountType = 'referral';
$subscriptionhistories->referralcodeId = $planAmountData['referralcodeId'];
$subscriptionhistories->appliedPromocode = $planAmountData['referralcode'];
}
$subscriptionhistories->paymentResponse = $encode_response;
$subscriptionhistories->planName = $planData->planName;
$subscriptionhistories->planAmount = $planAmountData['planAmount'];
$subscriptionhistories->planId = $request->planId;
$subscriptionhistories->planType = $request->planType;
$subscriptionhistories->discountAmount = $planAmountData['discountAmount'];
$subscriptionhistories->isTrial = 0;
$subscriptionhistories->subscriptionExpiryDate = $month->toDateString();
$subscriptionhistories->isRefundRequest = 0;
$subscriptionhistories->paymentStatus = 'success';
$subscriptionhistories->subscriptionValidity = $planDuration;
$subscriptionhistories->packageName = Self::getPackagesName($request->sportPackageId);
\DB::beginTransaction();
if($subscriptionhistories->save()){
// start user_packages_subscription_histories
$packagesData = [];
foreach ($request->sportPackageId as $packageKey => $package) {
$packagesData[] = [
'userId' => $user->id,
'subscriptionHistoriesId' => $subscriptionhistories->id,
'sportPackageId' => $package,
'isTrial' => 0
];
}
UserPackagesSubscriptionHistories::insert($packagesData);
// start packages wise user game history
$packageByGameData = PackagesAsignToGame::whereIn('packageId', $request->sportPackageId)
->pluck('gameId')->toArray();
$gameData = [];
foreach ($packageByGameData as $gameKey => $game) {
$gameData[] = [
'userId' => $user->id,
'subscriptionHistoriesId' => $subscriptionhistories->id,
'gameId' => $game,
'isTrial' => 0,
'isSubscribed' => 1
];
}
$userGameHistory = userGameHistory::insert($gameData);
$userGameHistoryLastId = userGameHistory::orderBy('id', 'desc')->first();
$cmd = 'cd ' . base_path() . ' && php artisan mail:SendInvoiceCommand "' . $subscriptionhistories->id . '' . $user->id . '"';
exec($cmd . ' > /dev/null &');
$resp['status'] = 1;
$notificationType = 7;
$image = url('admin-assets/images/logo/full_logo_new.png');
$notification[] = [
'senderId' => 1,
'userId' => $user->id,
'notificationType' => $notificationType,
'module' => 'subscription',
'title' => 'You have successfully subscribed for the <b style="color: #03a9f3;">' . $planData->planName . '</b> sports packages',
'content' => 'You have successfully subscribed for the <b style="color: #03a9f3;">' . $planData->planName . '</b> sports packages',
'userGameHistoryId' => $userGameHistoryLastId->id,
'media' => $image,
'createdAt' => Carbon::now(),
];
if(!empty($notification))
{
Notification::insert($notification);
$cmd = 'cd ' . base_path() . ' && php artisan SendNotificationType:send "' . $notificationType . '" "' . $userGameHistoryLastId->id . '" ';
//\Log::debug($cmd);
exec($cmd . '> /dev/null &');
}
return $resp;
}else{
$resp['status'] = 0;
return $resp;
}
}
/**
* Gets all user message .
*
* @param int $id
*
* @return query result
*/
public static function getDateFormate($filedName, $colunNmae)
{
$dateFormat = config('constant.DATE_TIME_FORMAT');
return 'CASE
WHEN '.$filedName.' between date_sub(now(), INTERVAL 60 second) and now()
THEN concat(second(TIMEDIFF(now(), '.$filedName.')), "sec")
WHEN '.$filedName.' between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), '.$filedName.')), " min")
WHEN '.$filedName.' between date_sub(now(), INTERVAL 24 hour) and now()
THEN concat(hour(TIMEDIFF(NOW(), '.$filedName.')), "h")
WHEN datediff(now(), '.$filedName.') = 1
THEN "Yesterday"
WHEN datediff(now(), '.$filedName.') = 2
THEN "2d"
WHEN datediff(now(), '.$filedName.') = 3
THEN "3d"
WHEN datediff(now(), '.$filedName.') = 7
THEN "1w"
WHEN datediff(now(), '.$filedName.') = 14
THEN "2w"
ELSE DATE_FORMAT('.$filedName.', "'.$dateFormat.'")
END as '.$colunNmae.'';
}
/**
* Gets Expiring Status for .
*
* @param int $id
*
* @return query result
*/
public static function getExpiringStatus($filedName, $colunNmae)
{
$dateFormat = config('constant.DATE_TIME_FORMAT');
//return 'CONCAT("Expiring in ", datediff(now(), '.$filedName.'), " days") '.$colunNmae.'';
return 'CASE
WHEN ABS(datediff(now() , '.$filedName.')) < 30
THEN CONCAT("Expiring in ", datediff('.$filedName.',now()), " days")
WHEN ABS(datediff(now() , '.$filedName.')) <= 60
THEN CONCAT("Valid till next"," 2 months")
ELSE DATE_FORMAT('.$filedName.', "'.$dateFormat.'")
END as '.$colunNmae.'';
}
/**
* Gets tips date formate .
*
* @param int $id
*
* @return query result
*/
public static function getTipsDateFormate($filedName, $colunNmae)
{
$dateFormat = config('constant.DAY_MONTH_DATE_FORMAT');
return 'CASE
WHEN datediff(now(), '.$filedName.') = 0
THEN "Today"
WHEN datediff(now(), '.$filedName.') = 1
THEN "Yesterday"
ELSE DATE_FORMAT('.$filedName.', "'.$dateFormat.'")
END as '.$colunNmae.'';
}
/**
* Gets message date formate .
*
*
* @return query result
*/
public static function getMessageDateFormate($filedName, $colunNmae)
{
$dateFormat = config('constant.DATE_TIME_FORMAT');
return 'CASE
WHEN datediff(now(), '.$filedName.') = 0
THEN "Today"
ELSE DATE_FORMAT('.$filedName.', "'.$dateFormat.'")
END as '.$colunNmae.'';
}
public static function getIstrialExpired($userId)
{
$todayDate = Carbon::now()->format('Y-m-d');
$isTrialCheck = SubscriptionHistories:: where(['userId'=> $userId])->orderBy('id','desc')->first();
if($isTrialCheck['isTrial'] == 1){
if($isTrialCheck['subscriptionExpiryDate'] > $todayDate){
return 0;
}
return 1;
}
return 0;
}
}
Comments
Post a Comment