<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PaymentGateway;
use App\Services\AdminActivityLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class GatewayController extends Controller
{
    public function index(): View
    {
        $defaults = [
            ['code' => 'razorpay', 'name' => 'Razorpay'],
            ['code' => 'stripe', 'name' => 'Stripe'],
            ['code' => 'paypal', 'name' => 'PayPal'],
            ['code' => 'cashfree', 'name' => 'Cashfree'],
            ['code' => 'phonepe', 'name' => 'PhonePe'],
            ['code' => 'manual', 'name' => 'Manual UPI'],
        ];

        foreach ($defaults as $gateway) {
            PaymentGateway::query()->firstOrCreate(
                ['code' => $gateway['code']],
                ['name' => $gateway['name'], 'is_enabled' => $gateway['code'] === 'manual']
            );
        }

        return view('admin.payments-gateways', [
            'gateways' => PaymentGateway::query()->orderBy('name')->get(),
        ]);
    }

    public function update(Request $request, PaymentGateway $gateway, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'config_json' => ['nullable', 'string'],
        ]);

        $payload = $validated['config_json'] ? json_decode($validated['config_json'], true) : null;
        if ($validated['config_json'] && $payload === null) {
            return back()->withErrors(['config_json' => 'Invalid JSON']);
        }

        $gateway->name = $validated['name'];
        $gateway->config_json = $payload;
        $gateway->save();

        $logger->log('gateway.update', PaymentGateway::class, $gateway->id);

        return back()->with('status', 'Gateway updated.');
    }

    public function toggle(PaymentGateway $gateway, AdminActivityLogger $logger): RedirectResponse
    {
        $gateway->is_enabled = ! $gateway->is_enabled;
        $gateway->save();

        $logger->log('gateway.toggle', PaymentGateway::class, $gateway->id, ['enabled' => $gateway->is_enabled]);

        return back()->with('status', 'Gateway status updated.');
    }
}
