<?php

namespace App\Notifications;

use App\Models\DnsZone;
use App\Models\DnsZoneAlert;
use App\Models\EmailTemplate;
use App\Models\NameServer;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class DnsZoneAlertReminder extends Notification
{
    use Queueable;

    public $zone;
    public $alert;

    /**
     * Create a new notification instance.
     */
    public function __construct(DnsZone $zone, DnsZoneAlert $alert)
    {
        $this->zone = $zone;
        $this->alert = $alert;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $template = EmailTemplate::where('key', 'dns_alert_nameservers_reminder')
            ->where('is_active', true)
            ->first();

        $userName = $notifiable->name ?? 'Administrator';
        $nameservers = $this->zone->nameServers->pluck('hostname')->implode('<br>');

        if ($nameservers === '') {
            $nameservers = NameServer::where('is_active', true)
                ->orderBy('priority')
                ->pluck('hostname')
                ->implode('<br>');
        }

        $hoursLeft = $this->alert->getHoursUntilSuspension();
        $daysSince = $this->alert->getDaysSinceDetection();

        $variables = [
            'name' => $userName,
            'domain' => $this->zone->domain,
            'hours_left' => $hoursLeft,
            'days_since' => $daysSince,
            'notification_count' => $this->alert->notification_count,
            'checked_at' => $this->alert->last_checked_at->format('d.m.Y H:i:s'),
            'nameservers' => $nameservers,
            'app_name' => config('app.name'),
            'app_url' => config('app.url'),
        ];

        if ($template) {
            $subject = $this->replaceVariables($template->subject, $variables);
            $body = $this->replaceVariables($template->body, $variables);

            return (new MailMessage)
                ->subject($subject)
                ->view('emails.custom', ['body' => $body]);
        }

        // Fallback
        return (new MailMessage)
            ->subject("🟠 URGENT: {$hoursLeft}h până la suspendarea {$this->zone->domain}")
            ->line("Bună {$userName},")
            ->line("**REMINDER #{$this->alert->notification_count}** - Nameserverele pentru **{$this->zone->domain}** încă nu sunt configurate corect!")
            ->line("**Timp rămas:** {$hoursLeft} ore (Zi {$daysSince}/3)")
            ->line("**Nameservere necesare:**")
            ->line($nameservers)
            ->action('Configurează ACUM', url("/dns-zones/{$this->zone->domain}"));
    }

    private function replaceVariables(string $text, array $variables): string
    {
        foreach ($variables as $key => $value) {
            $text = str_replace("{" . $key . "}", $value, $text);
            $text = str_replace("{{" . $key . "}}", $value, $text);
        }
        return $text;
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            //
        ];
    }
}
