<?php

namespace App\Http\Controllers\API\Manager;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Restaurant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    public function getSystemImages()
    {
        $imagesPath = public_path('images/products');
        $images = [];
        
        if (file_exists($imagesPath)) {
            $files = scandir($imagesPath);
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..' && in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                    $images[] = [
                        'name' => $file,
                        'url' => '/images/products/' . $file,
                        'size' => filesize($imagesPath . '/' . $file)
                    ];
                }
            }
        }
        
        return response()->json(['images' => $images]);
    }
    
    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|max:5120'
        ]);
        
        $file = $request->file('image');
        $filename = time() . '_' . $file->getClientOriginalName();
        $file->move(public_path('images/products'), $filename);
        
        return response()->json([
            'success' => true,
            'url' => '/images/products/' . $filename,
            'filename' => $filename
        ]);
    }
    public function index(Request $request)
    {
        try {
            $user = $request->user();
            
            if (!$user->restaurant_id) {
                return response()->json([
                    'error' => 'No restaurant assigned to this manager. Please contact admin.',
                    'user_id' => $user->id
                ], 404);
            }
            
            $restaurant = Restaurant::find($user->restaurant_id);
            
            if (!$restaurant) {
                return response()->json(['error' => 'Restaurant not found'], 404);
            }
            
            $query = Product::where('restaurant_id', $user->restaurant_id);
            
            if ($request->has('search') && $request->search) {
                $query->where('name', 'like', '%' . $request->search . '%');
            }
            
            if ($request->has('category_id') && $request->category_id) {
                $query->where('category_id', $request->category_id);
            }
            
            if ($request->has('status') && $request->status !== '' && $request->status !== null) {
                $query->where('is_available', (bool)$request->status);
            }
            
            $products = $query->with(['category', 'variations', 'addons'])->get();
                
            return response()->json($products);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'restaurant_id' => 'required|exists:restaurants,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0',
            'discount' => 'nullable|numeric|min:0',
            'image' => 'nullable|string',
            'variation_prices' => 'nullable|json',
            'variation_discounts' => 'nullable|json',
            'addon_prices' => 'nullable|json',
        ]);

        $user = $request->user();
        
        if (!$user->restaurant_id || $user->restaurant_id != $validated['restaurant_id']) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $product = Product::create($validated);

        if ($request->has('variation_prices')) {
            $variationPrices = json_decode($request->variation_prices, true);
            $variationDiscounts = json_decode($request->variation_discounts ?? '{}', true);
            
            foreach ($variationPrices as $categoryVariationId => $price) {
                if ($price) {
                    $categoryVariation = \App\Models\CategoryVariation::find($categoryVariationId);
                    $product->variations()->create([
                        'category_variation_id' => $categoryVariationId,
                        'name' => $categoryVariation->name,
                        'price' => $price,
                        'discount' => $variationDiscounts[$categoryVariationId] ?? 0,
                    ]);
                }
            }
        }

        if ($request->has('addon_prices')) {
            $addonPrices = json_decode($request->addon_prices, true);
            
            foreach ($addonPrices as $categoryAddonId => $price) {
                if ($price) {
                    $categoryAddon = \App\Models\CategoryAddon::find($categoryAddonId);
                    $product->addons()->create([
                        'category_addon_id' => $categoryAddonId,
                        'name' => $categoryAddon->name,
                        'price' => $price,
                    ]);
                }
            }
        }

        return response()->json($product->load(['category', 'variations', 'addons']), 201);
    }

    public function show(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)
            ->with(['category', 'variations.categoryVariation', 'addons.categoryAddon'])
            ->findOrFail($id);
        
        return response()->json(['data' => $product]);
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)->findOrFail($id);

        $validated = $request->validate([
            'restaurant_id' => 'required|exists:restaurants,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0',
            'discount' => 'nullable|numeric|min:0',
            'image' => 'nullable|string',
            'variation_prices' => 'nullable|json',
            'variation_discounts' => 'nullable|json',
            'addon_prices' => 'nullable|json',
        ]);
        
        if ($user->restaurant_id != $validated['restaurant_id']) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $product->update($validated);

        if ($request->has('variation_prices')) {
            $product->variations()->delete();
            $variationPrices = json_decode($request->variation_prices, true);
            $variationDiscounts = json_decode($request->variation_discounts ?? '{}', true);
            
            foreach ($variationPrices as $categoryVariationId => $price) {
                if ($price) {
                    $categoryVariation = \App\Models\CategoryVariation::find($categoryVariationId);
                    $product->variations()->create([
                        'category_variation_id' => $categoryVariationId,
                        'name' => $categoryVariation->name,
                        'price' => $price,
                        'discount' => $variationDiscounts[$categoryVariationId] ?? 0,
                    ]);
                }
            }
        }

        if ($request->has('addon_prices')) {
            $product->addons()->delete();
            $addonPrices = json_decode($request->addon_prices, true);
            
            foreach ($addonPrices as $categoryAddonId => $price) {
                if ($price) {
                    $categoryAddon = \App\Models\CategoryAddon::find($categoryAddonId);
                    $product->addons()->create([
                        'category_addon_id' => $categoryAddonId,
                        'name' => $categoryAddon->name,
                        'price' => $price,
                    ]);
                }
            }
        }

        return response()->json($product->load(['category', 'variations', 'addons']));
    }

    public function destroy(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)->findOrFail($id);
        
        // Soft delete - doesn't actually remove from database
        $product->delete();
        
        return response()->json(['success' => true, 'message' => 'Product deleted successfully']);
    }

    public function toggleAvailability(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)->findOrFail($id);
        
        $product->is_available = !$product->is_available;
        $product->save();
        
        return response()->json(['success' => true, 'is_available' => $product->is_available]);
    }
    
    public function toggleVariationAvailability(Request $request, $productId, $variationId)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)->findOrFail($productId);
        $variation = $product->variations()->findOrFail($variationId);
        
        $variation->is_available = !$variation->is_available;
        $variation->save();
        
        return response()->json(['success' => true, 'is_available' => $variation->is_available]);
    }
    
    public function toggleAddonAvailability(Request $request, $productId, $addonId)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::where('restaurant_id', $user->restaurant_id)->findOrFail($productId);
        $addon = $product->addons()->findOrFail($addonId);
        
        $addon->is_available = !$addon->is_available;
        $addon->save();
        
        return response()->json(['success' => true, 'is_available' => $addon->is_available]);
    }
    
    public function trashed(Request $request)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $products = Product::onlyTrashed()
            ->where('restaurant_id', $user->restaurant_id)
            ->with(['category', 'variations', 'addons'])
            ->get();
        
        return response()->json($products);
    }
    
    public function restore(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['error' => 'No restaurant assigned'], 404);
        }
        
        $product = Product::onlyTrashed()
            ->where('restaurant_id', $user->restaurant_id)
            ->findOrFail($id);
        
        $product->restore();
        
        return response()->json(['success' => true, 'message' => 'Product restored successfully']);
    }
}
