<?php

namespace Modules\StripeGateway\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting; // Assuming your Setting model is in App\Models
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;

class StripeConfigController extends Controller
{
    protected $settingKeys = [
        'stripe_enabled',
        'stripe_publishable_key',
        'stripe_secret_key',
        'stripe_webhook_secret',
        // Add 'stripe_mode' (live/test) if you want to manage this via settings
    ];

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

        $settings = [];
        foreach ($this->settingKeys as $key) {
            $settings[$key] = setting($key);
        }
        // Default enabled to '0' if not set
        if (is_null($settings['stripe_enabled'])) {
            $settings['stripe_enabled'] = '0';
        }
        return view('stripegateway::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([
            'stripe_enabled' => 'nullable|boolean',
            'stripe_publishable_key' => 'nullable|string|max:255',
            'stripe_secret_key' => 'nullable|string|max:255',
            'stripe_webhook_secret' => 'nullable|string|max:255',
        ]);

        try {
            // Define settings with their names, groups, and types
            $settingsData = [
                'stripe_enabled' => [
                    'value' => $request->input('stripe_enabled', '0'),
                    'name' => 'Enable Stripe Gateway',
                    'group' => 'Payment Gateways',
                    'type' => 'boolean'
                ],
                'stripe_publishable_key' => [
                    'value' => $request->input('stripe_publishable_key'),
                    'name' => 'Stripe Publishable Key',
                    'group' => 'Payment Gateways',
                    'type' => 'text'
                ],
                // Secret keys are handled separately to avoid overwriting with blank if not provided
            ];

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

            // Handle secret keys: only update if a new value is provided
            if ($request->filled('stripe_secret_key')) {
                Setting::setValue('stripe_secret_key', $request->input('stripe_secret_key'), 'Stripe Secret Key', 'Payment Gateways', 'password');
            }
            if ($request->filled('stripe_webhook_secret')) {
                Setting::setValue('stripe_webhook_secret', $request->input('stripe_webhook_secret'), 'Stripe Webhook Signing Secret', 'Payment Gateways', 'password');
            }

            // Clear cache for settings to take effect immediately
            Artisan::call('cache:clear');
            Artisan::call('config:clear');


            return redirect()->back()->with('success', 'Stripe settings updated successfully.');

        } catch (\Exception $e) {
            Log::error('Error updating Stripe settings: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to update Stripe settings. Please check the logs.');
        }
    }
}
