<?php

namespace App\Http\Controllers\API\Manager;

use App\Http\Controllers\Controller;
use App\Models\DeliveryBoy;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\{Hash, DB};

class DeliveryBoyController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json(['success' => false, 'message' => 'No restaurant found'], 404);
        }

        $restaurant = \App\Models\Restaurant::find($user->restaurant_id);
        
        if (!$restaurant) {
            return response()->json(['success' => false, 'message' => 'Restaurant not found'], 404);
        }

        // Get delivery boys in same city as restaurant
        $query = DeliveryBoy::select('id', 'full_name', 'phone', 'email', 'city', 'rating', 'total_deliveries', 'status', 'is_available')
            ->with('user:id,name,avatar')
            ->where('verification_status', 'verified')
            ->where('status', '!=', 'blocked');

        // Filter by restaurant city if exists
        if ($restaurant->city) {
            $query->where('city', $restaurant->city);
        }

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

        if ($request->available_only) {
            $query->where('is_available', true);
        }

        $deliveryBoys = $query->get();

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

    public function show(DeliveryBoy $deliveryBoy): JsonResponse
    {
        $data = [
            'id' => $deliveryBoy->id,
            'full_name' => $deliveryBoy->full_name,
            'phone' => $deliveryBoy->phone,
            'rating' => $deliveryBoy->rating,
            'total_deliveries' => $deliveryBoy->total_deliveries,
            'status' => $deliveryBoy->status,
            'is_available' => $deliveryBoy->is_available,
            'profile_photo' => $deliveryBoy->profile_photo,
        ];

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'phone' => 'required|string|max:20',
            'password' => 'required|string|min:6',
            'city' => 'nullable|string|max:100',
        ]);

        DB::beginTransaction();
        try {
            $user = User::create([
                'name' => $validated['full_name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'password' => Hash::make($validated['password']),
                'status' => 'active',
            ]);

            $user->assignRole('delivery_boy');

            $deliveryBoy = DeliveryBoy::create([
                'user_id' => $user->id,
                'full_name' => $validated['full_name'],
                'phone' => $validated['phone'],
                'email' => $validated['email'],
                'city' => $validated['city'] ?? null,
                'status' => 'offline',
                'verification_status' => 'pending',
                'commission_rate' => 10.00,
                'joined_date' => now(),
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Delivery boy created successfully',
                'data' => $deliveryBoy
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Failed to create delivery boy',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
