<?php

namespace App\Livewire\Invoices;

use App\Enums\PaymentStatus;
use App\Models\Payment;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public function render()
    {
        $user = auth()->user();

        $subscription = $user->subscription()->with('plan')->first()
            ?? $user->latestSubscription()->with('plan')->first();

        $openPayments = Payment::where('user_id', $user->id)
            ->whereIn('status', [PaymentStatus::Pending->value, PaymentStatus::Failed->value])
            ->with('subscription')
            ->latest()
            ->get();

        $payments = Payment::where('user_id', $user->id)
            ->with('subscription')
            ->latest()
            ->paginate(15);

        $daysLeft = $subscription?->ends_at
            ? (int) now()->diffInDays($subscription->ends_at, false)
            : null;

        return view('livewire.invoices.index', [
            'subscription'  => $subscription,
            'openPayments'  => $openPayments,
            'payments'      => $payments,
            'daysLeft'      => $daysLeft,
        ])->layout('layouts.app');
    }
}
