<?php

namespace App\Listeners;

use App\NotifyMe;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Events\WebhookReceived;

class StripeEventListener
{
    use NotifyMe;

    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(WebhookReceived $event): void
    {
        if ($event->payload['type'] === 'invoice.payment_succeeded') {
            session()->flash('alert', ['type' => 'success', 'message' => 'Payment completed successfully.']);
            Log::info('Payment succeeded');
            $amount = $event->payload['data']['object']['amount_paid'] / 100 ?? 'Unknown'; // Convert cents to dollars
            $email = $event->payload['data']['object']['customer_email'] ?? 'Unknown';

            $message = "✅ Payment Success\n".
                "Email: {$email}\n".
                'Amount: $'.number_format($amount, 2)."\n".
                'Time: '.now()->toDateTimeString();
            self::sendTelegramNotification($message);
        }

        if ($event->payload['type'] === 'customer.subscription.deleted') {
            session()->flash('alert', ['type' => 'error', 'message' => 'Subscription canceled.']);
            Log::info('Subscription canceled');

            $email = $event->payload['data']['object']['customer_email'] ?? 'Unknown';

            $message = "❌ Subscription Canceled\n".
                "Email: {$email}\n".
                'Time: '.now()->toDateTimeString();
            self::sendTelegramNotification($message);
        }
    }
}
