<?php

namespace App\Livewire\Checkout;

use App\Enums\PaymentStatus;
use App\Enums\SubscriptionStatus;
use App\Models\Payment;
use App\Models\Subscription;
use Livewire\Component;

class Success extends Component
{
    public bool   $subscriptionReady = false;
    public bool   $paymentReady      = false;
    public bool   $done              = false;
    public string $since             = '';

    public function mount(): void
    {
        // 60 Sekunden Fenster – Webhook braucht manchmal ein paar Sekunden
        $this->since = now()->subMinutes(1)->toDateTimeString();
        $this->checkStatus();
    }

    public function checkStatus(): void
    {
        if ($this->done) {
            return;
        }

        $userId = auth()->id();

        $sub = Subscription::where('user_id', $userId)
            ->where('provider', 'stripe')
            ->where('status', SubscriptionStatus::Active->value)
            ->latest('created_at')
            ->first();

        $this->subscriptionReady = $sub !== null;

        if ($sub) {
            // Primär: Payment direkt an dieser Subscription
            $this->paymentReady = Payment::where('subscription_id', $sub->id)
                ->where('status', PaymentStatus::Paid->value)
                ->exists();

            // Fallback: irgendein paid-Payment des Users seit Seitenaufruf
            // (fängt Race-Conditions ab wo Payment an anderer Sub-ID hängt)
            if (!$this->paymentReady) {
                $this->paymentReady = Payment::where('user_id', $userId)
                    ->where('status', PaymentStatus::Paid->value)
                    ->where('created_at', '>=', $this->since)
                    ->exists();
            }
        }

        $this->done = $this->subscriptionReady && $this->paymentReady;
    }

    public function render()
    {
        return view('livewire.checkout.success')
            ->layout('layouts.app');
    }
}
