<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

final class TransactionController extends Controller
{
    public function index(Request $request): Response
    {
        $query = PaymentTransaction::query()
            ->with(['user:id,name,email', 'invoice:id,number']);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search): void {
                $q->where('gateway_transaction_id', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhereHas('user', function ($uq) use ($search): void {
                        $uq->where('name', 'like', "%{$search}%")
                            ->orWhere('email', 'like', "%{$search}%");
                    });
            });
        }

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

        if ($gateway = $request->input('gateway')) {
            $query->where('gateway', $gateway);
        }

        $transactions = $query->latest()->paginate(25)->withQueryString();

        return Inertia::render('Admin/Transactions/Index', [
            'transactions' => $transactions,
            'filters' => [
                'search' => $request->input('search', ''),
                'status' => $request->input('status', ''),
                'gateway' => $request->input('gateway', ''),
            ],
        ]);
    }

    public function show(PaymentTransaction $transaction): Response
    {
        $transaction->load([
            'user:id,name,email,status',
            'invoice:id,number,total,status,currency',
            'subscription:id,type,stripe_id,stripe_status',
        ]);

        return Inertia::render('Admin/Transactions/Show', [
            'transaction' => $transaction,
        ]);
    }
}
