<?php

namespace App\Http\Controllers;

use App\Models\License;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Carbon\Carbon;

class LicenseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
    $query = License::with(['user', 'product'])->latest();

        // Support filtering by user or customer so admin pages and user detail pages
        // can show the same results via query params like ?user=4 or ?customer=3
        if ($userId = request('user')) {
            $query->forUser($userId);
        }

        // Backwards-compat: if a customer query param is provided, treat it as user_id
        if ($customerId = request('customer')) {
            $query->forUser($customerId);
        }

        $licenses = $query->paginate(10)->appends(request()->query());

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $users = \App\Models\User::all();
        $products = \App\Models\Product::all();
        $selectedUserId = request('user_id');

        return view('admin.licenses.create', compact('users', 'products', 'selectedUserId'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'product_id' => 'required|exists:products,id',
            'license_type' => 'required|in:regular,extended',
            'status' => 'required|in:active,inactive,suspended,expired',
            'expires_at' => 'nullable|date|after:today',
            'max_domains' => 'nullable|integer|min:1',
            'notes' => 'nullable|string',
        ]);

        // Keep backwards-compatible customer_id if passed (optional) - map to user_id
        if ($request->filled('customer_id')) {
            $validated['user_id'] = $request->input('customer_id');
        }

        // Map UI field to DB column with proper parsing and allowing null to clear
        if (array_key_exists('expires_at', $validated)) {
            $validated['license_expires_at'] = ($validated['expires_at'] !== null && $validated['expires_at'] !== '')
                ? Carbon::parse($validated['expires_at'])->format('Y-m-d H:i:s')
                : null;
            unset($validated['expires_at']);
        }

        // Generate license key automatically
        $validated['license_key'] = $this->generateLicenseKey();

        // Set purchase_code to be the same as license_key for now
        // This ensures consistency between what users enter and what's stored
        $validated['purchase_code'] = $validated['license_key'];

        // Set default values
        if (!isset($validated['max_domains'])) {
            $validated['max_domains'] = 1;
        }

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

        return redirect()->route('admin.licenses.index')
            ->with('success', trans('app.License created successfully.'));
    }

    /**
     * Display the specified resource.
     */
    public function show(License $license)
    {
    $license->load(['user', 'product', 'logs']);
        return view('admin.licenses.show', compact('license'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(License $license)
    {
        $users = \App\Models\User::all();
        $products = \App\Models\Product::all();

        return view('admin.licenses.edit', compact('license', 'users', 'products'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, License $license)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'product_id' => 'required|exists:products,id',
            'license_type' => 'required|in:regular,extended',
            'status' => ['required', Rule::in(['active', 'inactive', 'suspended', 'expired'])],
            'expires_at' => ['nullable', 'date'],
            'notes' => ['nullable', 'string'],
            'max_domains' => ['nullable', 'integer', 'min:1'],
        ]);

        if ($request->filled('customer_id')) {
            $validated['user_id'] = $request->input('customer_id');
        }

        // Map UI field to DB column with proper parsing and allowing null to clear
        if (array_key_exists('expires_at', $validated)) {
            $validated['license_expires_at'] = ($validated['expires_at'] !== null && $validated['expires_at'] !== '')
                ? Carbon::parse($validated['expires_at'])->format('Y-m-d H:i:s')
                : null;
            unset($validated['expires_at']);
        }

        // Set default values
        if (!isset($validated['max_domains'])) {
            $validated['max_domains'] = 1;
        }

        $license->update($validated);

        return redirect()->route('admin.licenses.index')
            ->with('success', trans('app.License updated successfully.'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(License $license)
    {
        $license->delete();

        return redirect()->route('admin.licenses.index')
            ->with('success', trans('app.License deleted successfully.'));
    }

    /**
     * Generate a unique license key
     */
    private function generateLicenseKey()
    {
        do {
            $key = strtoupper(substr(md5(microtime()), 0, 16));
            $key = substr($key, 0, 4) . '-' . substr($key, 4, 4) . '-' . substr($key, 8, 4) . '-' . substr($key, 12, 4);
        } while (License::where('license_key', $key)->exists());

        return $key;
    }
}
