@extends('layouts.admin') {{-- Or your main admin layout --}}

@section('title', 'WebPilotAI Module Settings')
@section('header_title', 'WebPilotAI Module Settings')

@section('content')
<div class="p-6">
    <form action="{{ route('admin.webpilotai.settings.update') }}" method="POST">
        @csrf
        @method('PUT')
        {{-- Main page card --}}
        <div class="bg-white dark:bg-gray-900 shadow-xl rounded-xl p-6 md:p-8">
            <h2 class="text-2xl font-semibold text-gray-800 dark:text-gray-100 mb-1">Module Configuration</h2>
            <p class="text-sm text-gray-500 dark:text-gray-400 mb-6">Manage settings for the WebPilotAI module. API keys and other sensitive information are stored securely.</p>

            @include('webpilotai::admin.partials._session_messages')
            @include('webpilotai::admin.partials._validation_errors')

            @if(empty($settingsSchema))
                <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4" role="alert">
                    <p class="font-bold">Warning</p>
                    <p>No settings schema found. Please ensure your module.json is correctly configured.</p>
                </div>
            @else
                @php
                    $groupedSettings = collect($settingsSchema)->groupBy('group');
                @endphp

                @foreach($groupedSettings as $groupName => $settingsInGroup)
                    {{-- Settings Group Card --}}
                    <div class="bg-gray-50 dark:bg-gray-800/60 ring-1 ring-gray-200 dark:ring-gray-700/50 shadow-sm rounded-lg mb-10">
                        <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                            {{ $groupName }}
                        </h3>
                        @php
                            $itemCount = count($settingsInGroup);
                            $groupContentClasses = 'p-6';
                            if ($itemCount === 2) {
                                $groupContentClasses .= ' grid grid-cols-1 md:grid-cols-2 gap-6';
                            } else {
                                $groupContentClasses .= ' space-y-6'; // Default for 1 or 3+ items
                            }
                        @endphp
                        <div class="{{ $groupContentClasses }}">
                            @foreach($settingsInGroup as $setting)
                            @php
                                $settingKey = 'webpilotai.' . $setting['key'];
                                $currentValueForField = $settingsData[$settingKey] ?? $setting['default'] ?? null;
                                $inputId = 'setting_' . Str::slug($setting['key'], '_');
                                $isDisabled = false;

                                if (isset($setting['depends_on']) && is_array($setting['depends_on'])) {
                                    foreach ($setting['depends_on'] as $dependencySimpleKey => $expectedValueFromSchema) {
                                        // $dependencySimpleKey is like 'enable_feature_x'
                                        // $expectedValueFromSchema is like true, 'active', '1'

                                        $dependencyFullKey = 'webpilotai.' . $dependencySimpleKey;

                                        // Find the schema for the dependency to get its default if not in $settingsData
                                        $dependencySettingSchema = null;
                                        foreach ($settingsSchema as $s_item) { // Iterate to find the dependency's schema
                                            if ($s_item['key'] === $dependencySimpleKey) {
                                                $dependencySettingSchema = $s_item;
                                                break;
                                            }
                                        }
                                        // The default value for the *dependency* field
                                        $dependencyDefaultValue = $dependencySettingSchema['default'] ?? null;
                                        // The actual current value of the *dependency* field (already cast by controller)
                                        $actualDependencyValue = $settingsData[$dependencyFullKey] ?? $dependencyDefaultValue;

                                        // Normalize $expectedValueFromSchema for comparison against $actualDependencyValue
                                        $normalizedExpectedValue = $expectedValueFromSchema;
                                        if (is_bool($actualDependencyValue)) {
                                            if (is_string($expectedValueFromSchema)) {
                                                $testVal = strtolower($expectedValueFromSchema);
                                                if ($testVal === 'true' || $testVal === '1') {
                                                    $normalizedExpectedValue = true;
                                                } elseif ($testVal === 'false' || $testVal === '0') {
                                                    $normalizedExpectedValue = false;
                                                }
                                            }
                                        } else {
                                            $actualDependencyValue = (string) $actualDependencyValue;
                                            $normalizedExpectedValue = (string) $normalizedExpectedValue;
                                        }

                                        if ($actualDependencyValue != $normalizedExpectedValue) {
                                            $isDisabled = true;
                                            break;
                                        }
                                    }
                                }
                            @endphp
                            {{-- Individual Setting Item --}}
                            <div class="setting-item-wrapper {{ $isDisabled ? 'opacity-60' : '' }}">
                                @if($setting['type'] === 'boolean' || $setting['type'] === 'checkbox')
                                    <div class="relative flex items-start">
                                        <div class="flex h-5 items-center">
                                            <input type="hidden" name="{{ $settingKey }}" value="0">
                                            <input id="{{ $inputId }}" name="{{ $settingKey }}" type="checkbox" value="1"
                                                   {{ old($settingKey, $currentValueForField) == '1' || old($settingKey, $currentValueForField) === true ? 'checked' : '' }}
                                                   {{ $isDisabled ? 'disabled' : '' }}
                                                   class="h-4 w-4 rounded border-gray-300 bg-gray-100 dark:border-gray-600 dark:bg-gray-700 text-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 dark:ring-offset-gray-800 focus:ring-2">
                                        </div>
                                        <div class="ml-3 text-sm">
                                            <label for="{{ $inputId }}" class="font-medium text-gray-700 dark:text-gray-200">
                                                {{ $setting['label'] ?? Str::title(str_replace('_', ' ', $setting['key'])) }}
                                                @if(Str::contains(json_encode($setting['rules'] ?? []), 'required')) <span class="text-red-500">*</span> @endif
                                            </label>
                                            @if(isset($setting['description']))
                                                <p class="text-xs text-gray-500 dark:text-gray-400">{{ $setting['description'] }}</p>
                                            @endif
                                        </div>
                                    </div>
                                @else
                                    <label for="{{ $inputId }}" class="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1.5">
                                        {{ $setting['label'] ?? Str::title(str_replace('_', ' ', $setting['key'])) }}
                                        @if(Str::contains(json_encode($setting['rules'] ?? []), 'required')) <span class="text-red-500">*</span> @endif
                                    </label>

                                    @if($setting['type'] === 'text' || $setting['type'] === 'number' || $setting['type'] === 'password')
                                        <input type="{{ $setting['type'] }}" name="{{ $settingKey }}" id="{{ $inputId }}"
                                               value="{{ old($settingKey, $currentValueForField) }}"
                                               {{ $isDisabled ? 'disabled' : '' }}
                                               class="block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700/80 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm text-gray-900 dark:text-gray-100 dark:placeholder-gray-400">
                                    @elseif($setting['type'] === 'textarea')
                                        <textarea name="{{ $settingKey }}" id="{{ $inputId }}" rows="3"
                                                  {{ $isDisabled ? 'disabled' : '' }}
                                                  class="block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700/80 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm text-gray-900 dark:text-gray-100 dark:placeholder-gray-400">{{ old($settingKey, $currentValueForField) }}</textarea>
                                    @elseif($setting['type'] === 'select' && isset($setting['options']))
                                        <select name="{{ $settingKey }}" id="{{ $inputId }}" {{ $isDisabled ? 'disabled' : '' }}
                                                class="block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700/80 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm text-gray-900 dark:text-gray-100">
                                            @foreach($setting['options'] as $value => $label)
                                                <option value="{{ $value }}" {{ old($settingKey, (string)$currentValueForField) == (string)$value ? 'selected' : '' }}>{{ $label }}</option>
                                            @endforeach
                                        </select>
                                    @endif

                                    @if(isset($setting['description']))
                                        <p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">{{ $setting['description'] }}</p>
                                    @endif
                                @endif
                                @error($settingKey)
                                    <p class="mt-1.5 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                                @enderror
                            </div>
                            @endforeach
                        </div>
                    </div>
                @endforeach
            @endif

            <div class="mt-10 pt-6 border-t border-gray-200 dark:border-gray-700">
                <div class="flex justify-end">
                    <button type="submit" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out">
                        <i class="fas fa-save mr-2"></i> Save Settings
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Logic to enable/disable dependent fields based on checkbox/select changes
    const settingsSchema = @json($settingsSchema ?? []);
    settingsSchema.forEach(setting => {
        if (setting.depends_on) {
            Object.keys(setting.depends_on).forEach(dependencyKey => {
                const dependencyFullKey = 'webpilotai.' + dependencyKey;
                const dependentFieldInputId = 'setting_' + setting.key.replace(/\./g, '_');
                const dependentField = document.getElementById(dependentFieldInputId);
                const controllerFieldId = 'setting_' + dependencyKey.replace(/\./g, '_');
                const controllerField = document.getElementById(controllerFieldId);

                if (controllerField && dependentField) {
                    // Function to determine the actual value of a controller field
                    const getControllerValue = (field) => {
                        if (field.type === 'checkbox') {
                            return field.checked; // boolean
                        }
                        // Add other types like select, number if needed for more complex scenarios
                        return field.value; // string for select, text, number inputs
                    };

                    const updateDependentState = () => {
                        let enable = true;
                        // The 'setting' here is the dependent setting.
                        // We need to check all its dependencies.
                        Object.entries(setting.depends_on).forEach(([depKey, depValueFromSchema]) => {
                            const currentControllerField = document.getElementById('setting_' + depKey.replace(/\./g, '_'));
                            if (currentControllerField) {
                                let actualControllerValue = getControllerValue(currentControllerField);
                                let expectedSchemaValue = depValueFromSchema; // Value from module.json

                                // Normalize schema value for comparison, especially for booleans
                                if (typeof actualControllerValue === 'boolean') {
                                    if (String(expectedSchemaValue).toLowerCase() === 'true' || String(expectedSchemaValue) === '1') {
                                        expectedSchemaValue = true;
                                    } else if (String(expectedSchemaValue).toLowerCase() === 'false' || String(expectedSchemaValue) === '0') {
                                        expectedSchemaValue = false;
                                    }
                                    // If expectedSchemaValue was already a boolean, it remains unchanged.
                                } else { // For string comparisons (e.g., select values, text inputs)
                                    actualControllerValue = String(actualControllerValue);
                                    expectedSchemaValue = String(expectedSchemaValue);
                                }

                                if (actualControllerValue != expectedSchemaValue) {
                                    enable = false;
                                }
                            }
                        });
                        dependentField.disabled = !enable;
                        const parentDiv = dependentField.closest('.setting-item-wrapper'); // Changed selector
                        if (parentDiv) {
                            parentDiv.style.opacity = enable ? '1' : '0.6'; // Adjusted opacity
                        }
                    };
                    controllerField.addEventListener('change', updateDependentState);
                    updateDependentState(); // Call on load to set initial state based on JS logic
                }
            });
        }
    });
});
</script>
@endpush