<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CurrencyRate;
use App\Models\Setting;
use Illuminate\Http\Request;

class CurrencyController extends Controller
{
    protected $currencies = ['XOF', 'EUR', 'USD', 'GBP'];

    public function index()
    {
        $rates = CurrencyRate::orderBy('from_currency')->orderBy('to_currency')->get();
        $defaultCurrency = Setting::where('key', 'default_currency')->value('value') ?? 'XOF';
        
        return view('admin.currencies.index', compact('rates', 'defaultCurrency'));
    }

    public function update(Request $request, CurrencyRate $rate)
    {
        $request->validate([
            'rate' => 'required|numeric|min:0.0000000001'
        ]);

        $rate->update([
            'rate' => $request->rate,
            'fetched_at' => now()
        ]);

        return redirect()->route('admin.currencies.index')
            ->with('success', 'Taux mis à jour');
    }

    public function store(Request $request)
    {
        $request->validate([
            'from_currency' => 'required|string|size:3',
            'to_currency' => 'required|string|size:3|different:from_currency',
            'rate' => 'required|numeric|min:0.0000000001'
        ]);

        CurrencyRate::updateOrCreate(
            [
                'from_currency' => strtoupper($request->from_currency),
                'to_currency' => strtoupper($request->to_currency)
            ],
            [
                'rate' => $request->rate,
                'fetched_at' => now()
            ]
        );

        return redirect()->route('admin.currencies.index')
            ->with('success', 'Taux ajouté');
    }

    public function destroy(CurrencyRate $rate)
    {
        $rate->delete();
        return redirect()->route('admin.currencies.index')
            ->with('success', 'Taux supprimé');
    }

    public function setDefault(Request $request)
    {
        $request->validate([
            'currency' => 'required|string|size:3'
        ]);

        Setting::updateOrCreate(
            ['key' => 'default_currency'],
            ['value' => strtoupper($request->currency), 'group' => 'currency']
        );

        return redirect()->route('admin.currencies.index')
            ->with('success', 'Devise par défaut mise à jour');
    }

    public function refreshRates()
    {
        return redirect()->route('admin.currencies.index')
            ->with('info', 'Mise à jour automatique des taux non configurée. Mettez à jour manuellement.');
    }
}
