<?php

namespace App\Http\Controllers\Api\Mobile\Rider;

use App\Http\Controllers\Controller;
use App\Services\LocalDeliveryDispatchService;
use Illuminate\Http\Request;

class StatusController extends Controller
{
    public function toggleOnline(Request $request)
    {
        $rider = $request->user();

        if (!$rider->isApproved()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Your account must be approved by admin before going online.',
            ], 403);
        }

        $request->validate(['is_online' => 'required']);
        $rider->is_online = filter_var($request->input('is_online'), FILTER_VALIDATE_BOOLEAN);
        $rider->save();

        if ($rider->is_online) {
            $dispatch = app(LocalDeliveryDispatchService::class);
            $dispatch->redistributeUnassignedOrders();
            $dispatch->ensureOffersForRider($rider->fresh());
        }

        return response()->json([
            'status' => 'success',
            'message' => $rider->is_online ? 'You are now online' : 'You are now offline',
            'data' => ['is_online' => (bool) $rider->is_online],
        ]);
    }

    public function toggleAccepting(Request $request)
    {
        $rider = $request->user();
        $request->validate(['accepts_requests' => 'required']);
        $rider->accepts_requests = filter_var($request->input('accepts_requests'), FILTER_VALIDATE_BOOLEAN);
        $rider->save();

        return response()->json([
            'status' => 'success',
            'message' => $rider->accepts_requests ? 'You will receive delivery requests' : 'Delivery requests paused',
            'data' => ['accepts_requests' => (bool) $rider->accepts_requests],
        ]);
    }
}
