<?php

namespace App\Http\Controllers;

use App\Models\SubscriptionInvoice;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceController extends Controller
{
    /**
     * Display a listing of user's invoices.
     */
    public function index()
    {
        $user = auth()->user();
        $invoices = $user->subscription
            ? $user->subscription->invoices()->latest()->paginate(20)
            : collect();

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

    /**
     * Display the specified invoice.
     */
    public function show(SubscriptionInvoice $invoice)
    {
        // Ensure user owns this invoice
        if ($invoice->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to invoice.');
        }

        return view('subscription.invoices.show', compact('invoice'));
    }

    /**
     * Download the invoice as PDF.
     */
    public function download(SubscriptionInvoice $invoice)
    {
        // Ensure user owns this invoice
        if ($invoice->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to invoice.');
        }

        $pdf = $this->generatePDF($invoice);

        return $pdf->download('invoice-' . $invoice->invoice_number . '.pdf');
    }

    /**
     * Generate PDF for invoice.
     */
    protected function generatePDF(SubscriptionInvoice $invoice)
    {
        $data = [
            'invoice' => $invoice,
            'user' => $invoice->user,
            'subscription' => $invoice->subscription,
            'plan' => $invoice->subscription->planModel,
        ];

        return Pdf::loadView('subscription.invoices.pdf', $data);
    }
}