<?php

namespace App\Http\Controllers;

use App\Models\License;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class LicenseController extends Controller
{
    public function index(): View
    {
        $licenses = License::withCount('activations')->latest()->paginate(15);

        return view('licenses.index', compact('licenses'));
    }

    public function create(): View
    {
        return view('licenses.create', [
            'featureKeys' => array_keys(License::DEFAULT_FEATURES),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'customer_name' => ['nullable', 'string', 'max:255'],
            'customer_email' => ['nullable', 'email', 'max:255'],
            'max_activations' => ['required', 'integer', 'min:1'],
            'expires_at' => ['nullable', 'date'],
            'notes' => ['nullable', 'string'],
        ]);

        $validated['key'] = License::generateKey();
        $validated['status'] = 'active';
        $validated['features'] = $this->featuresFromRequest($request);

        $license = License::create($validated);

        return redirect()->route('licenses.show', $license)->with('status', 'License created.');
    }

    public function show(License $license): View
    {
        $license->load(['activations' => fn ($q) => $q->latest()]);

        return view('licenses.show', compact('license'));
    }

    public function edit(License $license): View
    {
        return view('licenses.edit', [
            'license' => $license,
            'featureKeys' => array_keys(License::DEFAULT_FEATURES),
        ]);
    }

    public function update(Request $request, License $license): RedirectResponse
    {
        $validated = $request->validate([
            'customer_name' => ['nullable', 'string', 'max:255'],
            'customer_email' => ['nullable', 'email', 'max:255'],
            'status' => ['required', 'in:active,suspended,expired'],
            'max_activations' => ['required', 'integer', 'min:1'],
            'expires_at' => ['nullable', 'date'],
            'notes' => ['nullable', 'string'],
        ]);

        $validated['features'] = $this->featuresFromRequest($request);

        $license->update($validated);

        return redirect()->route('licenses.show', $license)->with('status', 'License updated.');
    }

    public function destroy(License $license): RedirectResponse
    {
        $license->delete();

        return redirect()->route('licenses.index')->with('status', 'License deleted.');
    }

    private function featuresFromRequest(Request $request): array
    {
        $features = [];

        foreach (array_keys(License::DEFAULT_FEATURES) as $key) {
            $features[$key] = $request->boolean("features.$key");
        }

        return $features;
    }
}
