<?php

namespace App\Notifications;

use App\Models\Request as RequestModel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class ValidatedRequestPendingSortieNotification extends Notification
{
    use Queueable;

    protected RequestModel $request;

    public function __construct(RequestModel $request)
    {
        $this->request = $request;
    }

    public function via(object $notifiable): array
    {
        $channels = ['database'];
        if ($notifiable->email) {
            $channels[] = 'mail';
        }
        return $channels;
    }

    public function toArray(object $notifiable): array
    {
        $ref = $this->request->reference ?? 'N/A';
        $dept = $this->request->department?->name ?? '-';
        $products = $this->request->requestDetails->map(fn($d) => ($d->product?->name ?? '-') . ' (' . $d->quantity . ')')->join(', ');
        $qty = $this->request->requestDetails->sum('quantity');

        return [
            'request_id' => $this->request->id,
            'request_number' => $ref,
            'icon_type' => 'pending_sortie',
            'message' => "Demande {$ref} validée – en attente de sortie du stock (Département {$dept}, {$qty} unité(s))",
            'products' => $products,
            'department' => $dept,
            'quantity' => $qty,
            'url' => route('movements.index', ['tab' => 'sortie']),
        ];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $ref = $this->request->reference ?? 'N/A';
        $dept = $this->request->department?->name ?? '-';

        return (new MailMessage)
            ->subject("Demande {$ref} validée – Sortie de stock en attente")
            ->greeting('Bonjour ' . ($notifiable->full_name ?? $notifiable->name) . ',')
            ->line("La demande {$ref} du département {$dept} a été validée et est en attente de sortie du stock.")
            ->action('Exécuter la sortie', route('movements.index', ['tab' => 'sortie']))
            ->line('Merci d\'utiliser notre système de gestion des stocks.');
    }
}
