<?php

namespace App\Http\Controllers\API\Manager;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductVariation;
use App\Models\ProductAddon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductManagementController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        
        $userRoles = $user->roles->pluck('name')->toArray();
        if (in_array('admin', $userRoles)) {
            $restaurantIds = [$user->restaurant_id];
        } else {
            $restaurantIds = $user->restaurants()->pluck('id');
        }

        $products = Product::with(['category', 'restaurant', 'variations', 'addons'])
            ->whereIn('restaurant_id', $restaurantIds)
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%"))
            ->when($request->category_id, fn($q) => $q->where('category_id', $request->category_id))
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json(['data' => $products]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'discount' => 'nullable|numeric|min:0',
            'image' => 'nullable|image|max:2048',
            'variations' => 'nullable|string',
            'addons' => 'nullable|string'
        ]);

        $user = $request->user();
        $restaurant = $user->restaurants()->first();

        if (!$restaurant) {
            return response()->json(['message' => 'No restaurant found'], 403);
        }

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('products', 'public');
        }

        $product = Product::create([
            'restaurant_id' => $restaurant->id,
            'category_id' => $request->category_id,
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'description' => $request->description,
            'price' => $request->price,
            'discount_price' => $request->discount,
            'image' => $imagePath,
            'is_available' => true,
            'preparation_time' => $request->preparation_time ?? 15
        ]);

        if ($request->variations) {
            $variations = json_decode($request->variations, true);
            foreach ($variations as $variation) {
                if (!empty($variation['name']) && isset($variation['price'])) {
                    ProductVariation::create([
                        'product_id' => $product->id,
                        'name' => $variation['name'],
                        'price' => $variation['price']
                    ]);
                }
            }
        }

        if ($request->addons) {
            $addons = json_decode($request->addons, true);
            foreach ($addons as $addon) {
                if (!empty($addon['name']) && isset($addon['price'])) {
                    ProductAddon::create([
                        'product_id' => $product->id,
                        'name' => $addon['name'],
                        'price' => $addon['price']
                    ]);
                }
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Product created successfully',
            'data' => $product->load(['variations', 'addons', 'category'])
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();
        $restaurantIds = $user->restaurants()->pluck('id');
        $product = Product::whereIn('restaurant_id', $restaurantIds)->findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0'
        ]);

        if ($request->hasFile('image')) {
            if ($product->image) Storage::disk('public')->delete($product->image);
            $product->image = $request->file('image')->store('products', 'public');
        }

        $product->update([
            'category_id' => $request->category_id,
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'description' => $request->description,
            'price' => $request->price,
            'discount_price' => $request->discount
        ]);

        if ($request->has('variations')) {
            $product->variations()->delete();
            $variations = json_decode($request->variations, true);
            foreach ($variations as $variation) {
                if (!empty($variation['name']) && isset($variation['price'])) {
                    ProductVariation::create(['product_id' => $product->id, 'name' => $variation['name'], 'price' => $variation['price']]);
                }
            }
        }

        if ($request->has('addons')) {
            $product->addons()->delete();
            $addons = json_decode($request->addons, true);
            foreach ($addons as $addon) {
                if (!empty($addon['name']) && isset($addon['price'])) {
                    ProductAddon::create(['product_id' => $product->id, 'name' => $addon['name'], 'price' => $addon['price']]);
                }
            }
        }

        return response()->json(['success' => true, 'message' => 'Product updated', 'data' => $product->load(['variations', 'addons'])]);
    }

    public function destroy($id)
    {
        $user = request()->user();
        $restaurantIds = $user->restaurants()->pluck('id');
        $product = Product::whereIn('restaurant_id', $restaurantIds)->findOrFail($id);

        if ($product->image) Storage::disk('public')->delete($product->image);
        $product->delete();

        return response()->json(['success' => true, 'message' => 'Product deleted']);
    }

    public function toggleAvailability($id)
    {
        $user = request()->user();
        $restaurantIds = $user->restaurants()->pluck('id');
        $product = Product::whereIn('restaurant_id', $restaurantIds)->findOrFail($id);
        $product->update(['is_available' => !$product->is_available]);

        return response()->json(['success' => true, 'data' => $product]);
    }
}
