<?php

namespace App\Notifications;

use App\Models\Order;
use App\Notifications\Traits\ChecksNotificationSettings;
use App\Services\CurrencyService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

/**
 * Notification sent to administrators when a new store order is placed.
 */
class AdminNewStoreOrder extends Notification implements ShouldQueue
{
    use Queueable, ChecksNotificationSettings;

    protected CurrencyService $currencyService;

    public function __construct(
        public Order $order
    ) {
        $this->currencyService = app(CurrencyService::class);
    }

    public function via(object $notifiable): array
    {
        // Database first to ensure in-app notification is saved even if email fails
        return ['database', 'mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $itemsList = $this->order->items->map(function ($item) {
            return "• {$item->quantity}x {$item->product_name} - " . $this->order->formatCurrency($item->subtotal);
        })->implode("\n");

        $message = (new MailMessage)
            ->subject('🛒 Nueva Orden #' . $this->order->order_number)
            ->greeting('¡Nuevo pedido recibido!')
            ->line('Se ha recibido un nuevo pedido en la tienda.')
            ->line('')
            ->line('**Información del Pedido:**')
            ->line('**Número:** ' . $this->order->order_number)
            ->line('**Fecha:** ' . $this->order->created_at->format('d/m/Y H:i'))
            ->line('')
            ->line('**Cliente:**')
            ->line('**Nombre:** ' . $this->order->user->name)
            ->line('**Email:** ' . $this->order->user->email)
            ->line('')
            ->line('**Productos:**')
            ->line($itemsList)
            ->line('')
            ->line('**Subtotal:** ' . $this->order->formatCurrency($this->order->subtotal));

        if ($this->order->discount_amount > 0) {
            $message->line('**Descuento:** -' . $this->order->formatCurrency($this->order->discount_amount));
        }

        if ($this->order->tax_amount > 0) {
            $message->line('**Impuestos:** ' . $this->order->formatCurrency($this->order->tax_amount));
        }

        if ($this->order->shipping_cost > 0) {
            $message->line('**Envío:** ' . $this->order->formatCurrency($this->order->shipping_cost));
        }

        $message->line('**TOTAL:** ' . $this->order->formatCurrency($this->order->total))
            ->line('')
            ->line('**Método de Pago:** ' . $this->getPaymentMethodLabel())
            ->line('**Estado:** ' . $this->getStatusLabel())
            ->line('')
            ->action('Ver Pedido en Admin', route('admin.store.orders.show', $this->order->id))
            ->salutation('Sistema de Notificaciones CoachPro');

        return $message;
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'admin_new_store_order',
            'order_id' => $this->order->id,
            'order_number' => $this->order->order_number,
            'customer_name' => $this->order->user->name,
            'customer_email' => $this->order->user->email,
            'total' => $this->order->total,
            'items_count' => $this->order->items->count(),
            'payment_method' => $this->order->payment_method,
            'status' => $this->order->status,
            'message' => "Nuevo pedido #{$this->order->order_number} de {$this->order->user->name} por " . $this->order->formatCurrency($this->order->total),
            'title' => 'Nueva Orden Recibida',
            'url' => route('admin.store.orders.show', $this->order->id),
            'icon' => 'shopping-cart',
            'priority' => 'high',
        ];
    }

    protected function getPaymentMethodLabel(): string
    {
        $labels = [
            'paypal' => 'PayPal',
            'stripe' => 'Tarjeta (Stripe)',
            'card' => 'Tarjeta de Crédito',
            'transfer' => 'Transferencia Bancaria',
            'cash' => 'Efectivo',
        ];

        return $labels[$this->order->payment_method] ?? $this->order->payment_method;
    }

    protected function getStatusLabel(): string
    {
        $labels = [
            'pending' => '⏳ Pendiente',
            'awaiting_payment' => '💳 Esperando Pago',
            'processing' => '📦 En Proceso',
            'shipped' => '🚚 Enviado',
            'delivered' => '✅ Entregado',
            'cancelled' => '❌ Cancelado',
            'refunded' => '↩️ Reembolsado',
        ];

        return $labels[$this->order->status] ?? $this->order->status;
    }

    public function databaseType(object $notifiable): string
    {
        return 'admin_new_store_order';
    }
}
