File size: 9,353 Bytes
70ba896 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Product;
use App\Models\Order;
class CartController extends Controller
{
public function index()
{
$cart = session()->get('cart', []);
return view('cart', compact('cart'));
}
public function add(Request $request, $id)
{
$product = Product::findOrFail($id);
$quantity = (int) $request->input('quantity', 1);
// Check if product has enough stock
if ($product->Amount < $quantity) {
if ($request->ajax()) {
return response()->json([
'success' => false,
'message' => 'Insufficient stock. Available: ' . $product->Amount
]);
}
return back()->with('error', 'Insufficient stock. Available: ' . $product->Amount);
}
$cart = session()->get('cart', []);
if (isset($cart[$id])) {
$newQuantity = $cart[$id]['quantity'] + $quantity;
if ($newQuantity > $product->Amount) {
if ($request->ajax()) {
return response()->json([
'success' => false,
'message' => 'Cannot add more items. Stock limit: ' . $product->Amount
]);
}
return back()->with('error', 'Cannot add more items. Stock limit: ' . $product->Amount);
}
$cart[$id]['quantity'] = $newQuantity;
} else {
$cart[$id] = [
'id' => $product->id,
'name' => $product->name,
'image' => $product->image,
'price' => $product->price,
'quantity' => $quantity,
'game' => $product->game,
];
}
session()->put('cart', $cart);
// Return JSON response for AJAX requests
if ($request->ajax()) {
return response()->json([
'success' => true,
'message' => 'Item added to cart successfully',
'cart_count' => array_sum(array_column($cart, 'quantity'))
]);
}
return redirect()->route('cart.index')->with('success', 'เพิ่มสินค้าลงตะกร้าเรียบร้อยแล้ว');
}
public function remove($id)
{
$cart = session()->get('cart', []);
if (isset($cart[$id])) {
unset($cart[$id]);
session()->put('cart', $cart);
}
return redirect()->route('cart.index')->with('success', 'ลบสินค้าออกจากตะกร้าเรียบร้อยแล้ว');
}
public function checkout(Request $request)
{
$request->validate([
'customer_name' => 'required|string|max:255',
'phone' => 'required|string|max:20',
'payment_slip' => 'required|image|mimes:jpeg,png,jpg,gif|max:10240', // 10MB limit
]);
try {
$path = $request->file('payment_slip')->store('payment_slips', 'public');
// Get cart data
$cart = session()->get('cart', []);
if (empty($cart)) {
return back()->with('error', 'Your cart is empty');
}
// Calculate total amount and validate stock
$totalAmount = 0;
foreach ($cart as $item) {
$product = Product::find($item['id']);
if (!$product) {
return back()->with('error', "Product {$item['name']} no longer exists");
}
if ($product->Amount < $item['quantity']) {
return back()->with('error', "Insufficient stock for {$product->name}. Available: {$product->Amount}, Requested: {$item['quantity']}");
}
$totalAmount += $item['price'] * $item['quantity'];
}
// Create order
$order = Order::create([
'customer_name' => $request->customer_name,
'phone' => $request->phone,
'payment_slip_path' => $path,
'cart_data' => json_encode($cart),
'total_amount' => $totalAmount,
'status' => 'pending',
]);
// Update product stock
foreach ($cart as $item) {
$product = Product::find($item['id']);
if ($product) {
$product->Amount = max(0, $product->Amount - $item['quantity']);
$product->save();
}
}
// Clear cart
session()->forget('cart');
return redirect()->route('cart.index')->with('success', 'Thank you for your order! We have received your order successfully.');
} catch (\Exception $e) {
return back()->with('error', 'Failed to process order: ' . $e->getMessage());
}
}
public function order()
{
$orders = Order::latest()->get(); // ดึงทั้งหมด เรียงล่าสุดก่อน
return view('order', compact('orders'));
}
public function deleteOrder($id)
{
try {
$order = Order::findOrFail($id);
// Delete payment slip file if it exists
if ($order->payment_slip_path && Storage::disk('public')->exists($order->payment_slip_path)) {
Storage::disk('public')->delete($order->payment_slip_path);
}
$order->delete();
return back()->with('success', 'Order deleted successfully');
} catch (\Exception $e) {
return back()->with('error', 'Failed to delete order: ' . $e->getMessage());
}
}
public function show($id)
{
try {
$order = Order::findOrFail($id);
return view('order-detail', compact('order'));
} catch (\Exception $e) {
return redirect()->route('orders.index')->with('error', 'Order not found');
}
}
public function completeOrder($id)
{
try {
$order = Order::findOrFail($id);
// Update order status to completed
$order->status = 'completed';
$order->save();
return redirect()->route('orders.index')->with('success', 'Order #' . str_pad($order->id, 4, '0', STR_PAD_LEFT) . ' has been ACCEPTED successfully!');
} catch (\Exception $e) {
return redirect()->route('orders.index')->with('error', 'Failed to accept order: ' . $e->getMessage());
}
}
public function rejectOrder($id)
{
try {
$order = Order::findOrFail($id);
// Update order status to cancelled (rejected)
$order->status = 'cancelled';
$order->save();
return redirect()->route('orders.index')->with('success', 'Order #' . str_pad($order->id, 4, '0', STR_PAD_LEFT) . ' has been REJECTED. Customer will see it as cancelled.');
} catch (\Exception $e) {
return redirect()->route('orders.index')->with('error', 'Failed to reject order: ' . $e->getMessage());
}
}
public function customerOrders(Request $request)
{
// For now, we'll show all orders since we don't have user authentication for customers
// In a real app, you'd filter by authenticated customer
$orders = Order::latest()->get();
// If it's an AJAX request for load more functionality
if ($request->ajax()) {
$page = $request->get('page', 1);
$perPage = 3;
$offset = ($page - 1) * $perPage;
$status = $request->get('status');
$game = $request->get('game');
// Filter orders based on status
$filteredOrders = $orders;
if ($status && $status !== 'recently') {
$filteredOrders = $orders->where('status', $status);
}
// Filter by game if specified
if ($game && $game !== 'all') {
$filteredOrders = $filteredOrders->filter(function($order) use ($game) {
$items = json_decode($order->cart_data, true);
if (is_array($items)) {
foreach ($items as $item) {
$product = \App\Models\Product::find($item['id'] ?? null);
if ($product && $product->game === $game) {
return true;
}
}
}
return false;
});
}
$paginatedOrders = $filteredOrders->slice($offset, $perPage);
$hasMore = $filteredOrders->count() > ($offset + $perPage);
return response()->json([
'orders' => $paginatedOrders->values(),
'hasMore' => $hasMore,
'currentPage' => $page
]);
}
return view('customer-orders', compact('orders'));
}
}
|