<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CurrencyRate;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class CurrencyController extends Controller
{
    public function index(): View
    {
        return view('admin.currencies', [
            'rates' => CurrencyRate::query()->orderBy('base_currency')->orderBy('quote_currency')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'base_currency' => ['required', 'string', 'max:10'],
            'quote_currency' => ['required', 'string', 'max:10'],
            'rate' => ['required', 'numeric', 'min:0.00000001'],
        ]);

        CurrencyRate::query()->updateOrCreate(
            [
                'base_currency' => strtoupper($validated['base_currency']),
                'quote_currency' => strtoupper($validated['quote_currency']),
            ],
            [
                'rate' => (float) $validated['rate'],
                'is_active' => true,
                'fetched_at' => now(),
            ]
        );

        return back()->with('status', 'Currency rate saved.');
    }

    public function toggle(int $rateId): RedirectResponse
    {
        $rate = CurrencyRate::query()->findOrFail($rateId);
        $rate->is_active = ! $rate->is_active;
        $rate->save();

        return back()->with('status', 'Currency status updated.');
    }
}
