<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Event;
use App\Models\SchoolService;
use App\Models\Service;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'item_type' => ['required', 'string', 'in:product,event,school_service,service'],
            'item_id' => ['required', 'uuid'],
            'quantity' => ['required', 'integer', 'min:1'],
            'price' => ['required', 'numeric', 'min:0'],
            'user_id' => ['required', 'uuid'],
            'status' => ['sometimes', 'string', 'in:pending,completed,cancelled'],
        ]);

        // Determine the actual model class based on item_type
        $modelClass = match ($validated['item_type']) {
            'product' => Product::class,
            'event' => Event::class,
            'school_service' => SchoolService::class,
            'service' => Service::class,
            default => null,
        };

        if (!$modelClass) {
            return response()->json(['message' => 'Invalid item type'], 400);
        }

        // Check if the item exists
        $item = $modelClass::find($validated['item_id']);
        if (!$item) {
            return response()->json(['message' => 'Item not found'], 404);
        }

        // Create the Order
        $order = Order::create([
            'id' => Str::uuid(),
            'user_id' => $validated['user_id'],
            'total_amount' => $validated['price'] * $validated['quantity'],
            'status' => $validated['status'] ?? 'pending',
            'order_date' => now(),
        ]);

        // Create the OrderItem
        OrderItem::create([
            'id' => Str::uuid(),
            'order_id' => $order->id,
            'item_type' => $modelClass,
            'item_id' => $item->id,
            'quantity' => $validated['quantity'],
            'price' => $validated['price'],
        ]);

        // Notify the user about the new order
        $user = \App\Models\User::find($validated['user_id']);
        if ($user) {
            $user->notify(new \App\Notifications\NewOrderNotification($order));
        }

        return response()->json(['message' => 'Order created successfully', 'order' => $order->load('orderItems')], 201);
    }
}
