<?php

namespace App\Http\Controllers;

use App\Models\SettingApp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SettingAppController extends Controller
{
    public function getByCategory($category)
    {
        $setting = SettingApp::where('category', $category)->first();

        if (!$setting) {
            return response([
                'success' => false,
                'message' => 'Setting app not found',
            ], 404);
        }

        return response([
            'success' => true,
            'data' => $setting,
        ], 200);
    }

    public function updateByCategory(Request $request, $category)
    {
        $validated = $request->validate([
            'status' => 'required|boolean',
        ]);

        DB::beginTransaction();

        try {
            $setting = SettingApp::updateOrCreate(
                ['category' => $category],
                ['status' => $validated['status']]
            );

            DB::commit();

            return response([
                'success' => true,
                'data' => $setting,
            ], 200);
        } catch (\Exception $e) {
            DB::rollback();

            return response([
                'success' => false,
                'message' => 'Terjadi kesalahan saat mengupdate setting app: ' . $e->getMessage(),
            ], 500);
        }
    }
}
