<?php

namespace App\Http\Controllers;

class ContractSettingController extends Controller
{
    public function edit(): \Inertia\Response
    {
        $setting = \App\Models\ContractSetting::query()->first();
        if (! $setting) {
            $setting = \App\Models\ContractSetting::query()->create([
                'create_activity_on_balance_change' => false,
                'default_action_id' => null,
                'default_decision_id' => null,
                'activity_note_template' => 'Sprememba stanja pogodbe: {old_balance} → {new_balance} {currency}',
            ]);
        }

        $decisions = \App\Models\Decision::query()->orderBy('name')->get(['id', 'name']);
        $actions = \App\Models\Action::query()
            ->with(['decisions:id'])
            ->orderBy('name')
            ->get()
            ->map(function (\App\Models\Action $a) {
                return [
                    'id' => $a->id,
                    'name' => $a->name,
                    'decision_ids' => $a->decisions->pluck('id')->values(),
                ];
            });

        return \Inertia\Inertia::render('Settings/Contracts/Index', [
            'setting' => [
                'id' => $setting->id,
                'create_activity_on_balance_change' => (bool) $setting->create_activity_on_balance_change,
                'default_action_id' => $setting->default_action_id,
                'default_decision_id' => $setting->default_decision_id,
                'activity_note_template' => $setting->activity_note_template,
            ],
            'decisions' => $decisions,
            'actions' => $actions,
        ]);
    }

    public function update(\App\Http\Requests\UpdateContractSettingRequest $request): \Illuminate\Http\RedirectResponse
    {
        $data = $request->validated();
        $setting = \App\Models\ContractSetting::query()->firstOrFail();

        $data['create_activity_on_balance_change'] = (bool) ($data['create_activity_on_balance_change'] ?? false);

        $setting->update($data);

        return back()->with('success', 'Nastavitve shranjene.');
    }
}
