<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdatePaymentSettingRequest;
use App\Models\Action;
use App\Models\Decision;
use App\Models\PaymentSetting;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class PaymentSettingController extends Controller
{
    public function edit(): Response
    {
        $setting = PaymentSetting::query()->first();
        if (! $setting) {
            $setting = PaymentSetting::query()->create([
                'default_currency' => 'EUR',
                'create_activity_on_payment' => false,
                'default_decision_id' => null,
                'default_action_id' => null,
                'activity_note_template' => 'Prejeto plačilo: {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/Payments/Index', [
            'setting' => [
                'id' => $setting->id,
                'default_currency' => $setting->default_currency,
                'create_activity_on_payment' => (bool) $setting->create_activity_on_payment,
                '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(UpdatePaymentSettingRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $setting = PaymentSetting::query()->firstOrFail();

        // Ensure boolean cast for checkbox
        $data['create_activity_on_payment'] = (bool) ($data['create_activity_on_payment'] ?? false);

        $setting->fill($data)->save();

        return back()->with('success', 'Payment settings updated.');
    }
}
