<?php

namespace App\Http\Controllers;

use App\Models\Currency;
use Illuminate\Http\Request;

class CurrencyController extends Controller
{
    public function index()
    {
        $currencies = Currency::orderBy('code')->get();

        return view('currencies.index', compact('currencies'));
    }

    public function store(Request $request)
    {
        $request->merge([
            'code' => strtoupper(trim((string) $request->input('code'))),
        ]);

        $data = $request->validate([
            'code' => ['required', 'string', 'max:10', 'regex:/^[A-Z]{3,10}$/', 'unique:currencies,code'],
            'name' => ['required', 'string', 'max:255'],
        ]);

        $currency = Currency::create($data);

        return redirect()
            ->route('currencies.index')
            ->with('success', 'Currency added successfully.');
    }

    public function edit(Currency $currency)
    {
        return view('currencies.edit', compact('currency'));
    }

    public function update(Request $request, Currency $currency)
    {
        $request->merge([
            'code' => strtoupper(trim((string) $request->input('code'))),
        ]);

        $data = $request->validate([
            'code' => ['required', 'string', 'max:10', 'regex:/^[A-Z]{3,10}$/', 'unique:currencies,code,' . $currency->id],
            'name' => ['required', 'string', 'max:255'],
        ]);

        $currency->update($data);

        return redirect()
            ->route('currencies.index')
            ->with('success', 'Currency updated successfully.');
    }
}
