<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Delivery;
use Illuminate\Http\Request;

class DeliveryController extends Controller
{
    /**
     * List deliveries for the authenticated user.
     */
    public function index(Request $request)
    {
        $query = Delivery::whereHas('subscription', function ($q) use ($request) {
            $q->where('user_id', $request->user()->id);
        })->with(['meals', 'address', 'subscription.plan']);

        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('from')) {
            $query->where('scheduled_date', '>=', $request->from);
        }

        if ($request->has('to')) {
            $query->where('scheduled_date', '<=', $request->to);
        }

        $deliveries = $query->orderBy('scheduled_date')->get();

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

    /**
     * Get a single delivery with details.
     */
    public function show(Request $request, Delivery $delivery)
    {
        // Ensure user owns this delivery
        if ($delivery->subscription->user_id !== $request->user()->id) {
            abort(403);
        }

        $delivery->load(['meals', 'address', 'subscription.plan']);

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

    /**
     * Select meals for an upcoming delivery.
     */
    public function selectMeals(Request $request, Delivery $delivery)
    {
        if ($delivery->subscription->user_id !== $request->user()->id) {
            abort(403);
        }

        if ($delivery->status !== 'scheduled') {
            return response()->json(['message' => 'Cannot modify meals for this delivery.'], 422);
        }

        // Must be at least 24 hours before delivery
        if ($delivery->scheduled_date->diffInHours(now()) < 24) {
            return response()->json(['message' => 'Meal selection deadline has passed (24h before delivery).'], 422);
        }

        $validated = $request->validate([
            'meals' => 'required|array',
            'meals.*.meal_id' => 'required|exists:meals,id',
            'meals.*.quantity' => 'required|integer|min:1|max:5',
        ]);

        $maxMeals = $delivery->subscription->plan->meals_per_delivery;
        $totalMeals = collect($validated['meals'])->sum('quantity');

        if ($totalMeals > $maxMeals) {
            return response()->json([
                'message' => "You can select up to {$maxMeals} meals for this delivery. You selected {$totalMeals}.",
            ], 422);
        }

        // Sync meals
        $syncData = [];
        foreach ($validated['meals'] as $meal) {
            $syncData[$meal['meal_id']] = ['quantity' => $meal['quantity']];
        }
        $delivery->meals()->sync($syncData);

        return response()->json([
            'delivery' => $delivery->fresh()->load('meals'),
            'message' => 'Meals selected successfully.',
        ]);
    }

    /**
     * Skip an upcoming delivery.
     */
    public function skip(Request $request, Delivery $delivery)
    {
        if ($delivery->subscription->user_id !== $request->user()->id) {
            abort(403);
        }

        if ($delivery->status !== 'scheduled') {
            return response()->json(['message' => 'Only scheduled deliveries can be skipped.'], 422);
        }

        // Must be at least 24 hours before delivery
        if ($delivery->scheduled_date->diffInHours(now()) < 24) {
            return response()->json(['message' => 'Skip deadline has passed (24h before delivery).'], 422);
        }

        $delivery->skip();

        return response()->json([
            'delivery' => $delivery->fresh(),
            'message' => 'Delivery skipped successfully.',
        ]);
    }

    /**
     * Update delivery time slot.
     */
    public function updateTimeSlot(Request $request, Delivery $delivery)
    {
        if ($delivery->subscription->user_id !== $request->user()->id) {
            abort(403);
        }

        $validated = $request->validate([
            'time_slot' => 'required|in:morning,afternoon,evening',
        ]);

        $delivery->update(['time_slot' => $validated['time_slot']]);

        return response()->json([
            'delivery' => $delivery->fresh(),
        ]);
    }
}
