<?php

namespace Modules\PaystackGateway\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;

class PaystackConfigController extends Controller
{
    protected $settingKeys = [
        'paystack_enabled',
        'paystack_public_key',
        'paystack_secret_key',
        'paystack_mode', // 'test' or 'live' (Paystack typically uses test/live keys rather than a mode switch in API calls)
        // 'paystack_payment_url', // Often fixed: https://api.paystack.co
        // 'paystack_merchant_email', // Sometimes required
    ];

    public function edit()
    {
        if (!function_exists('setting')) {
            // This check is good, but ideally, the setting() helper should always be available.
            // If it's from a package, ensure it's loaded globally or provided via a service provider.
            return redirect()->route('admin.dashboard')->with('error', 'Settings helper function not found.');
        }

        $settings = [];
        foreach ($this->settingKeys as $key) {
            $settings[$key] = setting($key);
        }
        $settings['paystack_mode'] = $settings['paystack_mode'] ?? 'test'; // Default to test
        // Default enabled to '0' if not set
        if (is_null($settings['paystack_enabled'])) {
            $settings['paystack_enabled'] = '0';
        }

        return view('paystackgateway::admin.config', compact('settings'));
    }

    public function update(Request $request)
    {
        if (!function_exists('setting')) {
            return redirect()->route('admin.dashboard')->with('error', 'Settings helper function not found.');
        }

        $validated = $request->validate([
            'paystack_enabled' => 'nullable|boolean',
            'paystack_public_key' => 'nullable|string|max:255',
            'paystack_secret_key' => 'nullable|string|max:255',
            'paystack_mode' => 'required|in:test,live',
        ]);

        try {
            // Define settings with their names, groups, and types
            $settingsData = [
                'paystack_enabled' => [
                    'value' => $request->input('paystack_enabled', '0'),
                    'name' => 'Enable Paystack Gateway',
                    'group' => 'Payment Gateways',
                    'type' => 'boolean'
                ],
                'paystack_mode' => [
                    'value' => $request->input('paystack_mode', 'test'),
                    'name' => 'Paystack Mode',
                    'group' => 'Payment Gateways',
                    'type' => 'select'
                ],
                'paystack_public_key' => [
                    'value' => $request->input('paystack_public_key'),
                    'name' => 'Paystack Public Key',
                    'group' => 'Payment Gateways',
                    'type' => 'text'
                ],
                // Secret key is handled separately
            ];

            foreach ($settingsData as $key => $data) {
                Setting::setValue($key, $data['value'], $data['name'], $data['group'], $data['type']);
            }

            // Handle secret key: only update if a new value is provided
            if ($request->filled('paystack_secret_key')) {
                Setting::setValue('paystack_secret_key', $request->input('paystack_secret_key'), 'Paystack Secret Key', 'Payment Gateways', 'password');
            }

            Artisan::call('cache:clear');
            Artisan::call('config:clear');
            return redirect()->back()->with('success', 'Paystack settings updated successfully.');
        } catch (\Exception $e) {
            Log::error('Error updating Paystack settings: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to update Paystack settings. Please check the logs.');
        }
    }
}