<?php

namespace App\Listeners;

use App\Events\LeaveStatusUpdatedEvent;
use App\Services\NotificationService;

class SendLeaveStatusNotificationListener
{
    public function __construct(
        protected NotificationService $notificationService
    ) {}

    public function handle(LeaveStatusUpdatedEvent $event): void
    {
        $application = $event->leaveApplication;
        $user = $application->user;

        if (!$user) {
            return;
        }

        $typeLabel = strtoupper($application->type);
        $statusLabel = $event->status === 'approved' ? 'DISETUJUI' : 'DITOLAK';
        $studentName = $user->name;
        $classLabel = $user->class_name ? " ({$user->class_name})" : '';
        $title = "Pengajuan {$typeLabel} {$studentName} Telah {$statusLabel}";

        $message = "Yth. Orang Tua/Wali Murid,\n\nPengajuan {$typeLabel} atas nama *{$studentName}*{$classLabel} untuk tanggal {$application->start_date->format('d/m/Y')} s/d {$application->end_date->format('d/m/Y')} telah *{$statusLabel}*.";
        if ($event->notes) {
            $message .= "\nCatatan: {$event->notes}";
        }
        if (!empty($user->parent_token)) {
            $message .= "\n\nPortal orang tua: " . route('parent.portal', $user->parent_token);
        }

        $notificationType = $event->status === 'approved' ? 'success' : 'danger';

        $this->notificationService->notify($user, $title, $message, $notificationType, ['database', 'email', 'whatsapp']);
    }
}
