Files

225 lines
7.6 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use App\Services\PriceCalculatorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;
class ProductController extends Controller
{
/**
* Display a listing of products.
*/
public function index(Request $request): View
{
$tab = $request->query('tab', 'all');
$query = Product::with(['category', 'makerworldCollection'])->latest();
if ($tab === 'published') {
$query->where(function ($q) {
$q->where('status', 'published')
->orWhereNull('status');
});
} elseif ($tab === 'draft') {
$query->where('status', 'draft');
} elseif ($tab === 'makerworld') {
$query->whereNotNull('makerworld_id');
}
if ($request->filled('q')) {
$q = $request->input('q');
$query->where(function ($w) use ($q) {
$w->where('name', 'like', "%{$q}%")
->orWhere('description', 'like', "%{$q}%")
->orWhere('makerworld_id', 'like', "%{$q}%");
});
}
if ($request->filled('category_id')) {
$query->where('category_id', $request->input('category_id'));
}
$totalAll = Product::count();
$totalPublished = Product::where('status', 'published')->orWhereNull('status')->count();
$totalDraft = Product::where('status', 'draft')->count();
$totalMakerWorld = Product::whereNotNull('makerworld_id')->count();
$products = $query->paginate(20)->withQueryString();
$categories = Category::all();
return view('admin.products.index', compact(
'products',
'categories',
'tab',
'totalAll',
'totalPublished',
'totalDraft',
'totalMakerWorld'
));
}
/**
* Show the form for creating a new product.
*/
public function create(): View
{
$categories = Category::all();
return view('admin.products.create', compact('categories'));
}
/**
* Store a newly created product in storage.
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'category_id' => 'required|exists:categories,id',
'base_price' => 'required|numeric|min:0.01',
'short_description' => 'nullable|string|max:500',
'description' => 'required|string',
'image_url' => 'nullable|string|max:2048',
'gallery_images' => 'nullable|array',
'gallery_images.*' => 'nullable|string|max:2048',
'dimensions' => 'nullable|string|max:100',
'weight_grams' => 'nullable|integer|min:0',
'print_time_hours' => 'nullable|numeric|min:0',
'is_featured' => 'nullable|boolean',
'is_active' => 'nullable|boolean',
]);
$validated['slug'] = Str::slug($validated['name']);
$validated['is_featured'] = $request->boolean('is_featured');
$validated['is_active'] = $request->boolean('is_active');
$validated['gallery_images'] = $this->cleanGalleryImages($request->input('gallery_images', []), $validated['image_url'] ?? null);
$validated['available_materials'] = ['pla', 'petg', 'silk', 'tpu'];
$validated['available_colors'] = [
'Zon Geel (Pikachu)', 'Vurig Rood (Charizard)', 'Hemelsblauw (Squirtle)',
'Muntgroen (Bulbasaur)', 'Spooky Paars (Gengar)', 'Koper Zijdeglans',
'Regenboog Multi-Color', 'Mat Zwart', 'Sneeuwwit',
];
Product::create($validated);
return redirect()->route('admin.products.index')
->with('success', "Product '{$validated['name']}' is succesvol aangemaakt!");
}
/**
* Show the form for editing the specified product.
*/
public function edit(Product $product): View
{
$categories = Category::all();
return view('admin.products.edit', compact('product', 'categories'));
}
/**
* Update the specified product in storage.
*/
public function update(Request $request, Product $product): RedirectResponse
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'category_id' => 'required|exists:categories,id',
'base_price' => 'required|numeric|min:0.01',
'short_description' => 'nullable|string|max:500',
'description' => 'required|string',
'image_url' => 'nullable|string|max:2048',
'gallery_images' => 'nullable|array',
'gallery_images.*' => 'nullable|string|max:2048',
'dimensions' => 'nullable|string|max:100',
'weight_grams' => 'nullable|integer|min:0',
'print_time_hours' => 'nullable|numeric|min:0',
'is_featured' => 'nullable|boolean',
'is_active' => 'nullable|boolean',
]);
$validated['is_featured'] = $request->boolean('is_featured');
$validated['is_active'] = $request->boolean('is_active');
$validated['gallery_images'] = $this->cleanGalleryImages($request->input('gallery_images', []), $validated['image_url'] ?? null);
$product->update($validated);
return redirect()->route('admin.products.index')
->with('success', "Product '{$product->name}' is succesvol bijgewerkt!");
}
/**
* Handle image upload for product gallery / cover.
*/
public function uploadImage(Request $request): JsonResponse
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,webp,gif|max:8192',
]);
$path = $request->file('image')->store('products', 'public');
$url = '/storage/'.$path;
return response()->json([
'success' => true,
'url' => $url,
]);
}
/**
* Calculate 3D printing cost price and suggested retail price.
*/
public function calculatePrice(Request $request, PriceCalculatorService $calculator): JsonResponse
{
$weight = (float) $request->input('weight_grams', 80);
$hours = (float) $request->input('print_time_hours', 4.0);
$colors = (int) $request->input('color_count', 1);
$material = (string) $request->input('material', 'pla');
$markup = $request->filled('markup_percent') ? (float) $request->input('markup_percent') : null;
$result = $calculator->calculate($weight, $hours, $colors, $material, $markup);
return response()->json([
'success' => true,
'data' => $result,
]);
}
/**
* Sanitize and filter gallery images.
*
* @param array<int, mixed> $images
* @return array<int, string>
*/
protected function cleanGalleryImages(array $images, ?string $coverUrl = null): array
{
$clean = [];
foreach ($images as $img) {
$img = trim((string) $img);
if ($img !== '' && $img !== $coverUrl && ! in_array($img, $clean, true)) {
$clean[] = $img;
}
}
return $clean;
}
/**
* Remove the specified product from storage.
*/
public function destroy(Product $product): RedirectResponse
{
$name = $product->name;
$product->delete();
return redirect()->route('admin.products.index')
->with('success', "Product '{$name}' is verwijderd.");
}
}