Server : Apache System : Linux 145.162.205.92.host.secureserver.net 5.14.0-611.45.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Apr 1 05:56:53 EDT 2026 x86_64 User : tradze ( 1001) PHP Version : 8.1.34 Disable Function : NONE Directory : /home/tradze/www/app/Modules/Users/Http/Controllers/Api/ |
<?php
namespace App\Modules\Users\Http\Controllers\Api;
use App\Events\ApiResetBasketEvent;
use App\Http\Controllers\ApiController;
use App\Modules\Schedules\Models\BookingOrder;
use App\Modules\Schedules\Models\Order;
use App\Modules\Schedules\Repositories\BookingClass;
use App\Modules\Notifications\Facades\NotifRepository;
use App\Modules\Schedules\Repositories\BookingRepository;
use App\Modules\Services\Models\ServiceDuration;
use App\Modules\Services\Models\SalonServiceDuration;
use App\Modules\Services\Models\ServiceType;
use App\Modules\Services\Models\SalonCategory;
use App\Modules\Users\Http\Requests\TherapistCreateClientRequest;
use App\Modules\Users\Models\UserLocation;
use App\Modules\Users\Models\UserProfile;
use App\Modules\Users\Repositories\ApiRepository;
use App\Modules\Vouchers\Models\Voucher;
use App\User;
use Spatie\Permission\Models\Role;
use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Modules\Schedules\Models\SalonCart;
use App\Modules\Banners\Repositories\BannersRepo;
use App\Modules\Users\Models\UserCoverageArea;
use Omnipay\Common\CreditCard;
use Omnipay\Omnipay;
use App\Stripe;
class ApiSalon extends ApiController
{
public function getTreatments() {
$treatments = SalonCategory::where('parent_category_id', 0)->get();
// $salon_treatment = SalonCategory::with(['subCategory' => function($q) {
// $query = $q->select('salon_categories.id as subsubcate_id','salon_categories.*')->first();
// $subcategory_id = !empty($query->subsubcate_id)?$query->subsubcate_id:null;
// $q->with(['subsubCategory'=>function($sq) use($subcategory_id) {
// $sq->select('salon_categories.id as subsubsubcate_id','salon_categories.*')->with('duration')->whereParentCategoryId($subcategory_id);
// }]);
// }])->get();
// $obj = $salon_treatment[0];
return response()->json([
'status'=> true,
'treatments' => $treatments,
]);
}
public function getVenues() {
$venues = User::getSubscribedSalonUser()->get();
return response()->json([
'status'=> true,
'venues' => $venues,
]);
}
public function getNearestVenues(Request $request) {
$add = $request->address;
if(!$add){
return response()->json([
'status'=> false,
'msg' => "Please enter your postal code/address",
]);
}
//Formatted address
$formattedAddr = str_replace(' ','+',$add);
// dd($formattedAddr);
//Send request and receive json data by address
$geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false&key='.config('googlemaps.key'));
$output = json_decode($geocodeFromAddr);
// dd($output);
if(!empty($output)){
$addressComponents = $output->results[0]->address_components;
foreach($addressComponents as $addrComp){
if($addrComp->types[0] == 'postal_code'){
//Return the zipcode
$address_postcode = $addrComp->long_name;
$booking['postcode'] = $address_postcode;
}
}
}
$addr_latitude = !empty($output->results[0]->geometry->location->lat)?$output->results[0]->geometry->location->lat:'';
$addr_longitude = !empty($output->results[0]->geometry->location->lng)?$output->results[0]->geometry->location->lng:'';
$this->data['lon'] = $addr_longitude;
$this->data['lat'] = $addr_latitude;
$salon_users = $this->getSalonUserInRange($addr_latitude, $addr_longitude, 100);
$salon_users = $this->activeSalonUsersInRange($salon_users);
$parent_salon_category = SalonCategory::where('parent_category_id', 0)->get();
$this->data['salon_users_one'] = [];
$this->data['other_salon_users_two'] = [];
foreach($salon_users as $users){
if($users->deleted_at == null){
$usr = User::where('id', $users->id)->with('salongallaryall','profile','address','workingdays', 'reviews')->first();
// $this->data['salon_users'][] = $usr;
}
if($request->treatment_id == 0) {
$this->data['other_salon_users_two'][] = $usr;
} else {
$tsubcategory = SalonCategory::where('parent_category_id', $request->treatment_id)->where('user_id',$usr->id)->get();
if($tsubcategory->count()){
$this->data['salon_users_one'][] = $usr;
} else {
// $this->data['other_salon_users_two'][] = $usr; // only comment this when only those salon have to show which do the category.
}
}
}
$this->data['salon_users'] = array_merge($this->data['salon_users_one'], $this->data['other_salon_users_two']);
return response()->json([
'status'=> true,
'venues' => $this->data['salon_users'],
]);
//end
}
public function activeSalonUsersInRange($result) {
$activeUsers = User::getSubscribedSalonUser()->pluck('id');
$ids_array = [];
foreach($activeUsers as $active) {
$ids_array[] = $active;
}
$matchedObjects = [];
// dd($result, $activeUsers);
// Loop through the array of objects and compare with the given IDs
foreach ($result as $object) {
// dd($object->id);
if (in_array($object->id, $ids_array)) {
$matchedObjects[] = $object;
}
}
// $results
return $matchedObjects;
}
public function getSalonDetails(Request $request) {
if(!$request->id) {
return response()->json([
'status'=> false,
'msg' => 'Salon Id is missing',
]);
} else {
$id = $request->id;
}
if(!$request->address){
return response()->json([
'status'=> false,
'msg' => 'Please enter your postal code/address',
]);
}
$salon = User::where('id', $id)->with('salongallaryall','profile','address','workingdays', 'reviews')->first();
$this->data['salon_therapist'] = $this->salonTherapist($id);
$this->data['salon'] = $salon;
if($salon == null){
return response()->json([
'status'=> false,
'msg' => 'No Salon Found',
]);
}
if(count($salon->address) == 0){
return response()->json([
'status'=> false,
'msg' => 'No Address is registerd by the salon',
]);
}
// check if any subcategory is added by user in parent category or not
$parent_salon_category = SalonCategory::where('parent_category_id', 0)->get();
$psaloncategory = [];
foreach($parent_salon_category as $category){
$tsubcategory = SalonCategory::where('parent_category_id', $category->id)->where('user_id',$id)->get();
if($tsubcategory->count()){
$psaloncategory[] = $category;
}
}
$this->data['salon_category'] = $psaloncategory;
return response()->json([
'status'=> true,
'data' => $this->data,
]);
}
public function getSalonSubcategory(Request $request) {
if(!$request->category_id || !$request->salon_id) {
return response()->json([
'status'=> false,
'msg' => "invalid parameters",
]);
}
$this->data['key'] = $request->category_id;
$this->data['salon_id'] = $request->salon_id;
$this->data['category'] = SalonCategory::with('duration')->where('parent_category_id', $request->category_id)->where('user_id',$request->salon_id)->get();
return response()->json([
'status'=> true,
'sub-category' => $this->data['category'],
]);
}
public function salonTherapist($id){
$therapists = [];
if(isset($id)){
$group = Role::where('name', 'therapist')->first();
$obj = User::query()->where('salon_id',$id)->whereHas('roles', function ($query) {
return $query->where('slug', 'therapist');
})->orderBy('nr_crt', 'asc')->get();
}
if($obj){
foreach($obj as $therapist){
$therapists[] = User::where('id',$therapist->id)->with('profile','workingdays', 'therapistreview', 'mywork')->first();
// dd($therapists);
}
}
// $obj = User::where('salon_id',$id)->where('role',);
return $therapists;
}
public function getSalonUserInRange($latitude, $longitude, $km){
return $salon_users = DB::select("SELECT * FROM (
SELECT *,
(
(
(
acos(
sin(( $latitude * pi() / 180))
*
sin(( `lat` * pi() / 180)) + cos(( $latitude * pi() /180 ))
*
cos(( `lat` * pi() / 180)) * cos((( $longitude - `long`) * pi()/180)))
) * 180/pi()
) * 60 * 1.1515 * 1.609344
)
as distance FROM `users`
) users
WHERE distance <= $km
");
}
public function getSalonCart(Request $request) {
// dd($this->user);
$user = $this->user;
if(!$request->salon_id) {
return response()->json([
'status'=> false,
'msg' => "invalid parameters",
]);
}
// dd($request->salon_id);
$cartDetails = SalonCart::with('salon', 'treatment', 'duration', 'therapist')->where('user_id', $user->id)->get();
$count = count($cartDetails);
return response()->json([
'status'=> true,
'cart' => $cartDetails,
'count' => $count
]);
}
public function getSalonHours(Request $request) {
$user = $this->user;
// if (!$date)
// $date = date('Y-m-d');
// $booking = Session::get('booking');
// if(!isset($booking['hour']) || $booking['hour'] == '00:00')
// {
// $repo = new BookingClass();
// $first_hours = $repo->getAndSetFirstAvailableDayHour();
// $booking = Session::get('booking');
// }
$repo = new BookingClass();
$hours = $repo->all_salon_hours($request->date, $request->duration);
$items = [];
foreach($hours as $key => $hour) {
// dd($hour);
if($hour['available'] == 1) {
$items[] = $hour;
}
}
// dd($hours);
// $this->data['hours'] = $hours;
// $this->data['selectedhour'] = isset($booking['hour'])?$booking['hour']:null;
return response()->json([
'status'=> true,
'hours' => $items,
]);
// dd("here");
}
public function getSalonTherapist(Request $request) {
$booking = Session::get('booking');
$booking['postcode']=$request->postcode;
$booking['address']=$request->address;
$booking['date']=$request->date;
$booking['hour']=$request->hour;
Session::put('booking',$booking);
//if one of mandatory fields is missing, return empty array results
$mandatory_fields = ['date', 'address', 'hour'];
foreach ($mandatory_fields as $field) {
if (!isset($booking[$field]))
return response()->json([
'status'=> true,
'therapist' => [],
]);
} //endforeach
;
$results = [];
if($request->category_id) {
$this->addCategoryToSession($request->category_id);
$repo = new BookingClass();
$results = $repo->salontherapists();
}
return response()->json([
'status'=> true,
'therapist' => $results,
]);
}
public function addCategoryToSession($itemId) {
$subcategory = SalonCategory::with('duration')->where('id',$itemId)->where('parent_category_id', '!=' ,0)->first();
$data = [
'user_id' => Auth::user() ? Auth::user()->id : null,
'subcategory_id' => $subcategory->id,
'duration_id' => $subcategory->duration->id,
'salon_id' => $subcategory->user_id,
];
$newData = (object) $data;
Session::put('cartItem', $newData);
Session::put('categoryIdForCart', $itemId);
return response()->json([
'success' => true,
]);
}
public function getSalonTherapistInfo(Request $request) {
dd("here");
}
public function addToCart(Request $request) {
$user = $this->user;
// dd($user);
if(!$request->category_id && !$request->thId && $request->booking_date && $request->booking_time ){
return response()->json([
'success' => false,
]);
}
$subcategory = SalonCategory::with('duration')->where('id',$request->category_id)->where('parent_category_id', '!=' ,0)->first();
if(!$subcategory) {
return response()->json([
'success' => false,
'category' => [],
]);
}
$data = [
'user_id' => $user->id,
'subcategory_id' => $subcategory->id,
'duration_id' => $subcategory->duration->id,
'salon_id' => $subcategory->user_id,
'therapist_id' => $request->thId,
'booking_date' => $request->booking_date,
'booking_time' => $request->booking_time
];
$cart = SalonCart::create($data);
$cartCount = SalonCart::where('user_id', $user->id)->count();
Session::put('cartItem', $cart);
return response()->json([
'success' => true,
'data' => $cart,
'count' => $cartCount
]);
}
public function getCart() {
$user = $this->user;
$cart = SalonCart::with('salon','treatment','duration', 'therapist')->where('user_id', $user->id)->get();
$cartCount = SalonCart::where('user_id', $user->id)->count();
return response()->json([
'success' => true,
'data' => $cart,
'count' => $cartCount
]);
}
public function deleteFromCart($itemId) {
if(!$itemId){
return response()->json([
'success' => false,
]);
}
$user = $this->user;
SalonCart::where('user_id', $user->id)->where('id', $itemId)->delete();
$cart = SalonCart::where('user_id', $user->id)->get();
$cartCount = SalonCart::where('user_id', $user->id)->count();
return response()->json([
'success' => true,
'data' => $cart,
'count' => $cartCount
]);
}
public function emptyCart(){
$user = $this->user;
// dd($user);
SalonCart::where('user_id', $user->id)->delete();
return response()->json([
'success' => true,
]);
}
public function payWithCash() {
$user = $this->user;
if(!$user) {
return response()->json([
'msg' => "User not found",
]);
}
// dd($user);
$total = $total_duration = 0;
$cartCount = SalonCart::where('user_id', $user->id)->count();
$cart = SalonCart::where('user_id', $user->id)->with('salon','treatment','duration')->get();
//salon
$salon = User::where('id', $cart[0]->salon_id)->with('salongallaryall','profile','address','workingdays')->first();
// salon address with geolocation
if(count($salon->address) != 0){
foreach($salon->address as $address){
if($address->is_main){
$add = $address->address.' '.$address->county.' '.$address->postcode;
}
}
// $add = "Gielly Green Boutique Salon, 42-44 George St, London W1U 7ES, UK";
//Formatted address
$formattedAddr = str_replace(' ','+',$add);
// dd($formattedAddr);
//Send request and receive json data by address
$geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false&key='.config('googlemaps.key'));
$output = json_decode($geocodeFromAddr);
// dd($output);
if(!empty($output)){
$addressComponents = $output->results[0]->address_components;
foreach($addressComponents as $addrComp){
if($addrComp->types[0] == 'postal_code'){
//Return the zipcode
$address_postcode = $addrComp->long_name;
$booking['postcode'] = $address_postcode;
}
}
}
$salon_geo_location = json_encode($output->results[0]->geometry->location);
$addr_latitude = !empty($output->results[0]->geometry->location->lat)?$output->results[0]->geometry->location->lat:'';
$addr_longitude = !empty($output->results[0]->geometry->location->lng)?$output->results[0]->geometry->location->lng:'';
$this->data['lon'] = $addr_longitude;
$this->data['lat'] = $addr_latitude;
}
$cartDetails = [];
foreach($cart as $key => $c){
$cartDetails[] = SalonCategory::with('duration')->where('id', $c->subcategory_id)->first();
$total += $cartDetails[$key]->duration->price;
$total_duration += $cartDetails[$key]->duration->duration;
}
$cartContent = $cartDetails;
if ($cartCount <= 0){
return "Your basket is empty";
} //endif
//register payment
DB::beginTransaction();
//Create order
$dataOrder = [
'user_id' => $user->id,
'amount' => $total,
'type' => 'cash',
];
$order = Order::create($dataOrder);
//create booking orders
$bookingOrders = [];
foreach($cart as $key=>$c) {
$item = SalonCart::with('salon', 'treatment', 'duration', 'therapist')->where('id', $c->id)->first();
$data = [
'order_id' => $order->id,
'user_id' => $user->id,
'salon_id' => $item->salon->id,
'is_active' => true,
'amount' => $item->duration->discounted_price,
'date' => $item->booking_date,
'hour' => $item->booking_time,
'duration' => $item->duration->duration,
'duration_min' => $item->duration->duration,
'massage_type' => null,
'address' => $add,
'location' => $add,
'locationGeo' => $salon_geo_location,
'orderInfo' => json_encode($item),
'updatedby_id' => $user->id,
];
//save booking order
$bookorder = BookingOrder::create($data);
//attach therapists to booking order
$bookorder->therapists()->attach($item->therapists_id,[
'date'=>$item->booking_date,
'duration'=>$item->duration->duration,
'hour'=>$item->booking_time
]);
//if voucher code was used, mark it as used
// if ($item->attributes->has_voucher){
// $voucherRepo->mark_as_used($item->attributes->voucher['code'],$item->getPriceSum(),$item->id);
// }
//end
$bookingOrders[] = $bookorder;
//end
}
//add mobile notifications
foreach($bookingOrders as $bo){
$notif_message = trans("schedules::booking.mobile_new_order",['number'=>$bo->id,'date'=>$bo->date_to_human,'hour'=>$bo->hour_to_human]);
$notif_users[] = $bo->user_id;
$boInfo = json_decode($bo->orderInfo,true);
$boTherapistsIds[] = $salon->id;
foreach($boTherapistsIds as $thid)
$notif_users[] = $thid;
// dd($notif_users);
//store notifications
foreach($notif_users as $user) {
NotifRepository::add($user,$notif_message, 'booking', 'New Booking');
}
} //endforeach
//start a new thread message
$repo = new BookingClass();
$repo->create_thread($bookorder);
//commit transaction order details
if ($order){
DB::commit();
//clear cart contents
foreach($cart as $c){
$c->delete();
}
//unset session booking key
//$request->session()->forget('booking');
// clear session
Session::put('salon_booking_date','');
Session::put('salon_booking_time','');
Session::put('selected_salon_therapist','');
//send email
// $this->sendEmailCheckout($bookingOrders);
}
else{
DB::rollBack();
}
return response()->json([
'success' => true,
]);
}
public function payWithToken() {
$gateway = Omnipay::create('SagePay\Direct');
$gateway->setVendor(env('SAGEPAY_VENDOR_NAME'));
$gateway->setTestMode(env('SAGEPAY_TEST_MODE'));
// $transactionId = time();
// Create a card object
$cardData = new \Omnipay\Common\CreditCard([
'firstName' => 'John',
'lastName' => 'Doe',
'number' => '4462000000000003', // Test credit card number
'expiryMonth' => '12',
'expiryYear' => '2023',
'cvv' => '123', // CVV code
]);
// Set the payment details
$transactionId = uniqid();
$amount = '10.00';
$currency = 'GBP';
// Create a deferred payment request
$response = $gateway->authorize([
'amount' => $amount,
'currency' => $currency,
'transactionId' => $transactionId,
'description' => 'Deferred payment',
'card' => $cardData, // Replace with the customer's card data
// 'token' => '{0F2F13A7-9596-4EBC-C817-0D2E5090AAFB}', // Replace with the customer's token for token-based payments
// 'billingAddress' => $billingData, // Replace with the customer's billing address data
// 'shippingAddress' => $shippingData, // Replace with the customer's shipping address data
'returnUrl' => 'https://google.com/',
'cancelUrl' => 'https://example.com/cancel',
'notifyUrl' => 'https://example.com/notify',
]);
// Check the response status and redirect the customer to the payment page
if ($response) {
echo json_encode($response);
die;
$response->redirect();
} else {
echo "Error: " . $response->getMessage();
}
}
public function stripeTest() {
// dd("here");
$stripe = new Stripe('sk_test_51H0QEqF8l8BBJQiwL6KbRUSL4v458ajWWRquSRz3MnVbtwJI8a1jKS34linZpx3UiRVUOTsXA4VYnKugRkIxXKzv005d4LXi9T');
$stripe->charge([
'amount' => 1000 * 100,
'currency' => 'inr',
'source' => 'tok_visa',
'description' => 'Test Charge By Alind'
]);
}
public function getSalonTherapistHours(Request $request) {
if (!$request->date)
{
$date = date('Y-m-d');
}
else
{
$date = $request->date;
}
Session::set('therapists_booking_info.'.$request->thID.'.date', $date);
$duration = SalonCategory::find($request->category_id)->duration;
$cartItem = collect();
$cartItem->duration_id = $duration->id;
Session::set('cartItem', $cartItem);
$repo = new BookingClass();
$hours = $repo->salon_th_hours($date, $request->thID);
$therapist = User::OfTherapists()
->where('id', $request->thID)
->first();
$dateC = Carbon::createFromFormat('Y-m-d',$date)->startOfDay();
$weekday = date('w',strtotime($dateC->format('Y-m-d')));
$twd = $therapist->workingdays()->where('dayoff',0)->where('weekday',$weekday)->first();
if($hours)
{
foreach ($hours as $k => $hour)
{
if(isset($hour['hour']))
{
$curr_hour_plus_duration = strtotime('+'.$duration.' minutes',strtotime($hour['hour']));
if(!$hour['available'])
{
unset($hours[$k]);
}
if($twd && ($curr_hour_plus_duration > strtotime($twd->bo_end_raw)))
{
unset($hours[$k]);
}
}
else
{
unset($hours[$k]);
}
}
}
return response()->json([
'status'=> true,
'count' => count($hours),
'hours' => $hours,
]);
}
}