
PK 
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Wishlist;
use App\Models\Cart;
use Illuminate\Support\Str;
use Helper;
class CartController extends Controller
{
protected $product=null;
public function __construct(Product $product){
$this->product=$product;
}
public function couponRemove()
{
session()->forget('coupon');
return back()->with('success', 'Coupon removed successfully.');
}
public function addToCart(Request $request){
if (empty($request->slug)) {
request()->session()->flash('error','Invalid Products');
return back();
}
$product = Product::where('slug', $request->slug)->first();
if (empty($product)) {
request()->session()->flash('error','Invalid Products');
return back();
}
// Check stock first
if ($product->stock <= 0) {
request()->session()->flash('error','Out of stock');
return back();
}
$already_cart = Cart::where('user_id', auth()->user()->id)
->where('order_id',null)
->where('product_id', $product->id)
->first();
if($already_cart) {
// Check if adding one more would exceed stock
if ($product->stock < ($already_cart->quantity + 1)) {
request()->session()->flash('error','Stock not sufficient!');
return back();
}
$already_cart->quantity = $already_cart->quantity + 1;
$already_cart->amount = $product->price + $already_cart->amount;
$already_cart->save();
} else {
// For new cart item, check stock is at least 1
if ($product->stock < 1) {
request()->session()->flash('error','Out of stock!');
return back();
}
$cart = new Cart;
$cart->user_id = auth()->user()->id;
$cart->product_id = $product->id;
$cart->price = ($product->price-($product->price*$product->discount)/100);
$cart->quantity = 1;
$cart->amount = $cart->price * $cart->quantity;
$cart->save();
// Delete wishlist item instead of updating cart_id
Wishlist::where('user_id', auth()->user()->id)
->where('product_id', $product->id)
->delete();
}
request()->session()->flash('success','Product successfully added to cart');
return back();
}
public function singleAddToCart(Request $request)
{
if (!auth()->check()) {
return response()->json([
'status' => false,
'message' => 'You must be logged in to add products to your cart.',
'redirect' => route('login.form')
], 401);
}
$request->validate([
'slug' => 'required|string',
'quantity' => 'required|integer|min:1'
]);
$product = Product::where('slug', $request->slug)->first();
if (!$product) {
return response()->json([
'status' => false,
'message' => 'Product not found'
], 404);
}
if ($product->stock <= 0) {
return response()->json([
'status' => false,
'message' => 'This product is out of stock'
], 400);
}
$requestedQty = (int)$request->quantity;
if ($requestedQty > $product->stock) {
return response()->json([
'status' => false,
'message' => 'Only '.$product->stock.' items available'
], 400);
}
$already_cart = Cart::where('user_id', auth()->id())
->where('order_id', null)
->where('product_id', $product->id)
->first();
try {
if ($already_cart) {
$newQty = $already_cart->quantity + $requestedQty;
if ($newQty > $product->stock) {
return response()->json([
'status' => false,
'message' => 'You already have '.$already_cart->quantity.' in cart. Only '.($product->stock - $already_cart->quantity).' more available'
], 400);
}
$already_cart->quantity = $newQty;
$already_cart->amount = ($product->price - ($product->price * $product->discount)/100) * $newQty;
$already_cart->save();
} else {
$price = $product->price - ($product->price * $product->discount)/100;
$cart = new Cart;
$cart->user_id = auth()->id();
$cart->product_id = $product->id;
$cart->price = $price;
$cart->quantity = $requestedQty;
$cart->amount = $price * $requestedQty;
$cart->save();
// Update wishlist if exists
Wishlist::where('user_id', auth()->id())
->where('cart_id', null)
->where('product_id', $product->id)
->update(['cart_id' => $cart->id]);
}
return response()->json([
'status' => true,
'message' => 'Product added to cart successfully',
//'cart_count' => Cart::where('user_id', auth()->id())->where('order_id', null)->count()
'cart_count' => Helper::cartCount() // Using your Helper function
]);
} catch (\Exception $e) {
return response()->json([
'status' => false,
'message' => 'Failed to add to cart: '.$e->getMessage()
], 500);
}
}
public function cartDelete(Request $request){
$cart = Cart::find($request->id);
if ($cart) {
$cart->delete();
request()->session()->flash('success','Cart successfully removed');
return back();
}
request()->session()->flash('error','Error please try again');
return back();
}
public function cartUpdate(Request $request){
if($request->quant){
$error = array();
$success = '';
foreach ($request->quant as $k=>$quant) {
$id = $request->qty_id[$k];
$cart = Cart::find($id);
if($quant > 0 && $cart) {
// Check stock before updating
if($cart->product->stock < $quant){
request()->session()->flash('error','Out of stock');
return back();
}
$cart->quantity = ($cart->product->stock > $quant) ? $quant : $cart->product->stock;
if ($cart->product->stock <= 0) {
continue;
}
$after_price = ($cart->product->price-($cart->product->price*$cart->product->discount)/100);
$cart->amount = $after_price * $quant;
$cart->save();
$success = 'Cart successfully updated!';
} else {
$error[] = 'Cart Invalid!';
}
}
return back()->with($error)->with('success', $success);
} else {
return back()->with('Cart Invalid!');
}
}
public function getCartDropdown()
{
if (!auth()->check()) {
return response()->json([
'status' => false,
'message' => 'User not authenticated'
]);
}
$cartItems = Helper::getAllProductFromCart();
$totalPrice = Helper::totalCartPrice();
$html = '';
$html .= '<div class="dropdown-cart-header">';
$html .= '<span>'.count($cartItems).' Items</span>';
$html .= '<a href="'.route('cart').'">View Cart</a>';
$html .= '</div>';
$html .= '<ul class="shopping-list">';
foreach($cartItems as $item) {
$photo = explode(',', $item->product->photo);
$html .= '<li>';
$html .= '<a href="'.route('cart-delete', $item->id).'" class="remove" title="Remove this item"><i class="fa fa-remove"></i></a>';
$html .= '<a class="cart-img" href="#"><img src="'.$photo[0].'" alt="'.$photo[0].'"></a>';
$html .= '<h4><a href="'.route('product-detail', $item->product->slug).'">'.$item->product->title.'</a></h4>';
$html .= '<p class="quantity">'.$item->quantity.'x - <span class="amount">₹'.number_format($item->price, 2).'</span></p>';
$html .= '</li>';
}
$html .= '</ul>';
$html .= '<div class="bottom">';
$html .= '<div class="total">';
$html .= '<span>Total</span>';
$html .= '<span class="total-amount">₹'.number_format($totalPrice, 2).'</span>';
$html .= '</div>';
$html .= '<a href="'.route('checkout').'" class="btn animate">Checkout</a>';
$html .= '</div>';
return response()->json([
'status' => true,
'count' => count($cartItems),
'total' => $totalPrice,
'html' => $html
]);
}
// public function addToCart(Request $request){
// // return $request->all();
// if(Auth::check()){
// $qty=$request->quantity;
// $this->product=$this->product->find($request->pro_id);
// if($this->product->stock < $qty){
// return response(['status'=>false,'msg'=>'Out of stock','data'=>null]);
// }
// if(!$this->product){
// return response(['status'=>false,'msg'=>'Product not found','data'=>null]);
// }
// // $session_id=session('cart')['session_id'];
// // if(empty($session_id)){
// // $session_id=Str::random(30);
// // // dd($session_id);
// // session()->put('session_id',$session_id);
// // }
// $current_item=array(
// 'user_id'=>auth()->user()->id,
// 'id'=>$this->product->id,
// // 'session_id'=>$session_id,
// 'title'=>$this->product->title,
// 'summary'=>$this->product->summary,
// 'link'=>route('product-detail',$this->product->slug),
// 'price'=>$this->product->price,
// 'photo'=>$this->product->photo,
// );
// $price=$this->product->price;
// if($this->product->discount){
// $price=($price-($price*$this->product->discount)/100);
// }
// $current_item['price']=$price;
// $cart=session('cart') ? session('cart') : null;
// if($cart){
// // if anyone alreay order products
// $index=null;
// foreach($cart as $key=>$value){
// if($value['id']==$this->product->id){
// $index=$key;
// break;
// }
// }
// if($index!==null){
// $cart[$index]['quantity']=$qty;
// $cart[$index]['amount']=ceil($qty*$price);
// if($cart[$index]['quantity']<=0){
// unset($cart[$index]);
// }
// }
// else{
// $current_item['quantity']=$qty;
// $current_item['amount']=ceil($qty*$price);
// $cart[]=$current_item;
// }
// }
// else{
// $current_item['quantity']=$qty;
// $current_item['amount']=ceil($qty*$price);
// $cart[]=$current_item;
// }
// session()->put('cart',$cart);
// return response(['status'=>true,'msg'=>'Cart successfully updated','data'=>$cart]);
// }
// else{
// return response(['status'=>false,'msg'=>'You need to login first','data'=>null]);
// }
// }
// public function removeCart(Request $request){
// $index=$request->index;
// // return $index;
// $cart=session('cart');
// unset($cart[$index]);
// session()->put('cart',$cart);
// return redirect()->back()->with('success','Successfully remove item');
// }
public function checkout(Request $request){
// $cart=session('cart');
// $cart_index=\Str::random(10);
// $sub_total=0;
// foreach($cart as $cart_item){
// $sub_total+=$cart_item['amount'];
// $data=array(
// 'cart_id'=>$cart_index,
// 'user_id'=>$request->user()->id,
// 'product_id'=>$cart_item['id'],
// 'quantity'=>$cart_item['quantity'],
// 'amount'=>$cart_item['amount'],
// 'status'=>'new',
// 'price'=>$cart_item['price'],
// );
// $cart=new Cart();
// $cart->fill($data);
// $cart->save();
// }
return view('frontend.pages.checkout');
}
}


PK 99