<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetClinic\Entities\VcModuleSetting;

class VcSettingsController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('vet_clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $settings = [
            'doctors_shared'  => VcModuleSetting::get($businessId, 'doctors_shared', '1'),
            'allow_overlap'   => VcModuleSetting::get($businessId, 'allow_overlap', '1'),
            'reminder_days'   => VcModuleSetting::get($businessId, 'reminder_days', config('vetclinic.reminder_days', 30)),
            'soap_chip_limit' => VcModuleSetting::get($businessId, 'soap_chip_limit', '15'),
            'action_target'   => VcModuleSetting::get($businessId, 'action_target', '_self'),
        ];

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

    public function save(Request $request)
    {
        if (!auth()->user()->can('vet_clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'reminder_days'   => 'required|integer|min:1|max:365',
            'soap_chip_limit' => 'required|integer|min:5|max:50',
        ]);

        $businessId = request()->session()->get('user.business_id');
        VcModuleSetting::set($businessId, 'doctors_shared',  $request->input('doctors_shared') === '1' ? '1' : '0');
        VcModuleSetting::set($businessId, 'allow_overlap',   $request->input('allow_overlap')  === '1' ? '1' : '0');
        VcModuleSetting::set($businessId, 'reminder_days',   (int) $request->reminder_days);
        VcModuleSetting::set($businessId, 'soap_chip_limit', (int) $request->soap_chip_limit);
        VcModuleSetting::set($businessId, 'action_target',   $request->input('action_target') === '_blank' ? '_blank' : '_self');

        return response()->json(['success' => true, 'msg' => __('vetClinic::lang.updated_successfully')]);
    }
}
