<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\User;
use App\Services\InvoiceService;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    protected $invoiceService;

    public function __construct(InvoiceService $invoiceService)
    {
        $this->invoiceService = $invoiceService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Invoice::with(['user', 'product', 'license']);

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by date range
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $invoices = $query->latest()->paginate(10);
        $stats = $this->invoiceService->getInvoiceStats();

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $users = User::select('id', 'name', 'email')->get();
        return view('admin.invoices.create', compact('users'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $isCustomInvoice = $request->license_id === 'custom';

        $rules = [
            'user_id' => 'required|exists:users,id',
            'license_id' => $isCustomInvoice ? 'nullable' : 'required|exists:licenses,id',
            'type' => 'required|in:initial,renewal,upgrade,custom',
            'amount' => 'required|numeric|min:0',
            'currency' => 'required|string|size:3',
            'status' => 'required|in:pending,paid,overdue,cancelled',
            'due_date' => 'nullable|date|after:today',
            'paid_at' => 'nullable|date|required_if:status,paid',
            'notes' => 'nullable|string|max:1000',
        ];

        // Add validation for custom invoice fields
        if ($isCustomInvoice) {
            $rules['custom_invoice_type'] = 'required|in:one_time,monthly,quarterly,semi_annual,annual,custom_recurring';
            $rules['custom_product_name'] = 'required|string|max:255';
            $rules['expiration_date'] = 'nullable|date|after:today';
        }

        $request->validate($rules);

        $license = null;
        $productId = null;

        if (!$isCustomInvoice) {
            $license = \App\Models\License::find($request->license_id);
            $productId = $license->product_id;
        }

        $invoice = Invoice::create([
            'user_id' => $request->user_id,
            'license_id' => $isCustomInvoice ? null : $request->license_id,
            'product_id' => $productId,
            'type' => $request->type,
            'amount' => $request->amount,
            'currency' => $request->currency,
            'status' => $request->status,
            'due_date' => $request->due_date,
            'paid_at' => $request->status === 'paid' ? ($request->paid_at ?? now()) : null,
            'notes' => $request->notes,
            'metadata' => $isCustomInvoice ? [
                'custom_invoice' => true,
                'custom_invoice_type' => $request->custom_invoice_type,
                'custom_product_name' => $request->custom_product_name,
                'expiration_date' => $request->custom_invoice_type !== 'one_time' ? $request->expiration_date : null,
            ] : null,
        ]);

        return redirect()->route('admin.invoices.show', $invoice)
                        ->with('success', 'Invoice created successfully');
    }

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

    /**
     * Mark invoice as paid
     */
    public function markAsPaid(Invoice $invoice)
    {
        $this->invoiceService->payInvoice($invoice);

        return redirect()->back()->with('success', 'Invoice marked as paid successfully');
    }

    /**
     * Cancel invoice
     */
    public function cancel(Invoice $invoice)
    {
        $this->invoiceService->cancelInvoice($invoice);

        return redirect()->back()->with('success', 'Invoice cancelled successfully');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Invoice $invoice)
    {
        $users = User::select('id', 'name', 'email')->get();
        $invoice->load(['user', 'license.product']);
        return view('admin.invoices.edit', compact('invoice', 'users'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Invoice $invoice)
    {
        $isCustomInvoice = $request->license_id === 'custom';

        $rules = [
            'user_id' => 'required|exists:users,id',
            'license_id' => $isCustomInvoice ? 'nullable' : 'required|exists:licenses,id',
            'type' => 'required|in:initial,renewal,upgrade,custom',
            'amount' => 'required|numeric|min:0',
            'currency' => 'required|string|size:3',
            'status' => 'required|in:pending,paid,overdue,cancelled',
            'due_date' => 'nullable|date',
            'paid_at' => 'nullable|date|required_if:status,paid',
            'notes' => 'nullable|string|max:1000',
        ];

        // Add validation for custom invoice fields
        if ($isCustomInvoice) {
            $rules['custom_invoice_type'] = 'required|in:one_time,monthly,quarterly,semi_annual,annual,custom_recurring';
            $rules['custom_product_name'] = 'required|string|max:255';
            $rules['expiration_date'] = 'nullable|date';
        }

        $request->validate($rules);

        $license = null;
        $productId = null;

        if (!$isCustomInvoice) {
            $license = \App\Models\License::find($request->license_id);
            $productId = $license->product_id;
        }

        $invoice->update([
            'user_id' => $request->user_id,
            'license_id' => $isCustomInvoice ? null : $request->license_id,
            'product_id' => $productId,
            'type' => $request->type,
            'amount' => $request->amount,
            'currency' => $request->currency,
            'status' => $request->status,
            'due_date' => $request->due_date,
            'paid_at' => $request->status === 'paid' ? ($request->paid_at ?? now()) : null,
            'notes' => $request->notes,
            'metadata' => $isCustomInvoice ? [
                'custom_invoice' => true,
                'custom_invoice_type' => $request->custom_invoice_type,
                'custom_product_name' => $request->custom_product_name,
                'expiration_date' => $request->custom_invoice_type !== 'one_time' ? $request->expiration_date : null,
            ] : null,
        ]);

        return redirect()->route('admin.invoices.show', $invoice)
                        ->with('success', 'Invoice updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Invoice $invoice)
    {
        // Check if invoice can be deleted (not paid)
        if ($invoice->status === 'paid') {
            return redirect()->back()->with('error', 'Cannot delete a paid invoice');
        }

        $invoice->delete();

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

    /**
     * Get user licenses for API
     */
    public function getUserLicenses(User $user)
    {
        $licenses = $user->licenses()->with('product')->get()->map(function ($license) {
            return [
                'id' => $license->id,
                'product' => [
                    'name' => $license->product->name ?? 'N/A',
                ],
                'license_type' => $license->license_type,
                'status' => $license->status,
                'license_key' => $license->license_key,
                'expires_at' => $license->expires_at?->format('Y-m-d'),
            ];
        });

        return response()->json($licenses);
    }
}
