<?php

declare(strict_types=1);

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();

        $activeServicesCount = $user->services()
            ->where('status', 'active')
            ->count();

        $activeSubscriptions = $user->subscriptions()
            ->whereIn('stripe_status', ['active', 'trialing'])
            ->latest()
            ->get();

        $activeSubscriptionsCount = $activeSubscriptions->count();

        $latestInvoices = $user->billingInvoices()
            ->latest()
            ->limit(5)
            ->get();

        $pendingInvoicesAmount = $user->billingInvoices()
            ->whereIn('status', ['pending', 'overdue'])
            ->sum('total');

        $nextRenewalDate = $user->subscriptions()
            ->whereIn('stripe_status', ['active', 'trialing'])
            ->whereNotNull('current_period_end')
            ->orderBy('current_period_end')
            ->value('current_period_end');

        $openTicketsCount = SupportTicket::query()
            ->where('user_id', $user->id)
            ->whereIn('status', ['open', 'in_progress', 'waiting'])
            ->count();

        $recentTickets = SupportTicket::query()
            ->where('user_id', $user->id)
            ->latest()
            ->take(5)
            ->get(['id', 'subject', 'status', 'priority', 'created_at', 'updated_at']);

        return Inertia::render('Dashboard', [
            'activeServicesCount' => $activeServicesCount,
            'activeSubscriptionsCount' => $activeSubscriptionsCount,
            'activeSubscriptions' => $activeSubscriptions,
            'latestInvoices' => $latestInvoices,
            'pendingInvoicesAmount' => number_format((float) $pendingInvoicesAmount, 2, '.', ''),
            'nextRenewalDate' => $nextRenewalDate,
            'openTicketsCount' => $openTicketsCount,
            'recentTickets' => $recentTickets,
        ]);
    }
}
