<?php

namespace App\Http\Controllers\SuperAdmin\Landlord;

use App\Http\Controllers\Controller;
use App\Models\LandLordSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Setting; // Assumes you have a Setting model

class SettingsController extends Controller
{
    /**
     * Display the settings page.
     */
    public function index()
    {
        // Fetch all settings as a key-value pair array
        // Example: ['company_name' => 'LegalPro', 'mpesa_env' => 'sandbox']
        $settings = LandLordSetting::all()->pluck('value', 'key')->toArray();

        return view('landlord.settings.index', compact('settings'));
    }

    /**
     * Update the settings.
     */
    public function update(Request $request)
    {
        // 1. Get all data except the token
        $data = $request->except('_token');

        // 2. Loop through and save/update each key
        foreach ($data as $key => $value) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        // 3. Handle checkboxes (if unchecked, they aren't sent in the request)
        // We manually check for known checkbox keys and set them to 0 if missing
        $checkboxes = ['enable_gemini', 'enable_openai', 'enable_sms_notifications', 'enable_whatsapp_notifications'];
        foreach ($checkboxes as $chk) {
            if (!$request->has($chk)) {
                Setting::updateOrCreate(['key' => $chk], ['value' => '0']);
            }
        }

        return back()->with('success', 'System configuration updated successfully.');
    }
}
