<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index()
    {
        $invoices = Invoice::where('user_id', auth()->id())
            ->with('package')->latest()->paginate(15);
        return view('user.invoices.index', compact('invoices'));
    }

    public function show(Invoice $invoice)
    {
        if ($invoice->user_id !== auth()->id()) abort(403);
        $invoice->load('package', 'payments');
        return view('user.invoices.show', compact('invoice'));
    }

    public function pay(Request $request, Invoice $invoice)
    {
        if ($invoice->user_id !== auth()->id()) abort(403);
        if ($invoice->isPaid()) {
            return back()->with('info', 'Invoice already paid.');
        }

        $gateway = strtolower((string) $request->get('gateway', 'paypal'));
        if (!gateway_enabled($gateway)) {
            return back()->with('error', ucfirst($gateway) . ' gateway is disabled by admin.');
        }
        return match ($gateway) {
            'tap' => redirect()->route('tap.process', $invoice),
            default => redirect()->route('paypal.process', $invoice),
        };
    }
}
