<?php

namespace App\Http\Controllers;

use App\Http\Requests\ExchangeRateRequest;
use App\Models\ExchangeRate;
use App\Models\Setting;
use App\Services\ExchangeRateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class CurrencyController extends Controller
{
    public function index()
    {
        // Latest rates
        $latest = ExchangeRate::orderByDesc('recorded_at')
            ->first();

        // Last 14 days for graph
        $exchange_rates = ExchangeRate::orderBy('recorded_at', 'desc')->take(10)->get();


        // ✅ Get settings where group = currency
        $currency_settings =  Setting::group('currency')->pluck('value', 'key');

        return Inertia::render('dashboard/currency-settings/index', [
            'latest' => $latest,
            'exchange_rates' => $exchange_rates,
            'currency_settings' => $currency_settings
        ]);
    }


    public function update(Request $request)
    {
        try {
            $validated = $request->validate([
                'exchange_rate_update_auto' => 'nullable|boolean',
                'exchange_rate_update_time' => 'nullable|string',
                'website_currency_types' => 'nullable|array',
                'website_currency' => 'nullable|string',
            ]);

            DB::transaction(function () use ($request, $validated) {

                $settings = [
                    'exchange_rate_update_auto',
                    'exchange_rate_update_time',
                    'website_currency_types',
                    'website_currency',
                ];

                foreach ($settings as $key) {
                    if ($request->has($key)) {
                        Setting::set($key, $validated[$key] ?? $request->input($key), 'currency');
                    }
                }

                $result = ExchangeRateService::addRecord();

                if (!$result) {
                    throw new \Exception('Exchange rate update failed');
                }
            });

            return back()->with('success', 'Settings saved & exchange rates updated successfully');
        } catch (\Throwable $e) {
            return back()->with('error', 'Transaction failed. Please try again.');
        }
    }
}
