File: /var/www/console.fixgini.com/app/Http/Controllers/Seller/ShopController.php
<?php
namespace App\Http\Controllers\Seller;
use App\Models\City;
use App\Models\Shop;
use App\Models\User;
use App\Models\State;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class ShopController extends Controller
{
public function getNearbyShop(Request $request)
{
try {
// $user = Auth::user
$shops = Shop::with('category')->where('status', 'verified')->inRandomOrder()->limit(10)->get();
return response()->json(['status' => 'success', 'message' => 'Shops found.', 'data' => $shops]);
} catch (\Throwable $th) {
// Return error message
return response()->json(['status' => 'error', 'message' => $th->getMessage()]);
}
}
private function googleGeo()
{
$userLat = 'USER_LATITUDE';
$userLng = 'USER_LONGITUDE';
$vendorLat = 'VENDOR_LATITUDE';
$vendorLng = 'VENDOR_LONGITUDE';
$apiKey = 'YOUR_GOOGLE_API_KEY';
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$userLat,$userLng&destinations=$vendorLat,$vendorLng&key=$apiKey";
$response = file_get_contents($url);
$data = json_decode($response, true);
if (!empty($data['rows'][0]['elements'][0]['distance'])) {
$distanceInKm = $data['rows'][0]['elements'][0]['distance']['value'] / 1000; // distance in kilometers
echo "Distance: " . $distanceInKm . " km";
} else {
echo "Distance information not available.";
}
}
// Haversine formula to calculate distance between two points
private function haversine($lat1, $lon1, $lat2, $lon2)
{
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
// Convert latitudes to radians
$lat1 = deg2rad($lat1);
$lat2 = deg2rad($lat2);
// Apply the Haversine formula
$a = pow(sin($dLat / 2), 2) + pow(sin($dLon / 2), 2) * cos($lat1) * cos($lat2);
$rad = 6371; // Radius of the Earth in kilometers
$c = 2 * asin(sqrt($a));
return $rad * $c; // Distance in kilometers
}
public function query(Request $request)
{
try {
$shop_id = $request->input('shop_id');
$shop_slug = $request->input('shop_slug');
$shop = Shop::with(['gigs.reviews'])
->when($shop_id, function ($query) use ($shop_id) {
$query->where('id', $shop_id);
})
->when($shop_slug, function ($query) use ($shop_slug) {
$query->orWhere('slug', $shop_slug);
})
->first();
if ($shop) {
return response()->json(['status' => 'success', 'data' => $shop]);
} else {
return response()->json(['status' => 'error', 'data' => []]);
}
} catch (\Throwable $th) {
return response()->json(['status' => 'error', 'message' => $th->getMessage()]);
}
}
public function getState()
{
$state = State::all();
if ($state) {
return response()->json(['status' => 'success', 'data' => $state]);
} else {
return response()->json(['status' => 'error', 'data' => []]);
}
}
public function getStateCity(Request $request)
{
try {
$validatedData = $request->validate([
'state_id' => 'required|exists:states,id',
]);
$state_id = $request->input('state_id');
$cities = City::where('state_id', $state_id)->get();
if ($cities) {
return response()->json(['status' => 'success', 'message' => 'Cities fetched successfully.', 'data' => $cities], 200);
}
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json([
'status' => 'error',
'message' => 'Cities not fetched successfully',
'data' => $e->getMessage()
], 400);
}
}
public function shop(Request $request)
{
$shop = Shop::where('user_id', $request->user_id)->first();
if ($shop) {
return response()->json([
'status' => 'success',
'message' => 'Seller shop retrieved successfully.',
'data' => $shop
], 200);
} else {
return response()->json([
'status' => 'error',
'message' => 'Shop not found.',
], 404);
}
}
public function store(Request $request)
{
try {
$validatedData = $request->validate([
'user_id' => 'required|unique:shops,user_id',
'category_id' => 'required|exists:categories,id',
'profile_photo_url' => 'required',
'latitude' => 'nullable',
'longitude' => 'nullable',
'profile_photo_public_id' => 'nullable',
'workshop_photo_urls' => 'required|array',
'workshop_photo_public_ids' => 'required|array',
'name' => 'required|unique:shops,name|max:100',
'description' => 'required|string|max:2000',
'address' => 'sometimes|string|max:200',
'city_id' => 'required|exists:cities,id',
'state_id' => 'required|exists:states,id',
'country_id' => 'required|exists:countries,id',
]);
User::where('id', $validatedData['user_id'])->update([
'profile_photo_url' => $validatedData['profile_photo_url'],
]);
$shop = Shop::create([
'user_id' => $validatedData['user_id'],
'category_id' => $validatedData['category_id'],
'latitude' => $validatedData['latitude'],
'longitude' => $validatedData['longitude'],
'profile_photo_url' => $validatedData['profile_photo_url'],
'profile_photo_public_id' => $validatedData['profile_photo_public_id'],
'workshop_photo_urls' => $validatedData['workshop_photo_urls'],
'workshop_photo_public_ids' => $validatedData['workshop_photo_public_ids'],
'name' => ucwords($validatedData['name']),
'slug' => Str::slug($validatedData['name']), // Ensure the slug is unique and properly formatted
'description' => $validatedData['description'],
'address' => $validatedData['address'],
'country_id' => $validatedData['country_id'],
'state_id' => $validatedData['state_id'],
'city_id' => $validatedData['city_id'],
]);
return response()->json(['status' => 'success', 'message' => 'Seller shop created successfully.', 'data' => $shop], 200);
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json([
'status' => 'error',
'message' => 'Seller shop not created successfully',
'data' => $e->getMessage()
], 400);
}
}
public function update(Request $request)
{
try {
$user = Auth::user();
$shop_id = $user->shop->id;
// Validate input data
$validatedData = $request->validate([
'category_id' => 'nullable',
'name' => 'nullable|max:100',
'description' => 'nullable|string|max:2000',
'address' => 'nullable|string|max:200',
'city_id' => 'nullable|exists:cities,id',
'state_id' => 'nullable|exists:states,id',
'profile_photo_url' => 'required',
'profile_photo_public_id' => 'required',
'workshop_photo_urls' => 'nullable|array',
'workshop_photo_public_ids' => 'nullable|array',
]);
// Find the shop by ID
$shop = Shop::find($shop_id);
// Update the shop's attributes
$shop->update([
'category_id' => $validatedData['category_id'] ?? $shop->category_id,
'name' => isset($validatedData['name']) ? ucwords($validatedData['name']) : $shop->name,
'slug' => isset($validatedData['name']) ? Str::slug($validatedData['name']) : $shop->slug,
'description' => isset($validatedData['description']) ? ucfirst($validatedData['description']) : $shop->description,
'address' => $validatedData['address'] ?? $shop->address,
'state_id' => $validatedData['state_id'] ?? $shop->state_id,
'city_id' => $validatedData['city_id'] ?? $shop->city_id,
'profile_photo_url' => $validatedData['profile_photo_url'] ?? $shop->profile_photo_url,
'profile_photo_public_id' => $validatedData['profile_photo_public_id'] ?? $shop->profile_photo_public_id,
'workshop_photo_urls' => isset($validatedData['workshop_photo_urls']) ? $validatedData['workshop_photo_urls'] : $shop->workshop_photo_urls,
'workshop_photo_public_ids' => isset($validatedData['workshop_photo_public_ids']) ? $validatedData['workshop_photo_public_ids'] : $shop->workshop_photo_public_ids,
]);
return response()->json([
'status' => 'success',
'message' => 'Shop updated successfully.',
'data' => $shop
], 200);
} catch (\Exception $e) {
// Log the error and return a response
Log::error($e->getMessage());
return response()->json([
'status' => 'error',
'message' => 'Shop not updated successfully',
'data' => $e->getMessage()
], 400);
}
}
public function destroy(Request $request)
{
try {
$validatedData = $request->validate([
'id' => 'required|exists:shops,id',
]);
$shop = Shop::find($validatedData['id']);
// Delete profile photo from Cloudinary
if ($shop->profile_photo_public_id) {
cloudinary()->destroy($shop->profile_photo_public_id);
}
// Delete workshop photos from Cloudinary
$workshop_photo_public_ids = json_decode($shop->workshop_photo_public_ids, true);
if (is_array($workshop_photo_public_ids)) {
foreach ($workshop_photo_public_ids as $publicId) {
cloudinary()->destroy($publicId);
}
}
// Delete the shop from the database
$shop->delete();
return response()->json(['status' => 'success', 'message' => 'Seller shop deleted successfully.'], 200);
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json(['status' => 'error', 'message' => 'Seller shop not deleted successfully', 'data' => $e->getMessage()], 400);
}
}
public function destroyPhoto(Request $request)
{
try {
$user = Auth::user();
$shop = Shop::where('user_id', $user->id)->first();
if ($shop && $shop->profile_photo_public_id) {
$publicId = $shop->profile_photo_public_id;
// Destroy the photo in Cloudinary
cloudinary()->destroy($publicId);
// Remove the photo URL and public ID from the database
$shop->profile_photo_public_id = null;
$shop->profile_photo_url = null;
$shop->save();
// Remove from user table
$user->profile_photo_url = null;
$user->save();
return response()->json(['status' => 'success', 'message' => 'Profile photo deleted successfully.', 'data' => $shop]);
}
return response()->json(['status' => 'error', 'message' => 'Shop or profile photo not found.'], 404);
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json(['status' => 'error', 'message' => 'Error deleting profile photo', 'data' => $e->getMessage()], 400);
}
}
public function destroyWorkShop(Request $request)
{
try {
// Validate request
$validatedData = $request->validate([
'public_id' => 'required',
]);
// Find the shop by ID
$user = Auth::user();
$shop = Shop::where('user_id', $user->id)->first();
if ($shop) {
$publicId = $validatedData['public_id'];
// Destroy the photo in Cloudinary
cloudinary()->destroy($publicId);
// Access the existing public IDs and URLs as arrays
$imagePublicIds = $shop->workshop_photo_public_ids; // This should be an array
$imageUrls = $shop->workshop_photo_urls; // This should be an array
// Remove the public ID and its corresponding URL
$key = array_search($publicId, $imagePublicIds);
if ($key !== false) {
unset($imagePublicIds[$key]);
unset($imageUrls[$key]);
}
// Re-index the arrays to ensure sequential keys (optional)
$imagePublicIds = array_values($imagePublicIds);
$imageUrls = array_values($imageUrls);
// Update the shop's properties
$shop->workshop_photo_public_ids = $imagePublicIds; // Keep as an array
$shop->workshop_photo_urls = $imageUrls; // Keep as an array
$shop->save();
return response()->json(['status' => 'success', 'message' => 'Shop Workshop photo deleted successfully.', 'data' => $shop]);
}
return response()->json(['status' => 'error', 'message' => 'shop not found.'], 404);
} catch (\Throwable $th) {
// Return error response
return response()->json([
'status' => 'error',
'message' => 'Something went wrong. Please try again.',
'data' => $th->getMessage()
], 400);
}
}
}