<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcModuleSetting;

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

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

        // Capability overrides (tri-state: '' inherit | '1' on | '0' off).
        $capabilities = [];
        foreach (['controlled_drugs', 'vitals', 'ai_assist'] as $cap) {
            $capabilities[$cap] = [
                'override'  => (string) ClcModuleSetting::get($businessId, 'capability.' . $cap, ''),
                'effective' => \Modules\ClinicCore\Entities\Services\ClinicCapabilities::businessHas($businessId, $cap),
            ];
        }

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

    public function save(Request $request)
    {
        if (!auth()->user()->can('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');
        ClcModuleSetting::set($businessId, 'doctors_shared',  $request->input('doctors_shared') === '1' ? '1' : '0');
        ClcModuleSetting::set($businessId, 'allow_overlap',   $request->input('allow_overlap')  === '1' ? '1' : '0');
        ClcModuleSetting::set($businessId, 'reminder_days',   (int) $request->reminder_days);
        ClcModuleSetting::set($businessId, 'soap_chip_limit', (int) $request->soap_chip_limit);
        ClcModuleSetting::set($businessId, 'action_target',   $request->input('action_target') === '_blank' ? '_blank' : '_self');

        // Capability overrides — '' (inherit) | '1' (force on) | '0' (force off).
        foreach (['controlled_drugs', 'vitals', 'ai_assist'] as $cap) {
            $val = (string) $request->input('capability_' . $cap, '');
            $val = in_array($val, ['1', '0'], true) ? $val : '';
            ClcModuleSetting::set($businessId, 'capability.' . $cap, $val);
        }

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

    /** Apply a clinic-type preset (a bundle of capability overrides). */
    public function applyPreset(Request $request)
    {
        if (!auth()->user()->can('clinic.access_settings')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');
        $ok = \Modules\ClinicCore\Entities\Services\ClinicCapabilities::applyPreset($businessId, (string) $request->preset);

        return response()->json([
            'success' => $ok,
            'msg'     => $ok ? __('clinicCore::lang.preset_applied') : __('clinicCore::lang.invalid_preset'),
        ], $ok ? 200 : 422);
    }
}
