<?php

namespace Modules\WebPilotAI\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class ModuleSettingsController extends Controller
{
    private string $moduleName = 'WebPilotAI';
    private string $moduleAlias = 'webpilotai';

    /**
     * Display the module settings page.
     */
    public function index()
    {
        $settingsConfig = $this->getSettingsConfig();
        $currentSettings = [];

        foreach ($settingsConfig as $setting) {
            // Fetch current value from the published config file
            $currentSettings[$setting['key']] = config($this->moduleAlias . '.' . $setting['key'], $setting['default'] ?? null);
        }

        return view('webpilotai::admin.modulesettings.index', compact('settingsConfig', 'currentSettings'));
    }

    /**
     * Store the updated module settings.
     */
    public function store(Request $request): RedirectResponse
    {
        $settingsConfig = $this->getSettingsConfig();
        $rules = [];
        $newData = [];

        foreach ($settingsConfig as $setting) {
            $key = $setting['key'];
            // Basic validation based on type
            switch ($setting['type']) {
                case 'boolean':
                    $rules[$key] = 'nullable|boolean';
                    $newData[$key] = $request->has($key); // Checkbox handling
                    break;
                case 'number':
                    $rules[$key] = 'nullable|numeric';
                    $newData[$key] = $request->input($key);
                    break;
                case 'text':
                case 'password':
                case 'textarea':
                case 'select':
                default:
                    $rules[$key] = 'nullable|string';
                    $newData[$key] = $request->input($key);
                    break;
            }
        }

        $request->validate($rules); // Use validated data if further processing needed

        // Path to the published config file
        $publishedConfigPath = config_path($this->moduleAlias . '.php');

        if (!File::exists($publishedConfigPath)) {
            // Attempt to publish if not exists (might require user to run command manually first)
            // Artisan::call('vendor:publish', ['--provider' => "Modules\\{$this->moduleName}\\Providers\\{$this->moduleName}ServiceProvider", '--tag' => "config"]);
            return redirect()->back()->withErrors(['msg' => 'Module configuration file not found. Please publish the module assets.']);
        }

        // Read existing published config
        $existingConfig = require $publishedConfigPath;

        // Merge new data with existing config, preserving other keys
        $updatedConfig = array_merge($existingConfig, $newData);

        // Write back to the published config file
        $phpCode = "<?php\n\nreturn " . var_export($updatedConfig, true) . ";\n";

        try {
            File::put($publishedConfigPath, $phpCode);
            // Clear config cache to apply changes
            Artisan::call('config:clear');
            // Optionally, re-cache if in production: Artisan::call('config:cache');
        } catch (\Exception $e) {
            Log::error("Failed to write WebPilotAI settings to config file: " . $e->getMessage());
            return redirect()->back()->withErrors(['msg' => 'Failed to save settings. Check file permissions or logs.']);
        }

        return redirect()->route('admin.webpilotai.settings.index')->with('success', $this->moduleName . ' settings updated successfully!');
    }

    private function getSettingsConfig(): array
    {
        $moduleJsonPath = module_path($this->moduleName, 'module.json');
        if (File::exists($moduleJsonPath)) {
            $moduleConfig = json_decode(File::get($moduleJsonPath), true);
            return $moduleConfig['settings'] ?? [];
        }
        return [];
    }
}