<?php

namespace Modules\LabCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\LabCore\Entities\LabSetting;

class LabSettingsController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('lab.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $settings = LabSetting::allFor($businessId);

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

    public function update(Request $request)
    {
        if (!auth()->user()->can('lab.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $data = $request->validate([
            'clinic_name'     => 'nullable|string|max:120',
            'clinic_subtitle' => 'nullable|string|max:160',
            'clinic_phone'    => 'nullable|string|max:40',
            'clinic_email'    => 'nullable|string|max:120',
        ]);

        foreach ($data as $key => $value) {
            LabSetting::set($businessId, $key, (string) $value);
        }
        LabSetting::set($businessId, 'vetclinic_sync', $request->boolean('vetclinic_sync') ? '1' : '0');

        return redirect()->route('lab.settings.index')->with('status', [
            'success' => 1, 'msg' => 'Settings saved.',
        ]);
    }
}
