<?php
namespace App\Notifications;

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

class GrantConfirmationNotification extends Notification
{
    protected Grant $grant;

    public function __construct(Grant $grant)
    {
        $this->grant = $grant;
    }

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

    public function toMail($notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Your Grant Application Has Been Received')
            ->view('emails.grants.confirmation', [
                'grant' => $this->grant
            ]);
    }

    public function toDatabase($notifiable): array
    {
        return [
            'grant_id' => $this->grant->id,
            'type' => $this->grant->type,
            'amount' => $this->grant->amount,
            'title' => $this->getTitle(),
            'status' => ucfirst($this->grant->status),
            'message' => $this->generateMessage(),
            'link' => url('/grant/logs'),
        ];
    }

    /**
     * Generate a human-readable message for notifications page.
     */
    protected function generateMessage(): string
    {
        $titleText = $this->getTitle(); // now type-based
        $extraInfo = '';

        // Optionally include project title (company) or first purpose (personal) in message
        if ($this->grant->type === 'company' && !empty($this->grant->metadata['project']['title'])) {
            $extraInfo = ' (“' . $this->grant->metadata['project']['title'] . '”)';
        } elseif ($this->grant->type === 'personal' && !empty($this->grant->purposes)) {
            $extraInfo = ' (' . ucwords(str_replace('_', ' ', $this->grant->purposes[0])) . ')';
        }

        return sprintf(
            'Your %s of $%s%s has been submitted and is currently %s.',
            $titleText,
            number_format($this->grant->amount ?? 0, 2, '.', ','),
            $extraInfo,
            ucfirst($this->grant->status)
        );
    }

    /**
     * Return title based strictly on grant type
     */
    protected function getTitle(): string
    {
        return $this->grant->type === 'company'
            ? 'Company Grant Application'
            : 'Personal Grant Application';
    }
}
