<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsMatchingSetting;

class MatchingSettingController extends BmsBaseController
{
    /** Matchable criteria (key => label). */
    protected function criteria(): array
    {
        return [
            'capacity'     => __('bms::lang.capacity'),
            'fnb_level'    => __('bms::lang.fnb_level'),
            'venue_type'   => __('bms::lang.venue_type'),
            'area'         => __('bms::lang.area'),
            'budget'       => __('bms::lang.min_budget'),
            'availability' => __('bms::lang.availability'),
        ];
    }

    public function edit()
    {
        $this->guard('bms.matching.manage');

        $setting = BmsMatchingSetting::resolve($this->businessId());
        $criteria = $this->criteria();

        return view('bms::matching.edit', compact('setting', 'criteria'));
    }

    public function update(Request $request)
    {
        $this->guard('bms.matching.manage');

        $request->validate([
            'threshold'   => 'required|integer|min:0|max:100',
            'weights'     => 'required|array',
            'weights.*'   => 'required|integer|min:0|max:100',
        ]);

        try {
            $setting = BmsMatchingSetting::resolve($this->businessId());
            $setting->business_id = $this->businessId();
            $setting->threshold = (int) $request->input('threshold');
            // keep only known criteria keys
            $weights = [];
            foreach (array_keys($this->criteria()) as $key) {
                $weights[$key] = (int) $request->input("weights.$key", 0);
            }
            $setting->weights = $weights;
            $setting->updated_by = $this->userId();
            $setting->save();

            $output = ['success' => 1, 'msg' => __('bms::lang.success')];
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            $output = ['success' => 0, 'msg' => __('messages.something_went_wrong')];
        }

        return redirect()->route('bms.matching.edit')->with('status', $output);
    }
}
