<?php

namespace App\Notifications;

use App\Models\Backup;
use App\Models\EmailTemplate;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class BackupFailed extends Notification
{
    use Queueable;

    public $backup;
    public $errorMessage;
    public $ipAddress;
    public $performedAt;

    /**
     * Create a new notification instance.
     */
    public function __construct(Backup $backup, string $errorMessage, ?string $ipAddress = null)
    {
        $this->backup = $backup;
        $this->errorMessage = $errorMessage;
        $this->ipAddress = $ipAddress ?? request()->ip();
        $this->performedAt = now();
    }

    /**
     * Get the notification's delivery channels.
     */
    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', 'backup_failed')
            ->where('is_active', true)
            ->first();

        $variables = [
            'user_name' => is_object($notifiable) && isset($notifiable->name) ? $notifiable->name : 'Administrator',
            'backup_id' => $this->backup->id,
            'backup_type' => $this->backup->type === 'full' ? 'Complet' : 'Incremental',
            'error_message' => $this->errorMessage,
            'failed_date' => now()->format('d.m.Y H:i'),
            'performed_at' => $this->performedAt->format('d.m.Y H:i:s'),
            'ip_address' => $this->ipAddress,
            '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)
                ->html($body);
        }

        // Fallback
        $userName = is_object($notifiable) && isset($notifiable->name) ? $notifiable->name : 'Administrator';
        
        return (new MailMessage)
            ->error()
            ->subject('Backup Eșuat')
            ->line("Bună {$userName},")
            ->line("Backup-ul #{$this->backup->id} a eșuat.")
            ->line("**Eroare:**")
            ->line($this->errorMessage)
            ->line("**Detalii:**")
            ->line("- ID: #{$this->backup->id}")
            ->line("- Tip: " . ($this->backup->type === 'full' ? 'Complet' : 'Incremental'))
            ->line("- Data/Ora: {$this->performedAt->format('d.m.Y H:i:s')}")
            ->line("- IP: {$this->ipAddress}")
            ->action('Vezi Backup-uri', url('/admin/backups'));
    }

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