<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\Product;
use App\Models\User;
use App\Services\InvoiceService;
use App\Services\EmailService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Admin License Controller
 * 
 * This controller handles license management in the admin panel.
 */
class LicenseController extends Controller
{
    protected EmailService $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->emailService = $emailService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $licenses = License::with(['user', 'product'])
            ->latest()
            ->paginate(10);

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $users = User::all();
        $products = Product::all();
        $selectedUserId = null;

        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_key' => 'nullable|string|unique:licenses,license_key',
            'license_type' => 'nullable|in:single,multi,developer,extended',
            'status' => 'required|in:active,inactive,suspended,expired',
            'max_domains' => 'nullable|integer|min:1',
            'license_expires_at' => 'nullable|date',
            'support_expires_at' => 'nullable|date',
            'notes' => 'nullable|string|max:1000',
            'invoice_payment_status' => 'required|in:paid,pending',
            'invoice_due_date' => 'nullable|date',
        ]);

        // Get product details
        $product = Product::find($validated['product_id']);
        if (!$product) {
            return back()->withErrors(['product_id' => 'Product not found.']);
        }

        // Inherit license type from product if not specified
        if (empty($validated['license_type'])) {
            $validated['license_type'] = $product->license_type ?? 'single';
        }

        // Set max_domains based on license type
        if (empty($validated['max_domains'])) {
            switch ($validated['license_type']) {
                case 'single':
                    $validated['max_domains'] = 1;
                    break;
                case 'multi':
                    $validated['max_domains'] = $request->input('max_domains', 5); // Default to 5 for multi
                    break;
                case 'developer':
                    $validated['max_domains'] = $request->input('max_domains', 10); // Default to 10 for developer
                    break;
                case 'extended':
                    $validated['max_domains'] = $request->input('max_domains', 20); // Default to 20 for extended
                    break;
                default:
                    $validated['max_domains'] = 1;
            }
        }

        // Set default values
        $validated['status'] = $validated['status'] ?? 'active';

        // Calculate license expiration date based on product duration
        if (empty($validated['license_expires_at'])) {
            if ($product->duration_days) {
                $validated['license_expires_at'] = now()->addDays($product->duration_days);
            }
        }

        // Calculate support expiration date based on product support days
        if (empty($validated['support_expires_at'])) {
            if ($product->support_days) {
                $validated['support_expires_at'] = now()->addDays($product->support_days);
            }
        }

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

        // Automatically create initial invoice with specified payment status
        $invoiceService = app(InvoiceService::class);
        $invoice = $invoiceService->createInitialInvoice($license, $validated['invoice_payment_status'], $validated['invoice_due_date'] ?? null);

        // Send email notifications
        try {
            // Send notification to user
            if ($license->user) {
                $this->emailService->sendLicenseCreated($license->user, [
                    'license_key' => $license->license_key,
                    'product_name' => $license->product->name ?? 'Unknown Product',
                    'expires_at' => $license->license_expires_at ? $license->license_expires_at->format('Y-m-d') : 'Never',
                ]);
            }

            // Send notification to admin
            $this->emailService->sendAdminLicenseCreated([
                'license_key' => $license->license_key,
                'product_name' => $license->product->name ?? 'Unknown Product',
                'customer_name' => $license->user ? $license->user->name : 'Unknown User',
                'customer_email' => $license->user ? $license->user->email : 'No email provided',
            ]);
        } catch (\Exception $e) {
            // Silently handle email errors to not fail license creation
        }

        return redirect()->route('admin.licenses.show', $license)
            ->with('success', 'License created successfully with automatic invoice generation.');
    }

    /**
     * Display the specified resource.
     */
    public function show(License $license)
    {
        $license->load(['user', 'product', 'domains', 'logs']);

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

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, License $license)
    {
        // Debug: Log the request data
        \Log::info('License update request data:', $request->all());
        
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'product_id' => 'required|exists:products,id',
            // 'license_key' => 'required|string|unique:licenses,license_key,' . $license->id, // Removed - license key should not be editable
            'license_type' => 'nullable|in:single,multi,developer,extended',
            'status' => 'required|in:active,inactive,suspended,expired',
            'max_domains' => 'nullable|integer|min:1',
            'expires_at' => 'nullable|date',
            'notes' => 'nullable|string|max:1000',
        ]);


        // 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\Carbon::parse($validated['expires_at'])->format('Y-m-d H:i:s')
                : null;
            unset($validated['expires_at']);
        }

        // Get product details for inheritance
        $product = Product::find($validated['product_id']);
        if (!$product) {
            return back()->withErrors(['product_id' => 'Product not found.']);
        }

        // Inherit license type from product if not specified
        if (empty($validated['license_type'])) {
            $validated['license_type'] = $product->license_type ?? 'single';
        }

        // Set max_domains based on license type
        if (empty($validated['max_domains'])) {
            switch ($validated['license_type']) {
                case 'single':
                    $validated['max_domains'] = 1;
                    break;
                case 'multi':
                    $validated['max_domains'] = 5;
                    break;
                case 'developer':
                    $validated['max_domains'] = 10;
                    break;
                case 'extended':
                    $validated['max_domains'] = 20;
                    break;
                default:
                    $validated['max_domains'] = 1;
            }
        }

        // Set default values
        $validated['max_domains'] = $validated['max_domains'] ?? 1;

        $license->update($validated);

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

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

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

    /**
     * Toggle license status
     */
    public function toggle(License $license)
    {
        $license->update([
            'status' => $license->status === 'active' ? 'inactive' : 'active'
        ]);

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

    /**
     * Export licenses to CSV
     */
    public function export()
    {
        $licenses = License::with(['user', 'product'])->get();

        $filename = 'licenses_' . date('Y-m-d_H-i-s') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function() use ($licenses) {
            $file = fopen('php://output', 'w');
            
            // CSV Headers
            fputcsv($file, [
                'ID',
                'License Key',
                'User',
                'Product',
                'Status',
                'Max Domains',
                'Expires At',
                'Created At'
            ]);

            // CSV Data
            foreach ($licenses as $license) {
                fputcsv($file, [
                    $license->id,
                    $license->license_key,
                    $license->user->name ?? 'N/A',
                    $license->product->name ?? 'N/A',
                    $license->status,
                    $license->max_domains,
                    $license->expires_at,
                    $license->created_at
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}