<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::with('category')->when($request->search,fn($q)=>$q->where('name','like',"%{$request->search}%"))->latest()->paginate(20);
        return response()->json(['success'=>true,'data'=>$products]);
    }
    public function store(Request $request)
    {
        $data = $request->validate(['name'=>'required','category_id'=>'required|exists:categories,id','price'=>'required|numeric|min:0','sale_price'=>'nullable|numeric','stock'=>'required|integer|min:0','description'=>'nullable','brand'=>'nullable','badge'=>'nullable','sizes'=>'nullable|array','colors'=>'nullable|array','is_active'=>'boolean','is_featured'=>'boolean']);
        $data['slug'] = Str::slug($data['name']).'-'.Str::random(4);
        $product = Product::create($data);
        return response()->json(['success'=>true,'data'=>$product],201);
    }
    public function show(int $id) { return response()->json(['success'=>true,'data'=>Product::with('category','reviews')->findOrFail($id)]); }
    public function update(Request $request, int $id)
    {
        $product = Product::findOrFail($id);
        $product->update($request->validate(['name'=>'string','price'=>'numeric','sale_price'=>'nullable|numeric','stock'=>'integer|min:0','is_active'=>'boolean','is_featured'=>'boolean','is_flash_deal'=>'boolean']));
        return response()->json(['success'=>true,'data'=>$product]);
    }
    public function destroy(int $id) { Product::findOrFail($id)->delete(); return response()->json(['success'=>true,'message'=>'Product deleted.']); }
    public function uploadImages(Request $request, int $id)
    {
        $request->validate(['images'=>'required|array','images.*'=>'image|mimes:jpg,jpeg,png,webp|max:2048']);
        $product = Product::findOrFail($id);
        $paths = collect($request->file('images'))->map(fn($f)=>Storage::url($f->store('products','public')))->toArray();
        $product->update(['images'=>array_merge($product->images??[],$paths)]);
        return response()->json(['success'=>true,'images'=>$product->fresh()->images]);
    }
}
