GOOD SHELL MAS BOY
Server: Apache/2.4.52 (Ubuntu)
System: Linux vmi1836763.contaboserver.net 5.15.0-130-generic #140-Ubuntu SMP Wed Dec 18 17:59:53 UTC 2024 x86_64
User: www-data (33)
PHP: 8.4.10
Disabled: NONE
Upload Files
File: /var/www/console.fixgini.com/app/Http/Controllers/Seller/GIGController.php
<?php

namespace App\Http\Controllers\Seller;

use App\Models\Gig;
use App\Models\GigFav;
use App\Models\Country;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class GIGController extends Controller
{
    public function getNearbyGig(Request $request)
    {
        try {

            $perPage = $request->input('per_page', 20); // Default to 20 items per page
            $page = $request->input('page', 1); // Get the current page number
            $webgigs = Gig::with('shop', 'reviews', 'category')
                ->inRandomOrder()
                ->paginate($perPage, ['*'], 'page', $page);

            $gigs = Gig::with('shop', 'reviews', 'category')->where('status', 'active')->inRandomOrder()->limit(20)->get();
            return response()->json([
                'status' => 'success',
                'message' => 'Fetched successfully',
                'data' => $gigs,
                'gig' => $webgigs->items(),
                'current_page' => $webgigs->currentPage(),
                'total_pages' => $webgigs->lastPage()
            ], 200);
        } catch (\Throwable $th) {
            // Handle validation or query errors
            return response()->json(['status' => 'error', 'message' => 'Something went wrong.'], 500);
        }
    }

    public function getSimilarGig(Request $request)
    {
        try {
            // Validate the incoming request
            $validatedData = $request->validate([
                'category_id' => 'nullable|exists:categories,id',
            ]);
            $gig = Gig::with('shop', 'reviews', 'category')->where('category_id', $validatedData['category_id'])->inRandomOrder()->limit(20)->get();
            return response()->json(['status' => 'success', 'message' => 'Similar services found successfully', 'data' => $gig], 200);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'Similar services not found successfully', 'data' => $th->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        $currency = Country::select('symbol')->where('id', $user->nationality_id)->first();
        try {
            $validatedData = $request->validate([
                'shop_id' => 'required|exists:shops,id',
                'category_id' => 'required|exists:categories,id',
                'subcategory_id' => 'required|exists:categories,id',
                'title' => 'required|max:255|unique:gigs',
                'delivery_number' => 'nullable|numeric',
                'delivery_unit' => 'nullable|string|in:minutes,hours,days,weeks,months,years',
                'description' => 'required|string|max:1000',
                'image_urls' => 'required|array',
                'image_public_ids' => 'required',
                'price' => 'required|string',
            ]);
            $gig = Gig::create([
                'user_id' => $user->id,
                'shop_id' => $validatedData['shop_id'],
                'category_id' => $validatedData['category_id'],
                'subcategory_id' => $validatedData['subcategory_id'],
                'title' => ucwords($validatedData['title']),
                'slug' => Str::slug($validatedData['title']),
                'delivery_number' => $validatedData['delivery_number'],
                'delivery_unit' => $validatedData['delivery_unit'],
                'description' => $validatedData['description'],
                'image_urls' => $validatedData['image_urls'],
                'image_public_ids' => $validatedData['image_public_ids'],
                'price' => $validatedData['price'],
                'currency' => $currency->symbol,
            ]);
            return response()->json(['status' => 'success', 'message' => 'Service added successfully', 'data' => $gig]);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Seller service failed to upload successfully', 'data' => $e->getMessage()], 400);
        }
    }


    public function query(Request $request)
    {
        try {
            // Validate the incoming request
            $validatedData = $request->validate([
                'gig_slug' => 'nullable|exists:gigs,slug',
                'gig_id'   => 'nullable|exists:gigs,id',
            ]);

            // Ensure at least one of the parameters is provided
            if (empty($validatedData['gig_slug']) && empty($validatedData['gig_id'])) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Either gig_slug or gig_id must be provided.'
                ], 422);
            }

            // Query the gig based on the provided parameter
            $gig = Gig::when(!empty($validatedData['gig_slug']), function ($query) use ($validatedData) {
                $query->where('slug', $validatedData['gig_slug']);
            })
                ->when(!empty($validatedData['gig_id']), function ($query) use ($validatedData) {
                    $query->where('id', $validatedData['gig_id']);
                })
                ->firstOrFail();

            // Get the IP address of the current request
            $ipAddress = $request->ip();
            $gigId = $gig->id;

            // Check if this IP has viewed this gig recently
            $cacheKey = "gig_view_{$gigId}_{$ipAddress}";
            if (!Cache::has($cacheKey)) {
                // Increment views and set cache for this IP and gig to avoid duplicate counting
                $gig->increment('views');
                Cache::put($cacheKey, true, now()->addHours(1)); // Customize the timeframe as needed
            }

            // Load related data
            $gig->load([
                'subcategory',
                'faq',
                'category',
                'shop.city.state',
                'user' => function ($query) {
                    $query->select('id')->with('certificate');
                },
                'reviews.user'
            ]);

            return response()->json(['status' => 'success', 'message' => 'Gig queried successfully', 'data' => $gig]);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'Something went wrong. Please try again', 'data' => $th->getMessage()], 400);
        }
    }


    public function update(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'id' => 'required|exists:gigs,id',
                'user_id' => 'nullable|exists:users,id',
                'shop_id' => 'nullable|exists:shops,id',
                'category_id' => 'nullable|exists:categories,id',
                'subcategory_id' => 'nullable|exists:categories,id',
                'title' => 'nullable|max:255',
                'status' => 'nullable|max:255',
                'delivery_number' => 'nullable|numeric',
                'delivery_unit' => 'nullable|string|in:minutes,hours,days,weeks,months,years',
                'description' => 'nullable|string|max:1000',
                'image_urls' => 'nullable',
                'image_public_ids' => 'nullable',
                'price' => 'nullable|string',
                'currency' => 'nullable|string',
            ]);

            // Find the Gig
            $gig = Gig::find($validatedData['id']);

            $gig->update(array_filter([
                'user_id' => $validatedData['user_id'] ?? $gig->user_id,
                'shop_id' => $validatedData['shop_id'] ?? $gig->shop_id,
                'status' => $validatedData['status'] ?? $gig->status,
                'category_id' => $validatedData['category_id'] ?? $gig->category_id,
                'subcategory_id' => $validatedData['subcategory_id'] ?? $gig->subcategory_id,
                'title' => isset($validatedData['title']) ? ucwords($validatedData['title']) : $gig->title,
                'slug' => isset($validatedData['title']) ? Str::slug($validatedData['title']) : $gig->slug,
                'delivery_number' => $validatedData['delivery_number'] ?? $gig->delivery_number,
                'delivery_unit' => $validatedData['delivery_unit'] ?? $gig->delivery_unit,
                'description' => $validatedData['description'] ?? $gig->description,
                'image_urls' => isset($validatedData['image_urls']) ? $validatedData['image_urls'] : $gig->image_urls,
                'image_public_ids' => isset($validatedData['image_public_ids']) ? $validatedData['image_public_ids'] : $gig->image_public_ids,
                'price' => $validatedData['price'] ?? $gig->price,
                'currency' => $validatedData['currency'] ?? $gig->currency,
            ]));
            return response()->json(['status' => 'success', 'message' => 'Seller service updated successfully', 'data' => $gig]);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Seller service failed to update successfully', 'data' => $e->getMessage()], 400);
        }
    }

    public function sellerGig(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'shop_id' => 'required|exists:shops,id',
            ]);
            $active_gigs = Gig::with('subcategory')->where('shop_id', $validatedData['shop_id'])->where('status', 'active')->latest()->get();
            $inactive_gigs = Gig::with('subcategory')->where('shop_id', $validatedData['shop_id'])->where('status', 'inactive')->latest()->get();
            return response()->json(['status' => 'success', 'message' => 'Seller services fetched successfully', 'active' => $active_gigs, 'inactive' => $inactive_gigs], 200);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'Failed to fetch seller service', 'data' => $th->getMessage()], 400);
        }
    }


    public function allGig()
    {
        try {
            $gigs = Gig::with('reviews')->latest()->paginate(10);
            return response()->json(['status' => 'success', 'data' => $gigs]);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'data' => $th->getMessage()]);
        }
    }

    public function destroy(Request $request)
    {
        try {
            // Validate request
            $validatedData = $request->validate([
                'id' => 'required|exists:gigs,id',
            ]);

            // Find the gig by ID
            $gig = Gig::find($validatedData['id']);

            // Handle images
            $imagePublicIds = is_array($gig->image_public_ids) ? $gig->image_public_ids : json_decode($gig->image_public_ids, true);

            // Delete images from Cloudinary
            foreach ($imagePublicIds as $publicId) {
                cloudinary()->destroy($publicId);
            }

            // Delete the gig record
            $gig->delete();

            // Return success response
            return response()->json(['status' => 'success', 'message' => 'Gig deleted successfully.']);
        } catch (\Throwable $th) {
            // Return error response
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong. Please try again.',
                'data' => $th->getMessage()
            ], 400);
        }
    }

    public function destroyGigPhoto(Request $request)
    {
        try {
            // Validate request
            $validatedData = $request->validate([
                'gig_id' => 'required|exists:gigs,id',
                'public_id' => 'required',
            ]);

            // Find the gig by ID
            $gig = Gig::find($validatedData['gig_id']);

            if ($gig) {
                $publicId = $validatedData['public_id'];
                // Destroy the photo in Cloudinary
                cloudinary()->destroy($publicId);

                // Access the existing public IDs and URLs as arrays
                $imagePublicIds = $gig->image_public_ids; // This should be an array
                $imageUrls = $gig->image_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 gig's properties
                $gig->image_public_ids = $imagePublicIds; // Keep as an array
                $gig->image_urls = $imageUrls; // Keep as an array
                $gig->save();

                return response()->json(['status' => 'success', 'message' => 'Service Image deleted successfully.']);
            }

            return response()->json(['status' => 'error', 'message' => 'Gig 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);
        }
    }

    public function storeFavourite(Request $request)
    {
        try {
            // Validate input
            $validatedData = $request->validate([
                'gig_id' => 'nullable|exists:gigs,id',
                'gig_slug' => 'nullable|exists:gigs,slug',
            ]);

            if (empty($validatedData['gig_id']) && empty($validatedData['gig_slug'])) {
                return response()->json(['status' => 'error', 'message' => 'Either gig_id or gig_slug is required']);
            }

            $user = Auth::user();
            if (!$user) {
                return response()->json(['status' => 'error', 'message' => 'Login or register to continue']);
            }

            // Find the gig using either id or slug
            $gig = null;
            if (!empty($validatedData['gig_id'])) {
                $gig = Gig::find($validatedData['gig_id']);
            } elseif (!empty($validatedData['gig_slug'])) {
                $gig = Gig::where('slug', $validatedData['gig_slug'])->first();
            }

            if (!$gig) {
                return response()->json(['status' => 'error', 'message' => 'Gig not found']);
            }

            $user_id = $user->id;
            // Check if the favorite already exists
            $favourite = GigFav::where('user_id', $user_id)
                ->where('gig_id', $gig->id)
                ->first();

            if ($favourite) {
                if ($favourite->is_like) {
                    // If `is_like` is true and user toggles it, delete the record
                    $favourite->delete();
                    return response()->json(['status' => 'success', 'message' => 'Favorite removed']);
                } else {
                    // If `is_like` is false, set it to true
                    $favourite->is_like = true;
                    $favourite->save();
                    return response()->json(['status' => 'success', 'message' => 'Favorite added']);
                }
            } else {
                // If the favorite doesn't exist, create a new record
                GigFav::create([
                    'user_id' => $user_id,
                    'gig_id' => $gig->id,
                    'is_like' => true,
                ]);
                return response()->json(['status' => 'success', 'message' => 'Favorite added']);
            }
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => $th->getMessage()]);
        }
    }


    public function listFavourite()
    {
        try {
            $user_id = Auth::user()->id;
            $favourite = GigFav::with('gig.category')->where('user_id', $user_id)->limit(10)->get();
            if ($favourite) {
                return response()->json([
                    'data' => $favourite,
                    'status' => 'success',
                    'message' => 'Favorites fetched successfully',
                ], 200);
            } else {
                return response()->json([
                    'data' => [],
                    'status' => 'success',
                    'message' => 'No favorite services available for you',
                ], 404);
            }
        } catch (\Throwable $th) {
            return response()->json([
                'status' => 'error',
                'message' => $th->getMessage(),
            ], 500);
        }
    }
}