<?php
namespace App\Services;

use App\Models\NexusNotification;
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
use App\Models\Ticket;
use App\Models\User;

class NotificationService
{
    // Ticket creado: notificar a admins/jefes y al agente asignado
    public function onTicketCreated(Ticket $ticket): void
    {
        $url   = route('tickets.show', $ticket);
        $title = "Nuevo ticket {$ticket->number}";
        $body  = $ticket->title;

        // Notificar a todos los admins y jefes
        User::role(['admin', 'superadmin', 'jefe_soporte'])
            ->where('id', '!=', $ticket->requester_id)
            ->get()
            ->each(fn($u) => NexusNotification::send($u->id, 'ticket_created', $title, $body, $url));

        // Notificar al agente asignado si existe
        if ($ticket->assignee_id && $ticket->assignee_id !== $ticket->requester_id) {
            NexusNotification::send(
                $ticket->assignee_id, 'ticket_assigned',
                "Se te asignó el ticket {$ticket->number}", $body, $url
            );
        }
    }

    // Estado cambiado: notificar al solicitante
    public function onStatusChanged(Ticket $ticket, string $oldStatus, string $newStatus): void
    {
        $url  = route('tickets.show', $ticket);
        NexusNotification::send(
            $ticket->requester_id,
            'ticket_status_changed',
            "Ticket {$ticket->number} actualizado",
            "Estado cambiado de '{$oldStatus}' a '{$newStatus}'",
            $url
        );

        if ($ticket->status->is_final) {
            NexusNotification::send(
                $ticket->requester_id,
                'ticket_closed',
                "Ticket {$ticket->number} resuelto",
                "Tu solicitud ha sido resuelta. ¿Puedes calificar la atención?",
                $url
            );
        }

        // Notificar por email al solicitante
        $requester = $ticket->requester;
        if ($requester && $requester->email) {
            try {
                $portalUrl = route('portal.show', $ticket);
                Mail::send([], [], function (Message $mail) use ($requester, $ticket, $newStatus, $portalUrl) {
                    $mail->to($requester->email, $requester->name)
                         ->subject("Actualización de tu solicitud {$ticket->number} — NEXUS Fedef")
                         ->html("
                            <div style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px'>
                                <img src='https://fedef.evolucionamos.com/images/logo.png' style='height:60px;margin-bottom:20px'>
                                <h2 style='color:#1d4ed8'>Actualización de tu solicitud</h2>
                                <p>Hola <strong>{$requester->name}</strong>,</p>
                                <p>Tu solicitud <strong>{$ticket->number}</strong> ha sido actualizada:</p>
                                <div style='background:#f1f5f9;border-radius:8px;padding:16px;margin:16px 0'>
                                    <p style='margin:0'><strong>Asunto:</strong> {$ticket->title}</p>
                                    <p style='margin:8px 0 0'><strong>Nuevo estado:</strong> <span style='color:#1d4ed8'>{$newStatus}</span></p>
                                </div>
                                <a href='{$portalUrl}' style='display:inline-block;background:#1d4ed8;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:bold'>
                                    Ver mi solicitud
                                </a>
                                <p style='color:#6b7280;font-size:12px;margin-top:24px'>NEXUS Service Desk — Fedef</p>
                            </div>
                         ");
                });
            } catch (\Throwable $e) {
                \Log::warning('Email notificación fallida: ' . $e->getMessage());
            }
        }
    }

    // Nuevo comentario: notificar a las partes
    public function onComment(Ticket $ticket, int $commenterId, bool $isInternal): void
    {
        if ($isInternal) return; // notas internas no notifican al usuario

        $url      = route('tickets.show', $ticket);
        $commenter = User::find($commenterId);

        $notifyIds = collect([$ticket->requester_id, $ticket->assignee_id])
            ->filter()
            ->unique()
            ->reject(fn($id) => $id === $commenterId);

        foreach ($notifyIds as $uid) {
            NexusNotification::send(
                $uid, 'ticket_comment',
                "Nuevo comentario en {$ticket->number}",
                "{$commenter->name} comentó en: {$ticket->title}",
                $url
            );
        }
    }

    // Asignación: notificar al nuevo agente
    public function onAssigned(Ticket $ticket, ?int $oldAssigneeId): void
    {
        if (!$ticket->assignee_id) return;
        $url = route('tickets.show', $ticket);
        NexusNotification::send(
            $ticket->assignee_id,
            'ticket_assigned',
            "Se te asignó el ticket {$ticket->number}",
            $ticket->title,
            $url
        );
    }

    // SLA por vencer (llamado por comando/scheduler)
    public function onSlaWarning(Ticket $ticket): void
    {
        $url  = route('tickets.show', $ticket);
        $notify = collect([$ticket->assignee_id])
            ->filter()
            ->merge(User::role(['admin','jefe_soporte'])->pluck('id'));

        foreach ($notify->unique() as $uid) {
            NexusNotification::send(
                $uid, 'sla_warning',
                "SLA por vencer — {$ticket->number}",
                "Quedan menos de 2 horas para vencer el SLA de resolución",
                $url
            );
        }
    }
}
