<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingApiController extends Controller
{
    /**
     * Tampilkan semua pengaturan global
     */
    public function index(Request $request)
    {
        // Pengaturan bersifat global (seperti Tarif PPN), aman untuk dibaca oleh seluruh otorisasi
        $settings = Setting::all();
        
        return response()->json([
            'success' => true,
            'data' => $settings
        ]);
    }

    /**
     * Update pengaturan sistem (Hanya Pusat)
     */
    public function update(Request $request, $id)
    {
        $user = $request->user();

        // ========================================================================
        // PERBAIKAN ENTERPRISE: Kunci Otorisasi Perubahan Konfigurasi Inti
        // ========================================================================
        if ($user && !in_array($user->role, ['owner', 'manager'])) {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Manajemen Pusat (Owner/Manager) yang berhak mengubah pengaturan sistem.'
            ], 403);
        }
        // ========================================================================

        $request->validate([
            'value' => 'required'
        ]);

        $setting = Setting::findOrFail($id);
        $setting->update([
            'value' => $request->value
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Pengaturan berhasil diperbarui',
            'data' => $setting
        ]);
    }
}