<?php
namespace App\Notifications;

use App\Models\Approval;
use App\Services\ApprovalService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class ApprovalDecided extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public Approval $approval) {}

    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function label(): string
    {
        $a = $this->approval;
        $t = ApprovalService::types()[$a->document_type] ?? null;
        return ($t['label'] ?? $a->document_type) . ' ' . $a->document_no;
    }

    public function toMail(object $notifiable): MailMessage
    {
        $ok = $this->approval->status === 'approved';
        return (new MailMessage)
            ->subject(($ok ? 'Approved: ' : 'Rejected: ') . $this->label())
            ->greeting('Hello ' . $notifiable->name . ',')
            ->line('**' . $this->label() . '** was **' . $this->approval->status . '** by ' . ($this->approval->decider->name ?? '—') . '.')
            ->line($this->approval->remarks ? 'Remarks: ' . $this->approval->remarks : 'No remarks recorded.')
            ->action('View Approvals', url('/approvals'));
    }

    public function toArray(object $notifiable): array
    {
        $ok = $this->approval->status === 'approved';
        return [
            'title' => ($ok ? 'Approved: ' : 'Rejected: ') . $this->label(),
            'body' => 'Decided by ' . ($this->approval->decider->name ?? '—') . ($this->approval->remarks ? ' — ' . $this->approval->remarks : ''),
            'url' => '/approvals',
            'icon' => $ok ? '✅' : '❌',
            'kind' => 'approval_decided',
            'approval_id' => $this->approval->id,
        ];
    }
}
