<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Services\Settings\VrcSettings;

/**
 * Repair-specific settings under the vrc.* namespace (spec §6.15). Writes to
 * the per-business vrc_settings store; currency / tax / timezone / numbering
 * continue to come from ERP business settings and are not duplicated here.
 */
class SettingController extends VrcBaseController
{
    public function edit()
    {
        $this->guard('vrc.settings.access');

        $settings = VrcSettings::all($this->businessId());

        return view('vrc::settings.edit', compact('settings'));
    }

    public function update(Request $request)
    {
        $this->guard('vrc.settings.access');

        $data = $this->validate($request, [
            'default_labor_rate'     => 'nullable|numeric|min:0',
            'estimate_validity_days' => 'nullable|integer|min:0',
            'estimate_source'        => 'required|in:native,erp',
            'service_catalog_source' => 'required|in:native,erp',
            'comms_channel'          => 'required|in:sms,whatsapp',
            'comms_matrix'           => 'nullable|array',
        ]);

        try {
            $businessId = $this->businessId();

            VrcSettings::put($businessId, 'default_labor_rate', (float) ($data['default_labor_rate'] ?? 0));
            VrcSettings::put($businessId, 'estimate_validity_days', (int) ($data['estimate_validity_days'] ?? 14));
            VrcSettings::put($businessId, 'estimate_source', $data['estimate_source']);
            VrcSettings::put($businessId, 'service_catalog_source', $data['service_catalog_source']);
            VrcSettings::put($businessId, 'comms_channel', $data['comms_channel']);

            // Comms matrix: persist every known event as an explicit boolean
            // so an unchecked box is stored as false (not just omitted).
            $known = array_keys((array) (VrcSettings::defaults()['comms_matrix'] ?: []));
            $posted = (array) ($data['comms_matrix'] ?? []);
            $matrix = [];
            foreach ($known as $event) {
                $matrix[$event] = (bool) ($posted[$event] ?? false);
            }
            VrcSettings::put($businessId, 'comms_matrix', $matrix);

            return redirect()->route('vrc.settings.edit')->with('status', [
                'success' => 1,
                'msg'     => __('vrc::lang.updated_success'),
            ]);
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return redirect()->route('vrc.settings.edit')->with('status', [
                'success' => 0,
                'msg'     => __('messages.something_went_wrong'),
            ]);
        }
    }
}
