<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SettingController extends Controller
{
    public function index()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Settings', 'active' => true]
        ];

        $setting = Setting::first();

        $data = [
            'title' => 'Settings',
            'breadcrumbs' => $breadcrumbs,
            'setting' => $setting
        ];

        return view('dashboard.admin.setting.index', $data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'registration_token' => ['required', 'string', 'max:255'],
        ]);

        try {
            DB::transaction(function () use ($request) {
                Setting::updateOrCreate([
                    'id' => 1,
                ], [
                    'registration_token' => $request->registration_token,
                ]);
            });

            return redirect()->back()->with('success', 'Settings updated successfully.');
        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return redirect()->back()->with('error', 'Failed to update settings.');
        }
    }
}
