<?php

namespace Modules\MedRegistry\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedRegistry\Entities\MedregModuleInstance;

/**
 * P1-T5 — per-instance settings screen. The form is auto-generated from the
 * module's settings_schema json (generic renderer: boolean / select / text /
 * number, with labels + defaults) and saved into module_instance.settings.
 */
class InstanceSettingsController extends MedRegistryBaseController
{
    public function edit($id)
    {
        $this->guard('medreg.settings.manage');
        $this->guardSubscription();

        $instance = MedregModuleInstance::with('module')
            ->where('business_id', $this->businessId())
            ->findOrFail($id);

        $schema = $this->schemaFor($instance);

        return view('medregistry::instances.settings', [
            'instance' => $instance,
            'module'   => $instance->module,
            'schema'   => $schema,
            'values'   => (array) ($instance->settings ?: []),
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->guard('medreg.settings.manage');
        $this->guardSubscription();

        $instance = MedregModuleInstance::with('module')
            ->where('business_id', $this->businessId())
            ->findOrFail($id);

        $schema = $this->schemaFor($instance);

        $settings = (array) ($instance->settings ?: []);
        $errors = [];

        foreach ($schema as $key => $field) {
            $type = $field['type'] ?? 'text';

            switch ($type) {
                case 'boolean':
                    $settings[$key] = $request->boolean('settings.' . $key);
                    break;

                case 'select':
                    $value = $request->input('settings.' . $key);
                    $options = (array) ($field['options'] ?? []);
                    if (! array_key_exists((string) $value, $options)) {
                        $value = $field['default'] ?? array_key_first($options);
                    }
                    $settings[$key] = $value;
                    break;

                case 'number':
                    $value = $request->input('settings.' . $key);
                    if ($value === null || $value === '') {
                        $settings[$key] = $field['default'] ?? null;
                    } elseif (! is_numeric($value)) {
                        $errors[] = $key;
                    } else {
                        $settings[$key] = $value + 0; // int or float
                    }
                    break;

                case 'text':
                default:
                    $value = $request->input('settings.' . $key);
                    $settings[$key] = $value !== null ? (string) $value : ($field['default'] ?? null);
                    break;
            }
        }

        if (! empty($errors)) {
            return redirect()->back()
                ->withInput()
                ->with('status', $this->fail(__('medregistry::lang.invalid_settings', ['fields' => implode(', ', $errors)])));
        }

        $instance->settings = $settings;
        $instance->save();

        return redirect()
            ->route('medreg.instances.settings.edit', $instance->id)
            ->with('status', $this->ok(__('medregistry::lang.settings_saved')));
    }

    /** The module's settings_schema, keyed field => definition. */
    protected function schemaFor(MedregModuleInstance $instance): array
    {
        $schema = $instance->module ? $instance->module->settings_schema : null;

        return is_array($schema) ? $schema : [];
    }
}
