<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:settings.view')->only(['index']);
        $this->middleware('permission:settings.edit')->only(['update']);
    }

    public function index()
    {
        $settings = Setting::all()->pluck('value', 'key');
        $auditLogs = AuditLog::with('user')->latest()->paginate(20);
        $organizations = \App\Models\Organization::all();
        
        return view('settings.index', compact('settings', 'auditLogs', 'organizations'));
    }

    public function update(Request $request)
    {
        $data = $request->except(['_token']);

        foreach ($data as $key => $value) {
            Setting::set($key, $value);
        }

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