<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\Settings\ModuleSettingsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Modules\SystemCore\App\Services\SystemCoreSettings;

class SettingsController extends Controller
{
    protected SystemCoreSettings $settings;

    protected ModuleSettingsService $settingsService;

    public function __construct(SystemCoreSettings $settings, ModuleSettingsService $settingsService)
    {
        $this->settings = $settings;
        $this->settingsService = $settingsService;
    }

    /**
     * Display the settings page
     */
    public function index()
    {
        $currentValues = $this->settings->getCurrentValues();
        $sections = $this->settings->getSections();
        $moduleName = $this->settings->getModuleName();
        $moduleDescription = $this->settings->getModuleDescription();
        $moduleIcon = $this->settings->getModuleIcon();

        return view('systemcore::settings.index', compact(
            'currentValues',
            'sections',
            'moduleName',
            'moduleDescription',
            'moduleIcon'
        ));
    }

    /**
     * Update the settings
     */
    public function update(Request $request)
    {
        // Prepare data for validation - convert checkbox values before validation
        $data = $request->all();

        // Convert checkbox values to boolean for validation
        $booleanFields = ['include_date_in_order_number', 'enable_sync_logging'];
        foreach ($booleanFields as $field) {
            if (isset($data[$field])) {
                $data[$field] = filter_var($data[$field], FILTER_VALIDATE_BOOLEAN);
            } else {
                // If checkbox not sent (unchecked), set to false
                $data[$field] = false;
            }
        }

        // Validate the prepared data
        $validator = Validator::make($data, $this->settings->getValidationRules());

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $validated = $validator->validated();

        // Save settings using the service
        foreach ($validated as $key => $value) {
            $this->settingsService->set('SystemCore', $key, $value);
        }

        return response()->json([
            'success' => true,
            'message' => __('Settings updated successfully'),
        ]);
    }
}
