<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\UpdatePaymentSettingsRequest;
use App\Services\Audit\ActivityLogger;
use App\Services\Settings\PaymentSettingsService;
use App\Services\Tenancy\CurrentBusiness;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class PaymentSettingsController extends Controller
{
    public function edit(CurrentBusiness $currentBusiness, PaymentSettingsService $paymentSettings): View
    {
        $business = $currentBusiness->get() ?? abort(403);

        return view('admin.settings.payments', [
            'settings' => $paymentSettings->get($business),
            'futureGateways' => $paymentSettings->futureGateways(),
        ]);
    }

    public function update(UpdatePaymentSettingsRequest $request, CurrentBusiness $currentBusiness, PaymentSettingsService $paymentSettings, ActivityLogger $logger): RedirectResponse
    {
        $business = $currentBusiness->get() ?? abort(403);
        $paymentSettings->save($business, $request->payload());
        $logger->log($request->user(), 'settings.payment.updated', 'Updated payment gateway settings.', $business, [
            'sections' => array_keys($request->payload()),
        ], $request, $business);

        return redirect()
            ->route('admin.settings.payments')
            ->with('status', 'Payment settings saved securely.');
    }

    public function test(string $gateway, UpdatePaymentSettingsRequest $request, CurrentBusiness $currentBusiness, PaymentSettingsService $paymentSettings, ActivityLogger $logger): RedirectResponse
    {
        $business = $currentBusiness->get() ?? abort(403);
        $paymentSettings->save($business, $request->payload());
        $logger->log($request->user(), 'settings.payment.test_requested', "Requested {$gateway} payment gateway test placeholder.", $business, [
            'gateway' => $gateway,
        ], $request, $business);

        return redirect()
            ->route('admin.settings.payments')
            ->with('status', $paymentSettings->testPlaceholder($gateway));
    }
}
