D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
home
/
forge
/
ghanempharmacy.com
/
app
/
Http
/
Controllers
/
Web
/
Filename :
BundleController.php
back
Copy
<?php namespace App\Http\Controllers\Web; use App\Http\Controllers\Controller; use App\Models\ProductBundle; use App\Models\Cart; use App\Models\Product; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class BundleController extends Controller { public function index() { $bundles = ProductBundle::active() ->where('start_date', '<=', now()) ->where('end_date', '>=', now()) ->with('bundleItems.product') ->paginate(12); return view('web-views.products.bundles', compact('bundles')); } public function show($slug) { $bundle = ProductBundle::where('slug', $slug) ->where('status', 1) ->with('bundleItems.product') ->firstOrFail(); // Check if bundle is active (within date range) if ($bundle->start_date > now() || $bundle->end_date < now()) { toastr()->error(translate('bundle_not_available')); return redirect()->route('home'); } return view('web-views.products.bundle-details', compact('bundle')); } public function addToCart(Request $request) { $request->validate([ 'bundle_id' => 'required|exists:product_bundles,id', 'quantity' => 'integer|min:1|max:10' ]); $bundle = ProductBundle::with('bundleItems.product')->findOrFail($request->bundle_id); // Validate bundle is active if (!$bundle->status || $bundle->start_date > now() || $bundle->end_date < now()) { return response()->json([ 'status' => 'error', 'message' => translate('bundle_not_available') ], 400); } if (Auth::guard('customer')->check()) { $customerId = Auth::guard('customer')->id(); } else { if (!session()->has('guest_id')) { $guestId = \App\Models\GuestUser::create([ 'ip_address' => $request->ip(), 'created_at' => now(), ]); session()->put('guest_id', $guestId->id); } $customerId = session('guest_id'); } $quantity = $request->quantity ?? 1; try { // Check if bundle already in cart $existingCart = Cart::where('customer_id', $customerId) ->where('bundle_id', $bundle->id) ->first(); if ($existingCart) { return response()->json([ 'status' => 'info', 'message' => translate('bundle_already_in_cart') ]); } // 1. Validate Stock for ALL items first foreach ($bundle->bundleItems as $item) { if (!$item->product || !$item->product->status) { return response()->json([ 'status' => 'error', 'message' => translate('one_or_more_products_in_this_bundle_are_unavailable') ]); } $requiredQty = $item->quantity * $quantity; if ($item->product->current_stock < $requiredQty) { return response()->json([ 'status' => 'error', 'message' => translate('insufficient_stock_for_product') . ': ' . $item->product->name ]); } } // 2. Calculate Pricing Distribution // We need to distribute the total bundle price among items proportionally to their original price // to avoid zero-priced items and ensure tax/refund calculations work better. $bundlePrice = $bundle->getFinalPrice(); $totalOriginalPrice = 0; foreach ($bundle->bundleItems as $item) { $totalOriginalPrice += $item->product->unit_price * $item->quantity; } // Prevent division by zero if total original price is 0 (unlikely but possible) $totalOriginalPrice = $totalOriginalPrice > 0 ? $totalOriginalPrice : 1; // 3. Add Items to Cart foreach ($bundle->bundleItems as $item) { $product = $item->product; // Calculate item's share of the bundle price $itemOriginalTotal = $product->unit_price * $item->quantity; $itemShareOfBundlePrice = ($itemOriginalTotal / $totalOriginalPrice) * $bundlePrice; $unitPriceInCart = $itemShareOfBundlePrice / $item->quantity; $sellerId = $product->added_by == 'admin' ? 1 : $product->user_id; $sellerIs = $product->added_by; // Determine Cart Group ID $cartCheck = Cart::where([ 'customer_id' => $customerId, 'is_guest' => Auth::guard('customer')->check() ? 0 : 1, 'seller_id' => $sellerId, 'seller_is' => $sellerIs ])->first(); if ($cartCheck) { $cartGroupId = $cartCheck->cart_group_id; } else { $prefix = Auth::guard('customer')->check() ? Auth::guard('customer')->id() : 'guest'; $cartGroupId = $prefix . '-' . \Illuminate\Support\Str::random(5) . '-' . time(); } $tax = \App\Utils\Helpers::tax_calculation($product, $unitPriceInCart, $product->tax, $product->tax_type); Cart::create([ 'customer_id' => $customerId, 'cart_group_id' => $cartGroupId, 'is_guest' => Auth::guard('customer')->check() ? 0 : 1, 'product_id' => $product->id, 'product_type' => $product->product_type, 'quantity' => $item->quantity * $quantity, 'price' => $unitPriceInCart, 'discount' => 0, 'tax' => $tax, 'tax_model' => $product->tax_model, 'is_checked' => 1, 'slug' => $product->slug, 'name' => $product->name, 'thumbnail' => $product->thumbnail, 'bundle_id' => $bundle->id, 'bundle_name' => $bundle->title, 'color' => null, 'variant' => null, 'choices' => json_encode([]), 'variations' => json_encode([]), 'shop_info' => $product->added_by == 'admin' ? getInHouseShopConfig(key: 'name') : ($product->seller->shop->name ?? translate('unavailable')), 'seller_id' => $sellerId, 'seller_is' => $sellerIs, 'shipping_cost' => 0, 'shipping_type' => 'order_wise', 'original_price' => $product->unit_price, 'created_at' => now(), 'updated_at' => now(), ]); } cacheRemoveByType(type: 'carts'); return response()->json([ 'status' => 'success', 'message' => translate('bundle_added_to_cart_successfully'), 'cart_count' => Cart::where('customer_id', $customerId)->where('is_guest', Auth::guard('customer')->check() ? 0 : 1)->count() ]); } catch (\Exception $e) { // Log the error for debugging return response()->json([ 'status' => 'error', 'message' => $e->getMessage() . ' Line: ' . $e->getLine() ], 500); } } /* public function selectGift(Request $request) { $request->validate([ 'bundle_id' => 'required|exists:product_bundles,id', 'gift_products' => 'required|array' ]); $bundle = ProductBundle::findOrFail($request->bundle_id); $customerId = Auth::guard('customer')->id() ?? session()->get('guest_id'); if (!$customerId) { return response()->json([ 'status' => 'error', 'message' => translate('please_login_first') ], 401); } // Validate gift configuration if (!$bundle->hasGift() || $bundle->gift_type !== 'product_wise') { return response()->json([ 'status' => 'error', 'message' => translate('invalid_gift_configuration') ], 400); } // Validate product selection $validationResult = $bundle->validateGiftProductSelection($request->gift_products); if (!$validationResult['valid']) { return response()->json([ 'status' => 'error', 'message' => $validationResult['message'] ], 400); } try { // Find existing cart item to get quantity $existingCart = Cart::where('customer_id', $customerId) ->where('bundle_id', $bundle->id) ->first(); if (!$existingCart) { return response()->json([ 'status' => 'error', 'message' => translate('bundle_not_found_in_cart') ], 404); } $bundleQty = $existingCart->quantity; // Use the bundle quantity // Remove existing gift items for this bundle from Cart // Identify gifts as: bundle_id matches, and product_id is NOT in the main bundle items $bundleItemProductIds = $bundle->bundleItems->pluck('product_id')->toArray(); Cart::where('customer_id', $customerId) ->where('bundle_id', $bundle->id) ->whereNotIn('product_id', $bundleItemProductIds) ->delete(); // Add new gift items to Cart foreach ($request->gift_products as $giftProductId) { $product = Product::find($giftProductId); if ($product) { Cart::create([ 'customer_id' => $customerId, 'is_guest' => Auth::guard('customer')->check() ? 0 : 1, 'product_id' => $product->id, 'product_type' => $product->product_type, 'quantity' => $bundleQty, // 1 gift per bundle unit 'price' => 0, 'discount' => 0, 'tax' => 0, 'slug' => $product->slug, 'name' => $product->name, 'thumbnail' => $product->thumbnail, 'bundle_id' => $bundle->id, 'bundle_name' => $bundle->title . ' (' . translate('Gift') . ')', 'has_bundle_gift' => 0, // It's the gift itself 'shop_info' => $product->added_by == 'admin' ? getInHouseShopConfig(key: 'name') : $product->seller->shop->name, 'seller_id' => $product->user_id, 'seller_is' => $product->added_by, 'created_at' => now(), 'updated_at' => now(), ]); } } // Also update the main items to store the selection (Legacy/UI support) Cart::where('customer_id', $customerId) ->where('bundle_id', $bundle->id) ->update([ 'bundle_gift_products' => json_encode($request->gift_products) ]); return response()->json([ 'status' => 'success', 'message' => translate('gift_products_selected_successfully') ]); } catch (\Exception $e) { return response()->json([ 'status' => 'error', 'message' => translate('error_occurred') ], 500); } } */ }