<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Restaurant;
use App\Models\RestaurantCategory;
use Illuminate\Support\Facades\DB;

class RestaurantMenuController extends Controller
{
    public function getCategories($restaurantId)
    {
        // Get unique categories from products in this restaurant
        $categories = \App\Models\Category::whereHas('products', function($query) use ($restaurantId) {
            $query->where('restaurant_id', $restaurantId)
                  ->where('is_available', true);
        })->with(['variations', 'addons'])->get();

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

    public function getProducts($restaurantId)
    {
        $products = \App\Models\Product::where('restaurant_id', $restaurantId)
            ->where(function($query) {
                $query->where('is_available', true)
                      ->orWhereNull('is_available');
            })
            ->where(function($query) {
                $query->where('is_active', true)
                      ->orWhereNull('is_active');
            })
            ->with([
                'category',
                'variations' => function($query) {
                    $query->where('is_available', true);
                },
                'addons' => function($query) {
                    $query->where('is_available', true);
                }
            ])
            ->get()
            ->map(function($product) {
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'description' => $product->description,
                    'image' => $product->image ? '/storage/' . $product->image : null,
                    'price' => $product->price,
                    'discount' => $product->discount,
                    'category_id' => $product->category_id,
                    'category_name' => $product->category->name ?? null,
                    'variations' => $product->variations,
                    'addons' => $product->addons,
                ];
            });

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

    public function getProductVariants($productId)
    {
        $variants = DB::table('product_variations')
            ->where('product_id', $productId)
            ->get();

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

    public function getProductAddons($productId)
    {
        $addons = DB::table('product_addons')
            ->where('product_id', $productId)
            ->get();

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