<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Throwable;

class AdminTransactionMail extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public function __construct(
        public string $memberName,
        public string $memberEmail,
        public float $amount,
        public string $currencyCode,
        public string $transactionType,
        public string $status,
        public string $channel = 'internal',
        public ?string $reference = null,
    ) {}

    public function envelope(): Envelope
    {
        $typeLabel = ucfirst(str_replace('_', ' ', $this->transactionType));
        $statusLabel = ucfirst($this->status);

        return new Envelope(
            subject: "{$typeLabel} {$statusLabel}: {$this->currencyCode} ".number_format($this->amount, 2),
        );
    }

    public function content(): Content
    {
        $typeLabel = ucfirst(str_replace('_', ' ', $this->transactionType));
        $statusLabel = ucfirst($this->status);
        $channelLabel = strtoupper($this->channel);

        return new Content(
            view: 'emails.simple-message',
            with: [
                'greeting' => 'Hello Admin,',
                'intro' => "A member {$typeLabel} transaction has been {$this->status}.",
                'lines' => [
                    "Member: {$this->memberName} ({$this->memberEmail})",
                    "Channel: {$channelLabel}",
                    "Amount: {$this->currencyCode} ".number_format($this->amount, 2),
                    "Status: {$statusLabel}",
                    'Reference: '.($this->reference ?: 'N/A'),
                ],
                'actionText' => 'Open Transactions',
                'actionUrl' => $this->resolveAdminTransactionsUrl(),
                'outro' => 'Please review this transaction in the admin panel.',
            ],
        );
    }

    protected function resolveAdminTransactionsUrl(): string
    {
        try {
            if (app()->bound('url')) {
                return route('admin.transactions.index');
            }
        } catch (Throwable) {
            // Fallback is returned below.
        }

        return rtrim((string) config('app.url'), '/').'/admin/transactions';
    }
}
