<?php

namespace App\Http\Controllers\Customer;

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

class LicenseController extends Controller
{
    public function index()
    {
        $licenses = auth()->user()->licenses()->with('product')->latest()->paginate((int) setting('items_per_page', 15));
        return view('customer.licenses.index', compact('licenses'));
    }

    public function show(License $license)
    {
        // Use the same relationship query as the index page.
        // This is more reliable than comparing user_id directly,
        // as it handles any edge cases where user IDs might differ.
        $owned = auth()->user()->licenses()->where('licenses.id', $license->id)->exists();

        if (! $owned) {
            return redirect()->route('customer.licenses.index')
                ->with('error', 'That license does not belong to your account. Here are your licenses.');
        }

        $license->load(['product', 'activations', 'downloads']);
        return view('customer.licenses.show', compact('license'));
    }

    public function deactivateActivation(License $license, LicenseActivation $activation)
    {
        abort_unless(auth()->user()->licenses()->where('licenses.id', $license->id)->exists(), 403);
        abort_if($activation->license_id !== $license->id, 404);

        $activation->update(['status' => 'deactivated', 'deactivated_at' => now()]);
        $license->decrement('activations_count');

        return back()->with('success', 'Activation removed. You can now activate on a new installation.');
    }

    public function apiCredentials(License $license)
    {
        abort_unless(auth()->user()->licenses()->where('licenses.id', $license->id)->exists(), 403);

        // Show secret key once — only accessible to the license owner
        return view('customer.licenses.credentials', compact('license'));
    }
}
