<?php

namespace App\Http\Controllers\Admin;

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

class AdminLicenseController extends Controller
{
    public function index(Request $request)
    {
        $query = License::with(['user', 'activeActivations']);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('license_key', 'like', "%{$search}%")
                  ->orWhereHas('user', fn ($q2) => $q2->where('first_name', 'like', "%{$search}%")->orWhere('last_name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%"));
            });
        }

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

        $licenses = $query->latest()->paginate(20)->through(fn ($license) => [
            'id' => $license->id,
            'license_key' => $license->license_key,
            'user_name' => $license->user->name,
            'user_email' => $license->user->email,
            'domain' => $license->activeActivations->first()?->domain,
            'status' => $license->status,
            'created_at' => $license->created_at->format('d M Y'),
        ]);

        return Inertia::render('Admin/Licenses', [
            'licenses' => $licenses,
            'filters' => $request->only(['search', 'status']),
            'total_licenses' => License::count(),
        ]);
    }

    public function revoke(License $license)
    {
        $license->update(['status' => 'revoked']);
        $license->activations()->update(['status' => 'revoked']);

        return back()->with('success', 'License revoked successfully.');
    }

    public function reinstate(License $license)
    {
        $license->update(['status' => 'active']);

        return back()->with('success', 'License reinstated successfully.');
    }
}
