<?php

namespace App\Http\Controllers\API\Customer;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class DeliveryTrackingController extends Controller
{
    public function trackOrder(Order $order): JsonResponse
    {
        if ($order->user_id !== auth()->id()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }

        $delivery = $order->delivery;
        
        if (!$delivery || !$delivery->deliveryBoy) {
            return response()->json(['success' => false, 'message' => 'No delivery boy assigned'], 404);
        }

        $deliveryBoy = $delivery->deliveryBoy;
        $location = $deliveryBoy->locations()->latest()->first();

        $data = [
            'delivery_boy' => [
                'name' => $deliveryBoy->full_name,
                'photo' => $deliveryBoy->profile_photo,
                'rating' => $deliveryBoy->rating,
                'phone' => $deliveryBoy->phone,
            ],
            'location' => $location ? [
                'latitude' => $location->latitude,
                'longitude' => $location->longitude,
                'updated_at' => $location->recorded_at,
            ] : null,
            'order_status' => $order->status,
        ];

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

    public function rateDeliveryBoy(Request $request, Order $order): JsonResponse
    {
        if ($order->user_id !== auth()->id()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'review' => 'nullable|string|max:500',
            'delivery_time_rating' => 'nullable|integer|min:1|max:5',
            'behavior_rating' => 'nullable|integer|min:1|max:5',
            'food_condition_rating' => 'nullable|integer|min:1|max:5',
        ]);

        $delivery = $order->delivery;
        
        if (!$delivery) {
            return response()->json(['success' => false, 'message' => 'No delivery found'], 404);
        }

        $rating = $delivery->deliveryBoy->ratings()->create([
            'order_id' => $order->id,
            'customer_id' => auth()->id(),
            'rating' => $validated['rating'],
            'review' => $validated['review'] ?? null,
            'delivery_time_rating' => $validated['delivery_time_rating'] ?? null,
            'behavior_rating' => $validated['behavior_rating'] ?? null,
            'food_condition_rating' => $validated['food_condition_rating'] ?? null,
        ]);

        // Update delivery boy average rating
        $deliveryBoy = $delivery->deliveryBoy;
        $avgRating = $deliveryBoy->ratings()->avg('rating');
        $deliveryBoy->update([
            'rating' => round($avgRating, 2),
            'total_ratings' => $deliveryBoy->ratings()->count(),
        ]);

        return response()->json(['success' => true, 'message' => 'Rating submitted', 'data' => $rating]);
    }
}
