<?php

namespace App\Http\Controllers\Restaurant;

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

class DashboardController extends Controller
{
    public function index()
    {
        $restaurant = auth()->user()->restaurant;
        $deliveries = $restaurant
            ? $restaurant->deliveries()
                ->with('courier')
                ->whereDate('created_at', now()->toDateString())
                ->latest()
                ->get()
            : collect();

        $deliveriesList = $deliveries->take(5);
        $latestUrgent = $deliveries->firstWhere('is_urgent', true);

        $deliveriesForMap = $deliveries->map(function ($delivery) {
            return [
                'lat' => $delivery->delivery_lat,
                'lng' => $delivery->delivery_lng,
                'address' => $delivery->delivery_address,
                'status' => $delivery->status,
            ];
        });

        $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('restaurant.dashboard', [
            'restaurant' => $restaurant,
            'deliveries' => $deliveriesList,
            'allDeliveries' => $deliveries,
            'latestDelivery' => $deliveries->first(),
            'deliveriesForMap' => $deliveriesForMap,
            'statusCounts' => $statusCounts,
            'totalDeliveries' => $deliveries->count(),
            'latestUrgent' => $latestUrgent,
        ]);
    }

    public function urgentStatus(Request $request)
    {
        $restaurant = $request->user()?->restaurant;
        if (!$restaurant) {
            return response()->json(['status' => 'none']);
        }

        $latestUrgent = $restaurant->deliveries()
            ->whereDate('created_at', now()->toDateString())
            ->where('is_urgent', true)
            ->latest()
            ->first();

        if (!$latestUrgent) {
            return response()->json(['status' => 'none']);
        }

        return response()->json([
            'status' => $latestUrgent->status ?? 'pending',
            'id' => $latestUrgent->id,
        ]);
    }

    public function lastOrderStatus(Request $request)
    {
        $restaurant = $request->user()?->restaurant;
        if (!$restaurant) {
            return response()->json(['status' => 'none']);
        }

        $latest = $restaurant->deliveries()
            ->with('courier')
            ->whereDate('created_at', now()->toDateString())
            ->latest()
            ->first();

        if (!$latest) {
            return response()->json(['status' => 'none']);
        }

        $createdAt = $latest->created_at?->copy();
        $ago = $createdAt ? $createdAt->locale('es')->diffForHumans() : null;

        $courierName = $latest->courier?->name;
        $courierLine = $courierName ?: 'Sin repartidor';
        $courierStatus = match ($latest->status) {
            Delivery::STATUS_PENDING => 'Buscando repartidor',
            Delivery::STATUS_CONFIRMED => 'Repartidor confirmado',
            Delivery::STATUS_AT_RESTAURANT => 'Repartidor en el restaurante',
            Delivery::STATUS_EN_ROUTE => 'En camino al cliente',
            Delivery::STATUS_DELIVERED => 'Entrega completada',
            Delivery::STATUS_CANCELLED => 'Pedido cancelado',
            default => $courierName ? 'Repartidor asignado' : 'Sin asignar',
        };

        return response()->json([
            'status' => $latest->status,
            'id' => $latest->id,
            'is_urgent' => (bool) $latest->is_urgent,
            'customer_name' => $latest->customer_name,
            'delivery_address' => $latest->delivery_address,
            'created_time' => $createdAt ? $createdAt->format('H:i') : null,
            'created_at' => $createdAt ? $createdAt->toIso8601String() : null,
            'ago' => $ago,
            'courier_name' => $courierName,
            'courier_line' => $courierLine,
            'courier_status' => $courierStatus,
        ]);
    }
}
