<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\License;
use App\Models\Ticket;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();

    // Load full licenses with related product and domains using the centralized scope
    $licensesQuery = License::with(['product', 'domains'])->forUser($user)->latest();

        // Paginate for the dashboard list (show latest 10)
        $licenses = $licensesQuery->paginate(10);

        // Compute accurate active licenses count: status 'active' and not expired (if license_expires_at present)
        $activeCount = License::forUser($user)
            ->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('license_expires_at')
                  ->orWhere('license_expires_at', '>', now());
            })->count();

        // Get available products (for suggestions)
        $products = Product::where('is_active', true)->latest()->limit(6)->get();

        // Invoice statistics for user dashboard
        $invoiceTotal = $user->invoices()->count();
        $invoicePaid = $user->invoices()->where('status', 'paid')->count();
        $invoicePending = $user->invoices()->where('status', 'pending')->count();
        $invoiceCancelled = $user->invoices()->where('status', 'cancelled')->count();

        // SEO data
        $seoTitle = \App\Models\Setting::get('seo_site_title', null);
        $seoDescription = \App\Models\Setting::get('seo_site_description', null);

        return view('user.dashboard', compact(
            'licenses',
            'products',
            'activeCount',
            'invoiceTotal',
            'invoicePaid',
            'invoicePending',
            'invoiceCancelled',
            'seoTitle',
            'seoDescription'
        ));
    }
}