<?php

namespace App\Http\Controllers\Web\Bo;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\Payout;
use App\Services\PaymentGatewayConfigService;
use Illuminate\Support\Facades\Schema;
use Illuminate\Http\Request;
use Illuminate\View\View;

class FinanceController extends Controller
{
    public function __invoke(Request $request, PaymentGatewayConfigService $paymentGatewayConfigService): View
    {
        $paymentStatus = $request->string('payment_status')->toString();
        $payoutStatus = $request->string('payout_status')->toString();
        $linerId = $request->integer('liner_id');
        $hasPaymentMethodsTable = Schema::hasTable('user_payment_methods');

        $paymentsQuery = Payment::query()
            ->with(['mission:id,title,status', 'client:id,name,email', 'liner:id,name,email'])
            ->latest();

        if ($hasPaymentMethodsTable) {
            $paymentsQuery->with('paymentMethod:id,label,provider');
        }

        if ($paymentStatus !== '') {
            $paymentsQuery->where('status', $paymentStatus);
        }

        if ($linerId > 0) {
            $paymentsQuery->where('liner_id', $linerId);
        }

        $payoutsQuery = Payout::query()
            ->with(['liner:id,name,email'])
            ->latest();

        if ($hasPaymentMethodsTable) {
            $payoutsQuery->with('paymentMethod:id,label,provider');
        }

        if ($payoutStatus !== '') {
            $payoutsQuery->where('status', $payoutStatus);
        }

        if ($linerId > 0) {
            $payoutsQuery->where('liner_id', $linerId);
        }

        return view('bo.finance', [
            'paymentStatus' => $paymentStatus,
            'payoutStatus' => $payoutStatus,
            'linerId' => $linerId,
            'hasPaymentMethodsTable' => $hasPaymentMethodsTable,
            'gatewaySettings' => $paymentGatewayConfigService->forBo(),
            'payments' => $paymentsQuery->paginate(20, ['*'], 'payments_page')->withQueryString(),
            'payouts' => $payoutsQuery->paginate(20, ['*'], 'payouts_page')->withQueryString(),
            'summary' => [
                'payments_paid' => (float) Payment::where('status', 'paid')->sum('amount'),
                'payments_pending' => (float) Payment::where('status', 'pending')->sum('amount'),
                'payments_failed' => Payment::where('status', 'failed')->count(),
                'payouts_paid' => (float) Payout::where('status', 'paid')->sum('amount'),
                'payouts_pending' => (float) Payout::where('status', 'pending')->sum('amount'),
                'payouts_failed' => Payout::where('status', 'failed')->count(),
            ],
        ]);
    }
}
