<?php

namespace App\Services;

use App\Models\Delivery;
use App\Models\User;
use Illuminate\Support\Str;

class TelegramNotificationService
{
    public function sendToUser(User $user, string $text): void
    {
        if (!$user->telegram_chat_id) {
            return;
        }

        app(TelegramService::class)->sendMessage($user->telegram_chat_id, $text);
    }

    public function sendToAdmin(string $text): void
    {
        $chatId = config('services.telegram.admin_chat_id');
        if (!$chatId) {
            return;
        }

        app(TelegramService::class)->sendMessage($chatId, $text);
    }

    public function formatCourierAssignment(Delivery $delivery): string
    {
        $restaurant = $delivery->restaurant?->name ?? 'Restaurante';
        $pickup = $delivery->restaurant?->address ?? 'Recogida';
        $dropoff = $delivery->delivery_address ?: 'Por definir';
        $urgent = $delivery->is_urgent ? "🚨 PEDIDO URGENTE\n" : "🚚 NUEVO PEDIDO\n";
        $payment = $delivery->payment_method === 'cash' ? 'Efectivo' : 'Wallet';
        $fee = $delivery->delivery_fee !== null ? number_format($delivery->delivery_fee, 2) : '0.00';
        $when = $delivery->created_at
            ? $delivery->created_at->locale('es')->translatedFormat('d F Y \\· h:i a')
            : null;

        $id = $delivery->id;
        $url = url('/courier');

        return $urgent .
            "🧾 Orden #{$id}\n" .
            "🏪 Restaurante: {$restaurant}\n" .
            "📍 Recogida: {$pickup}\n" .
            "🏠 Entrega: {$dropoff}\n" .
            "💳 Pago: {$payment} · €{$fee}\n" .
            ($when ? "🕒 {$when}\n" : '') .
            "🔗 Ver: {$url}";
    }

    public function formatAdminNewOrder(Delivery $delivery): string
    {
        $restaurant = $delivery->restaurant?->name ?? 'Restaurante';
        $dropoff = $delivery->delivery_address ?: 'Por definir';
        $urgent = $delivery->is_urgent ? "🚨 ORDEN URGENTE\n" : "🧾 NUEVA ORDEN\n";
        $payment = $delivery->payment_method === 'cash' ? 'Efectivo' : 'Wallet';
        $fee = $delivery->delivery_fee !== null ? number_format($delivery->delivery_fee, 2) : '0.00';
        $when = $delivery->created_at
            ? $delivery->created_at->locale('es')->translatedFormat('d F Y \\· h:i a')
            : null;
        $id = $delivery->id;
        $url = url('/admin/orders/' . $id);

        return $urgent .
            "🧾 Orden #{$id}\n" .
            "🏪 Restaurante: {$restaurant}\n" .
            "🏠 Entrega: {$dropoff}\n" .
            "💳 Pago: {$payment} · €{$fee}\n" .
            ($when ? "🕒 {$when}\n" : '') .
            "🔗 Ver: {$url}";
    }
}
