<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UpdateMobileSettingRequest;
use App\Models\MobileSetting;
use App\Services\MobileConfig\MobileConfigService;
use App\Services\Monitoring\SystemMonitoringService;
use Illuminate\Support\Facades\Log;

class MobileSettingController extends Controller
{
    public function __construct(
        protected MobileConfigService $service,
        protected SystemMonitoringService $monitor
    ) {}

    public function index()
    {
        $settings = $this->service->getGroupedSettingsForAdmin();
        $settings = collect($settings)->only([
            'branding',
            'control_center',
            'app_updates',
            'features',
            'security_auth',
            'connectivity',
            'notifications',
            'support_social',
            'analytics_system',
            'localization',
        ]);

        return view('pages.mobile-settings.index', compact('settings'));
    }

    public function update(UpdateMobileSettingRequest $request)
    {
        try {
            // 1. Separate files and text data
            $files = $request->allFiles();
            $data = $request->except(array_merge(array_keys($files), ['_token', '_method', 'fakeuser', 'fakepass']));

            // 2. Identify all boolean fields to handle "false" values (unchecked checkboxes)
            $booleanKeys = $this->service->getBooleanKeys();
            foreach ($booleanKeys as $key) {
                if (! isset($data[$key])) {
                    $data[$key] = 'false';
                }
            }

            // 3. Delegate to Service (service::update already clears its own cache)
            $this->service->update($data, $files);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => __('Configuration and assets updated!'),
                    'settings' => MobileSetting::all()->pluck('value', 'key'),
                    'timestamp' => now()->timestamp,
                ]);
            }

            return redirect()->back()->with('success', __('Configuration and assets updated!'));
        } catch (\Exception $e) {
            Log::error('Mobile Settings Save Error: '.$e->getMessage(), [
                'trace' => $e->getTraceAsString(),
            ]);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error: '.$e->getMessage(),
                ], 500);
            }

            return redirect()->back()->with('error', 'Error occurred while saving: '.$e->getMessage());
        }
    }
}
