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/Order/SaveOrder.php
<?php

namespace App\Http\Controllers\Order;

use App\Models\User;
use App\Models\Order;
use App\Models\Wallet;
use App\Models\Address;
use App\Mail\OrderReceipt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use App\Mail\MailSellerForCustomerPurchase;

class SaveOrder extends Controller
{
    public function saveOrder(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'product_meta' => ['required'],
                'trx_id' => ['required'],
                'order_id' => ['required'],
                'customer_id' => ['required', 'exists:users,id'],
                'delivery_status' => ['nullable', 'string'],
                'payment_status' => ['nullable', 'string'],
                'order_status' => ['nullable'],
                'payment_method' => ['nullable'],
                'amount_paid' => ['required'],
                'shipping_fee' => ['required'],
                'quantity' => ['required', 'string'],
                'discount' => ['required', 'string'],
                'receipt_url' => ['required', 'string'],
            ]);


            // Decode the product_meta JSON string to get the product details
            $productMeta = json_decode($validatedData['product_meta'], true);

            // Extract all the product_ids from the product_meta
            $productId = collect($productMeta)->pluck('id');

            // Get all the seller_ids corresponding to the product_uuids from the products table
            $sellers = DB::table('products')
                ->whereIn('id', $productId)
                ->pluck('seller_id')
                ->unique();

            // Check if no sellers were found
            if ($sellers->isEmpty()) {
                throw new \Exception('No sellers found for the given products.');
            }

            // Fetch customer address
            $address = Address::where('customer_id', $validatedData['customer_id'])->first();
            $delivery_address = null;
            if ($address) {
                $delivery_address = json_encode([
                    'street' => $address->street,
                    'state' => $address->state,
                    'country' => $address->country,
                    'zipcode' => $address->zipcode,
                ]);
            }

            // Loop through each seller and create an order for each
            foreach ($sellers as $sellerId) {
                // Get all products for the current seller in one query
                $productsForSeller = DB::table('products')
                    ->whereIn('id', $productId)
                    ->where('seller_id', $sellerId)
                    ->get();

                // Skip if no products found for this seller
                if ($productsForSeller->isEmpty()) {
                    continue;
                }

                // Create an order for the current seller
                $order = Order::create([
                    'trx_id' => $validatedData['trx_id'],
                    'order_id' => $validatedData['order_id'],
                    'seller_id' => $sellerId,
                    'customer_id' => $validatedData['customer_id'],
                    'receipt_url' => $validatedData['receipt_url'],
                    'delivery_status' => $validatedData['delivery_status'] ?? 'pending',
                    'payment_status' => $validatedData['payment_status'] ?? 'pending',
                    'order_status' => $validatedData['order_status'] ?? 'pending',
                    'payment_method' => $validatedData['payment_method'],
                    'amount_paid' => $validatedData['amount_paid'],
                    'shipping_fee' => $validatedData['shipping_fee'],
                    'delivery_address' => $delivery_address,
                    'quantity' => collect($productMeta)
                        ->whereIn('id', $productsForSeller->pluck('id'))
                        ->sum('quantity'),
                    'discount' => $validatedData['discount'],
                    'product_meta' => json_encode($productsForSeller->toArray()), // Save only the products for this seller
                ]);

             


                // Send email notifications
                $customer = User::find($order->customer_id);
                if ($customer) {
                    $email = $customer->email;
                    $name = $customer->name;

                    // Send order receipt email to the customer
                    info($order);
                    Mail::to($email)->send(new OrderReceipt($order, $name));
                    $adminEmail = 'ayokahfoods@gmail.com';
                    Mail::to($adminEmail)->send(new OrderReceipt($order, $name));
                }

                // Fetch seller's details
                $seller = User::find($sellerId);
                if ($seller) {
                    $email = $seller->email;
                    $name = $seller->name;

                    // Send mail to the seller with the order details
                    Mail::to($email)->send(new MailSellerForCustomerPurchase($order, $name, $customer));
                } else {
                }
            }

            // Return all orders in the response
            return response()->json([
                'status' => 'success',
                'message' => 'Product successfully ordered',
                'data' => $validatedData,
            ], 200);
        } catch (\Exception $e) {
            Log::error("Order processing error: " . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 500);
        }
    }


    public function listCustomerOrder(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'customer_id' => ['required', 'exists:orders,customer_id'],
            ]);

            $orders = Order::with('product', 'customer')
                ->where('customer_id', $validatedData['customer_id'])
                ->get();

            if ($orders->isEmpty()) {
                return response()->json(['status' => 'error', 'message' => 'No orders found for this customer.', '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);
        }
    }


    public function listSellerOrder(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'seller_id' => ['required'],
            ]);

            $orders = Order::with('product', 'customer')
                ->where('seller_id', $validatedData['seller_id'])
                ->latest()->limit(10)->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);
        }
    }
    public function sellerOrders(Request $request)
    {
        // Capture the search query and cursor
        $searchQuery = $request->input('search');
        $cursor = $request->input('cursor', null);
        $seller_id = $request->input('seller_id');

        // Define how many items per page
        $perPage = 10;

        // Query the orders table with search and paginate using cursor pagination
        $query = Order::query()
            ->where('id', 'like', '%' . $searchQuery . '%')->where('seller_id', $seller_id);

        // Apply cursor pagination
        $orders = $query->cursorPaginate($perPage, ['*'], 'cursor', $cursor);

        // Prepare the response
        return response()->json([
            'status' => 'success',
            'data' => $orders->items(),
            'next_cursor' => $orders->nextCursor()?->encode() ?? null,
        ]);
    }

    public function allSellerOrder(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'seller_id' => ['required'],
            ]);

            $orders = Order::where('seller_id', $validatedData['seller_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);
        }
    }
   
}