<?php

namespace Modules\PaypalGateway\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 PaypalConfigController extends Controller
{
    protected $settingKeys = [
        'paypal_enabled',
        'paypal_client_id',
        'paypal_client_secret',
        'paypal_webhook_id', // Webhook ID from PayPal dashboard for verification
        'paypal_mode', // 'sandbox' or 'live'
    ];

    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 mode to sandbox if not set
        $settings['paypal_mode'] = $settings['paypal_mode'] ?? 'sandbox';
        // Default enabled to '0' if not set
        if (is_null($settings['paypal_enabled'])) {
            $settings['paypal_enabled'] = '0';
        }


        return view('paypalgateway::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([
            'paypal_enabled' => 'nullable|boolean',
            'paypal_client_id' => 'nullable|string|max:255',
            'paypal_client_secret' => 'nullable|string|max:255',
            'paypal_webhook_id' => 'nullable|string|max:255',
            'paypal_mode' => 'required|in:sandbox,live',
        ]);

        try {
            // Define settings with their names, groups, and types
            $settingsData = [
                'paypal_enabled' => [
                    'value' => $request->input('paypal_enabled', '0'),
                    'name' => 'Enable PayPal Gateway',
                    'group' => 'Payment Gateways',
                    'type' => 'boolean'
                ],
                'paypal_mode' => [
                    'value' => $request->input('paypal_mode', 'sandbox'),
                    'name' => 'PayPal Mode',
                    'group' => 'Payment Gateways',
                    'type' => 'select'
                ],
                'paypal_client_id' => [
                    'value' => $request->input('paypal_client_id'),
                    'name' => 'PayPal Client ID',
                    'group' => 'Payment Gateways',
                    'type' => 'text'
                ],
                'paypal_webhook_id' => [
                    'value' => $request->input('paypal_webhook_id'),
                    'name' => 'PayPal Webhook ID',
                    'group' => 'Payment Gateways',
                    'type' => 'text'
                ],
            ];

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

            // Handle client secret separately: only update if a new value is provided
            if ($request->filled('paypal_client_secret')) {
                Setting::setValue('paypal_client_secret', $request->input('paypal_client_secret'), 'PayPal Client Secret', 'Payment Gateways', 'password');
            }

            Artisan::call('cache:clear');
            Artisan::call('config:clear');

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

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