<?php

namespace App\Notifications;


use App\Models\Grant;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class GrantStatusNotification extends Notification
{

    /**
     * Create a new notification instance.
     */
    public Grant $grant;
    public string $status;
    public ?string $note;

    public function __construct(Grant $grant, string $status, ?string $note = null)
    {
        $this->grant = $grant;
        $this->status = $status;
        $this->note = $note;
    }

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


    /**
     * Get the mail representation of the notification.
     */
    /**
     * Get the mail representation of the notification.
     */

    public function toMail($notifiable)
    {
        $appName = config('app.name');
        $headerUrl = config('app.url');

        $subject = "Your Grant Request #{$this->grant->id} is {$this->grant->statusLabel}";

        // Flatten grant metadata
        $flatten = function (array $array, string $prefix = '') use (&$flatten) {
            $result = [];
            foreach ($array as $key => $value) {
                $fullKey = $prefix === '' ? $key : "{$prefix}.{$key}";
                if (is_array($value)) {
                    $result += $flatten($value, $fullKey);
                } else {
                    $result[$fullKey] = $value;
                }
            }
            return $result;
        };

        $grantArray = $this->grant->only(['id', 'type', 'amount', 'purpose', 'status', 'created_at']);
        $metadata = $this->grant->metadata ?? [];
        $flatMetadata = $flatten(is_array($metadata) ? $metadata : [], '');

        $grantDetails = [
            'ID' => $grantArray['id'],
            'Type' => ucfirst($grantArray['type'] ?? '-'),
            'Amount' => number_format((float) $grantArray['amount'], 2),
            'Purpose' => $grantArray['purpose'] ?? '-',
            'Status' => $this->grant->statusLabel,      // <--- use accessor
            'Created At' => optional($this->grant->created_at)->format('Y-m-d H:i'),
        ];

        foreach ($flatMetadata as $k => $v) {
            $label = ucwords(str_replace(['_', '.'], [' ', ' → '], $k));
            $grantDetails[$label] = is_null($v) || $v === '' ? '-' : (string) $v;
        }

        $userName = $notifiable->name ?? 'User';

        return (new MailMessage)
            ->subject($subject)
            ->view('emails.grants.grant-status', [
                'subject' => $subject,
                'appName' => $appName,
                'userName' => $userName,
                'grantDetails' => $grantDetails,
                'buttonUrl' => route('user.grants.history'),
                'displayStatus' => $this->grant->statusLabel,  // <--- use accessor
                'statusColor' => $this->grant->statusColor,    // <--- use accessor
                'buttonColor' => $this->grant->statusColor,    // <--- use accessor
                'headerUrl' => $headerUrl,
                'note' => $this->note,
                'grantId' => $this->grant->id,
            ]);
    }



    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        $displayStatus = match ($this->status) {
            'approved' => 'Approved',
            'rejected' => 'Rejected',
            'on_hold' => 'On Hold',
            default => ucwords(str_replace('_', ' ', $this->status)),
        };

        return [
            'title' => "Grant Request #{$this->grant->id} {$displayStatus}",
            'message' => "Your grant request #{$this->grant->id} has been {$displayStatus}",
            'link' => route('user.grants.history'), // Link to the grant details
            'grant_id' => $this->grant->id,
            'status' => $this->status,
            'note' => $this->note,
        ];
    }

}
