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/api.ayokah.co.uk/app/Http/Controllers/CustomerController.php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Order;
use App\Models\Coupon;
use App\Models\Address;
use App\Models\Product;
use App\Models\Wishlist;
use Illuminate\Http\Request;
use App\Models\NotificationSetting;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Models\ShippingFee;

class CustomerController extends Controller
{
    public function placeOrder(Request $request)
    {
        try {
            // Validate the incoming request data
            $validatedData = $request->validate([
                'product_id' => ['required', 'string', 'exists:products,id'],
                'seller_id' => ['nullable', 'string', 'exists:sellers,id'],
                'customer_id' => ['required', 'numeric', 'exists:users,id'],
                'delivery_status' => ['nullable', 'string'],
                'payment_status' => ['nullable', 'string'],
                'order_status' => ['nullable', 'string'],
                'payment_method' => ['nullable', 'string'],
                'amount_paid' => ['required', 'string'],
                'shipping_fee' => ['required', 'string'],
                'tracking_id' => ['nullable', 'string'],
                'delivery_address' => ['required', 'string'],
                'quantity' => ['required', 'string'],
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['error' => $e->errors()], 422);
        }

        try {
            $user = User::findOrFail($request->customer_id);
            if ($user->role === 'seller') {
                if ($request->has('id')) {
                    $order = Order::findOrFail($request->id);
                    $action = 'updated';
                } else {
                    $order = new Order();
                    $action = 'placed';
                }
                $order->fill($validatedData);
                $order->save();

                return response()->json(['status' => 'success', 'message' => 'Order ' . $action . ' successfully', 'order' => $order], 200);
            } else {
                return response()->json(['status' => 'error', 'message' => 'Only sellers can update order status'], 403);
            }
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['status' => 'error', 'message' => 'User not found'], 404);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Internet error occured. Please, try again later.'], 500);
        }
    }

    public function storeReview(Request $request)
    {
        try {
            // Validate the incoming request data
            $validatedData = $request->validate([
                'product_id' => ['required', 'string', 'exists:products,id'],
                'customer_id' => ['nullable', 'string', 'exists:orders,id'],
                'comment' => ['required', 'string'],
                'rating' => ['nullable', 'numeric'],
            ]);

            $user = User::findOrFail($request->customer_id);
            if ($user->role === 'seller') {
                if ($request->has('id')) {
                    $order = Order::findOrFail($request->id);
                    $action = 'updated';
                } else {
                    $order = new Order();
                    $action = 'saved';
                }
                $order->fill($validatedData);
                $order->save();

                return response()->json(['message' => 'Order detail ' . $action . ' successfully', 'order' => $order], 200);
            } else {
                return response()->json(['error' => 'Only sellers can update order status'], 403);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function updateOrCreateAddress(Request $request)
    {
        try {
            // Validate the request data
            $validatedData = $request->validate([
                'user_id' => 'required|exists:users,id',
                'street' => 'required|string|max:255',
                'postcode' => 'nullable|string',
                'state' => 'required|string',
                'city' => 'nullable|string',
                'country' => 'required|string|max:100',
                'longitude' => 'required|max:100',
                'latitude' => 'required|max:100',
            ]);

            // Check if address already exists for this customer_id (user_id)
            $address = Address::where('customer_id', $validatedData['user_id'])->first();

            if ($address) {
                // Update the existing address
                $address->update($validatedData);
                $action = 'updated';
            } else {
                // Create a new address if none is found
                $address = Address::create([
                    'customer_id' => $validatedData['user_id'],
                    'street' => $validatedData['street'],
                    'postcode' => $validatedData['postcode'],
                    'state' => $validatedData['state'],
                    'city' => $validatedData['city'],
                    'country' => $validatedData['country'],
                    'longitude' => $validatedData['longitude'],
                    'latitude' => $validatedData['latitude'],
                ]);
                $action = 'created';
            }

            // Return a success response
            return response()->json([
                'message' => 'Shipping address ' . $action . ' successfully',
                'data' => $address
            ], 200);
        } catch (\Exception $e) {
            // Log the error and return a failure response
            info('Mail the admin system about this error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Check your inputs and please try again'
            ], 500);
        }
    }
 

    public function myAddress(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'customer_id' => ['required'],
            ]);
            $address = Address::where('customer_id', $validatedData['customer_id'])->first();
            if ($address) {
                return response()->json(['status' => 'success', 'data' => $address], 200);
            } else {
                return response()->json(['message' => 'No available shipping address', 'data' => []], 404);
            }
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Unknow error ' . $e->getMessage()], 500);
        }
    }

    public function wishlist(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'customer_id' => ['required', 'exists:wishlists,user_id'],
            ]);
            $wishlist = Wishlist::with('product')->with('category')->where('user_id', $validatedData['customer_id'])->get();

            if ($wishlist->isEmpty()) {
                return response()->json(['status' => 'error', 'message' => 'No available wishlist', 'data' => []], 200);
            }

            return response()->json(['status' => 'success', 'data' => $wishlist], 200);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'You do not have wishlist items'], 500);
        }
    }
    public function deleteWishlist(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'customer_id' => ['nullable', 'exists:wishlists,user_id'],
            ]);
            $wishlist = Wishlist::where('user_id', $validatedData['customer_id'])->first();
            $wishlist->delete();
            return response()->json(['status' => 'success', 'message' => 'deleted successfully'], 200);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Unknow error ' . $e->getMessage()], 500);
        }
    }
    public function OrderHistory(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'customer_id' => ['required', 'exists:orders,customer_id'],
            ]);
            $order = Order::where('customer_id', $validatedData['customer_id'])->get();
            foreach ($order as $o) {
                // Decode the product_meta JSON string to get the products in the order
                $productMeta = json_decode($o->product_meta, true);

                // Extract product IDs from the product_meta
                $productIds = collect($productMeta)->pluck('id');

                // Fetch product details based on product IDs
                $products = Product::whereIn('id', $productIds)->get();
                // Add the products to the order
                $orderWithProducts = $order->toArray(); // Convert order to array
                $orderWithProducts['product'] = $products; // Add product details to order
                $combinedData[] = $orderWithProducts;
            }
            info($combinedData);
            if ($order->isEmpty()) {
                return response()->json(['status' => 'error', 'message' => 'No available order', 'data' => []], 404);
            }

            return response()->json(['status' => 'success', 'data' => $combinedData, 'products' => $orderWithProducts], 200);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'You do not have order items'], 500);
        }
    }
    public function getVoucher()
    {
        try {
            $today = now()->toDateString(); // Get today's date in 'Y-m-d' format
            $coupon = Coupon::with('seller')
                ->whereDate('expiry_date', '!=', $today)
                ->get();

            if ($coupon->isEmpty()) {
                return response()->json(['status' => 'error', 'message' => 'No available voucher', 'data' => []], 200);
            }

            return response()->json(['status' => 'success', 'data' => $coupon], 200);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'No available voucher'], 500);
        }
    }
    public function updateSettings(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'send_email' => 'sometimes|boolean',
                'send_new_product' => 'sometimes|boolean',
                'send_new_coupon' => 'sometimes|boolean',
                'send_new_offer' => 'sometimes|boolean',
                'user_id' => 'required|exists:users,id',
            ]);

            // Find existing notification settings or create a new record if none exist
            $settings = NotificationSetting::firstOrNew(['user_id' => $validatedData['user_id']]);

            // Convert boolean values to integer (0 or 1)
            $settings->send_email = isset($validatedData['send_email']) ? (int) $validatedData['send_email'] : $settings->send_email;
            $settings->send_new_product = isset($validatedData['send_new_product']) ? (int) $validatedData['send_new_product'] : $settings->send_new_product;
            $settings->send_new_coupon = isset($validatedData['send_new_coupon']) ? (int) $validatedData['send_new_coupon'] : $settings->send_new_coupon;
            $settings->send_new_offer = isset($validatedData['send_new_offer']) ? (int) $validatedData['send_new_offer'] : $settings->send_new_offer;


            $settings->save();
            info($settings);
            return response()->json(['status' => 'success', 'message' => 'Notification settings updated successfully.', 'data' => $settings], 200);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Failed to update notification settings.'], 500);
        }
    }


    public function getSettings(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'user_id' => 'required|exists:users,id',
            ]);

            $notificationSettings = NotificationSetting::where('user_id', $validatedData['user_id'])->first();
            info($notificationSettings);
            return response()->json(['status' => 'success', 'data' => $notificationSettings], 200);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Failed to retrieve notification settings.'], 500);
        }
    }

    public function saveShopLike(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'shop_id' => ['required', 'numeric', 'exists:sellers,id'],
                'user_id' => ['required', 'numeric', 'exists:users,id'],
            ]);

            $existingLike = Wishlist::where('shop_id', $validatedData['shop_id'])
                ->where('user_id', $validatedData['user_id'])
                ->first();

            if ($existingLike) {
                // If a like already exists, delete it (unlike the shop)
                $existingLike->delete();
                return response()->json(['status' => 'success', 'message' => 'Unliked'], 200);
            } else {
                // If no like exists, create a new one (like the shop)
                Wishlist::create($validatedData);
                return response()->json(['status' => 'success', 'message' => 'Liked'], 200);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['status' => 'error', 'message' => 'Validation Failed', 'data' => $e->errors()], 422);
        } catch (\Exception $e) {
            info($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Failed to process request', 'data' => $e->getMessage()], 500);
        }
    }

    public function fetchShopLike(Request $request)
    {
        $validatedData = $request->validate([
            'user_id' => ['required', 'numeric', 'exists:users,id'],
            'shop_id' => ['required', 'numeric', 'exists:sellers,id'],
        ]);

        $exists = Wishlist::where('user_id', $validatedData['user_id'])
            ->where('shop_id', $validatedData['shop_id'])
            ->exists();

        return response()->json(['status' => 'success', 'data' => $exists], 200);
    }

    public function queryProduct(Request $request)
    {
        try {

            $validatedData = $request->validate([
                'uuid' => 'required|exists:products,uuid',
            ]);
            $product = Product::with('category')->where('uuid', $validatedData['uuid'])->first();

            if ($product) {
                return response()->json(['status' => 'success', 'data' => $product], 200);
            } else {
                return response()->json(['status' => 'error', 'message' => 'product not found!'], 404);
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 404);
        }
    }
    public function shippingFee()
    {
        try {
            $shippingFee = ShippingFee::inRandomOrder()->get();
            if ($shippingFee) {
                return response()->json(['status' => 'success', 'data' => $shippingFee], 200);
            } else {
                return response()->json(['status' => 'error', 'message' => 'shipping not found!'], 404);
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 404);
        }
    }
    public function orderDetail(Request $request)
    {
        try {
            $data = $request->validate([
                'customer_id' => ['required', 'exists:orders,customer_id'],
                'id' => ['required', 'exists:orders,id'],
            ]);

            $orders = Order::where('customer_id', $data['customer_id'])->where('id', $data['id'])->get();

            if ($orders->isEmpty()) {
                return response()->json(['status' => 'error', 'message' => 'No orders found for this seller.', 'data' => []], 404);
            }

            return response()->json(['status' => 'success', 'message' => 'Orders fetched successfully', 'data' => $orders], 200);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Network Issue! Please, try again later.', 'data' => $e->getMessage()], 500);
        }
    }
}