<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LicenseActivation;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminActivationController extends Controller
{
    public function index(Request $request)
    {
        $query = LicenseActivation::with(['license.user']);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('domain', 'like', "%{$search}%")
                  ->orWhereHas('license', fn ($q2) => $q2->where('license_key', 'like', "%{$search}%"));
            });
        }

        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        $activations = $query->latest()->paginate(20)->through(function ($activation) {
            return [
                'id' => $activation->id,
                'domain' => $activation->domain,
                'license_key' => $activation->license->license_key,
                'user_name' => $activation->license->user->name,
                'status' => $activation->status,
                'activated_at' => $activation->activated_at?->format('d M Y'),
                'last_seen_at' => $activation->last_seen_at?->diffForHumans(),
                'requests_24h' => $activation->aiRequests()->where('created_at', '>=', now()->subDay())->count(),
            ];
        });

        return Inertia::render('Admin/Activations', [
            'activations' => $activations,
            'filters' => $request->only(['search', 'status']),
            'total_active' => LicenseActivation::where('status', 'active')->count(),
        ]);
    }
}
