<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateInstallmentSettingRequest;
use App\Models\Action;
use App\Models\Decision;
use App\Models\InstallmentSetting;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class InstallmentSettingController extends Controller
{
    public function edit(): Response
    {
        $setting = InstallmentSetting::query()->first();
        if (! $setting) {
            $setting = InstallmentSetting::query()->create([
                'default_currency' => 'EUR',
                'create_activity_on_installment' => false,
                'default_decision_id' => null,
                'default_action_id' => null,
                'activity_note_template' => 'Dodan obrok: {amount} {currency}',
            ]);
        }

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

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

    public function update(UpdateInstallmentSettingRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $setting = InstallmentSetting::query()->firstOrFail();

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

        $setting->update($data);

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