<?php

namespace App\Http\Controllers;

use App\Models\License;
use App\Services\LicenseKeyGenerator;
use Illuminate\Http\Request;
use Carbon\Carbon;

class LicenseController extends Controller
{
    protected $licenseGenerator;

    public function __construct(LicenseKeyGenerator $licenseGenerator)
    {
        $this->licenseGenerator = $licenseGenerator;
    }

    public function index(Request $request)
    {
        $query = License::query();

        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('key', 'like', '%' . $request->search . '%')
                  ->orWhere('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%');
            });
        }

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

        $licenses = $query->orderBy('created_at', 'desc')->paginate(15);
        
        $stats = [
            'total' => License::count(),
            'active' => License::where('status', 'active')->count(),
            'expired' => License::where('status', 'expired')->count(),
            'suspended' => License::where('status', 'suspended')->count(),
            'revoked' => License::where('status', 'revoked')->count(),
        ];

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

    public function create()
    {
        return view('licenses.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'expires_at' => 'nullable|date',
            'max_devices' => 'nullable|integer|min:1|max:100',
            'quantity' => 'nullable|integer|min:1|max:100',
            'note' => 'nullable|string',
        ]);

        $quantity = (int) ($validated['quantity'] ?? 1);
        
        if ($quantity === 1) {
            $license = $this->licenseGenerator->create($validated);
            return redirect()->route('licenses.show', $license->id)
                ->with('success', 'License created successfully!');
        }

        // Create multiple licenses
        $licenses = $this->licenseGenerator->createMultiple($validated, $quantity);
        
        return redirect()->route('licenses.index')
            ->with('success', $quantity . ' licenses created successfully!');
    }

    public function show(License $license)
    {
        $license->load('deviceLogs');
        
        $deviceStats = [
            'total' => $license->deviceLogs()->count(),
            'active' => $license->deviceLogs()->where('is_active', true)->count(),
            'inactive' => $license->deviceLogs()->where('is_active', false)->count(),
        ];

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

    public function edit(License $license)
    {
        return view('licenses.edit', compact('license'));
    }

    public function update(Request $request, License $license)
    {
        $validated = $request->validate([
            'name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'max_devices' => 'nullable|integer|min:1|max:100',
            'note' => 'nullable|string',
        ]);

        $license->update($validated);

        return redirect()->route('licenses.show', $license->id)
            ->with('success', 'License updated successfully!');
    }

    public function updateStatus(Request $request, License $license)
    {
        $validated = $request->validate([
            'status' => 'required|in:active,expired,suspended,revoked',
        ]);

        $license->update(['status' => $validated['status']]);

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

    public function renew(Request $request, License $license)
    {
        $validated = $request->validate([
            'new_expiry' => 'required|date|after:today',
        ]);

        $this->licenseGenerator->renewWithDate($license->key, $validated['new_expiry']);

        return redirect()->route('licenses.show', $license->id)
            ->with('success', 'License renewed until ' . \Carbon\Carbon::parse($validated['new_expiry'])->format('M d, Y') . '!');
    }

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

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

    public function export()
    {
        $licenses = License::all();
        
        // Add BOM for proper UTF-8 encoding in Excel
        $csv = "\xEF\xBB\xBF";
        $csv .= "ID,License Key,Name,Email,Status,Max Devices,Active Devices,Expires At,Activated At,Created At,Note\n";
        
        foreach ($licenses as $license) {
            // Prefix with tab to force Excel to treat as text
            $csv .= "\t" . $license->id . ",";
            $csv .= "\t" . $license->key . ",";
            $csv .= "\t" . ($license->name ?? '') . ",";
            $csv .= "\t" . ($license->email ?? '') . ",";
            $csv .= "\t" . ucfirst($license->status) . ",";
            $csv .= "\t" . $license->max_devices . ",";
            $csv .= "\t" . $license->current_devices . ",";
            $csv .= "\t" . ($license->expires_at ? $license->expires_at->format('M d, Y h:i A') : 'Never') . ",";
            $csv .= "\t" . ($license->activated_at ? $license->activated_at->format('M d, Y h:i A') : 'Not activated') . ",";
            $csv .= "\t" . $license->created_at->format('M d, Y h:i A') . ",";
            $csv .= "\t" . ($license->note ?? '') . "\n";
        }

        return response($csv, 200, [
            'Content-Type' => 'text/csv; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="licenses-' . date('Y-m-d') . '.csv"',
        ]);
    }
}