<?php

declare(strict_types=1);

namespace App\Filament\Resources\PaymentResource\Pages;

use App\Filament\Resources\PaymentResource;
use App\Models\Payment;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Facades\Schema;

class ViewPayment extends ViewRecord
{
    protected static string $resource = PaymentResource::class;

    /**
     * Header actions: open/copy public HPP link + Edit.
     *
     * @return array<int, \Filament\Actions\Action|\Filament\Actions\EditAction>
     */
    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('openPublicPayLink')
                ->label('Open public pay link')
                ->icon('heroicon-o-link')
                ->color('primary')
                ->url(fn () => $this->publicPayUrl($this->record))
                ->openUrlInNewTab(),

            Actions\Action::make('copyPublicPayLink')
                ->label('Copy pay link')
                ->icon('heroicon-o-clipboard')
                ->action(fn () => null) // server-side no-op; clipboard handled client-side
                ->extraAttributes(function () {
                    $url = e($this->publicPayUrl($this->record));
                    return [
                        'x-data'     => '{}',
                        'x-on:click' => "navigator.clipboard.writeText('{$url}').then(()=>alert('Link copied')).catch(()=>alert('Copy failed: {$url}'));",
                    ];
                }),

            Actions\EditAction::make(),
        ];
    }

    /**
     * Build/ensure the public Hosted Payment Page URL for this Payment.
     */
    protected function publicPayUrl(Payment $payment): string
    {
        $this->ensurePublicLink($payment);

        // Refresh relation to guarantee we have the token
        $payment->unsetRelation('link');
        $payment->load('link');

        // Use the lightweight /pay/{token} route as per your Job page implementation
        return url('/pay/' . $payment->link->public_token);

        // If you prefer a named route, swap to:
        // return route('payments.public.show', ['token' => $payment->link->public_token]);
    }

    /**
     * Ensure a PaymentLink exists on the Payment (creates one if missing).
     */
    protected function ensurePublicLink(Payment $payment): void
    {
        $payment->loadMissing('link');

        if (blank(optional($payment->link)->public_token)) {
            $payment->link()->create([
                // keep tenancy aligned with the Payment (if present in your schema)
                'tenant_id'    => Schema::hasColumn('payment_links', 'tenant_id') ? $payment->tenant_id : null,
                'public_token' => bin2hex(random_bytes(24)),
            ]);
        }
    }
}
