<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Inertia\Inertia;
use Illuminate\Support\Facades\Redirect;

class AdminPaymentSettingsController extends Controller
{
    /**
     * Display the payment settings form.
     */
    public function edit()
    {
        $settings = Setting::firstOrCreate([]); // Get the first settings record, or create one if it doesn't exist
        $paymentGateways = $settings->payment_gateways ?? [];

        return Inertia::render('Admin/PaymentSettings/Edit', [
            'paymentGateways' => $paymentGateways,
        ]);
    }

    /**
     * Update the payment settings.
     */
    public function update(Request $request)
    {
        $request->validate([
            'paystack_public_key' => 'nullable|string|max:255',
            'paystack_secret_key' => 'nullable|string|max:255',
            'paystack_merchant_email' => 'nullable|email|max:255',
            'paystack_payment_url' => 'nullable|url|max:255', // New field
            'paypal_mode' => 'nullable|in:sandbox,live',
            'paypal_sandbox_client_id' => 'nullable|string|max:255',
            'paypal_sandbox_client_secret' => 'nullable|string|max:255',
            'paypal_live_client_id' => 'nullable|string|max:255',
            'paypal_live_client_secret' => 'nullable|string|max:255',
            'paypal_currency' => 'nullable|string|max:10',
        ]);

        $settings = Setting::firstOrCreate([]);

        $settings->payment_gateways = [
            'paystack' => [
                'public_key' => $request->paystack_public_key,
                'secret_key' => $request->paystack_secret_key,
                'merchant_email' => $request->paystack_merchant_email,
                'payment_url' => $request->paystack_payment_url, // New field
            ],
            'paypal' => [
                'mode' => $request->paypal_mode,
                'sandbox_client_id' => $request->paypal_sandbox_client_id,
                'sandbox_client_secret' => $request->paypal_sandbox_client_secret,
                'live_client_id' => $request->paypal_live_client_id,
                'live_client_secret' => $request->paypal_live_client_secret,
                'currency' => $request->paypal_currency,
            ],
        ];

        $settings->save();

        return Redirect::route('admin.payment-settings.edit')->with('success', 'Payment settings updated successfully.');
    }
}