<?php

namespace App\Http\Controllers\Courier;

use App\Http\Controllers\Controller;
use App\Models\Delivery;
use App\Services\DeliveryAssigner;

class DashboardController extends Controller
{
    public function index()
    {
        $courier = auth()->user()->courier;
        $deliveries = $courier
            ? Delivery::where('courier_id', $courier->id)->latest()->get()
            : collect();

        $pendingDelivery = $deliveries->firstWhere('status', Delivery::STATUS_PENDING);

        if ($courier && $courier->is_active && $courier->is_online && !$pendingDelivery) {
            app(DeliveryAssigner::class)->assignNextForCourier($courier->id);
            $deliveries = Delivery::where('courier_id', $courier->id)->latest()->get();
            $pendingDelivery = $deliveries->firstWhere('status', Delivery::STATUS_PENDING);
        }

        $acceptedDelivery = $deliveries->firstWhere('status', Delivery::STATUS_CONFIRMED);
        $activeDeliveries = $deliveries->whereIn('status', Delivery::ACTIVE_STATUSES)->values();

        $statusCounts = [
            'pending' => $deliveries->where('status', Delivery::STATUS_PENDING)->count(),
            'confirmed' => $deliveries->where('status', Delivery::STATUS_CONFIRMED)->count(),
            'at_restaurant' => $deliveries->where('status', Delivery::STATUS_AT_RESTAURANT)->count(),
            'en_route' => $deliveries->where('status', Delivery::STATUS_EN_ROUTE)->count(),
            'delivered' => $deliveries->where('status', Delivery::STATUS_DELIVERED)->count(),
        ];

        return view('courier.dashboard', [
            'courier' => $courier,
            'deliveries' => $deliveries,
            'pendingDelivery' => $pendingDelivery,
            'acceptedDelivery' => $acceptedDelivery,
            'activeDeliveries' => $activeDeliveries,
            'statusCounts' => $statusCounts,
            'currentDeliveryData' => [
                'pickup' => [
                    'address' => $pendingDelivery?->restaurant?->address,
                    'lat' => $pendingDelivery?->restaurant?->lat,
                    'lng' => $pendingDelivery?->restaurant?->lng,
                ],
                'dropoff' => [
                    'address' => $pendingDelivery?->delivery_address,
                    'lat' => $pendingDelivery?->delivery_lat,
                    'lng' => $pendingDelivery?->delivery_lng,
                ],
            ],
        ]);
    }
}
