<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Setting;
use App\Services\CurrencyService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Cache;

class CurrencyController extends Controller
{
    public function index()
    {
        return Inertia::render('cp/Settings/CurrencyManager', [
            'apiKey' => Setting::where('key', 'exchangerate_api_key')->value('value') ?? ''
        ]);
    }

    public function getCurrencies()
    {
        return response()->json(Currency::orderBy('is_default', 'desc')->get());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|size:3|unique:currencies,code',
            'symbol' => 'required|string|max:10',
            'exchange_rate' => 'numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $currency = Currency::create($validated);
        Cache::forget('active_currencies'); // <-- CLEAR CACHE
        return response()->json($currency);
    }

    public function destroy(Currency $currency)
    {
        if ($currency->is_default) {
            return response()->json(['message' => 'Cannot delete the default currency.'], 400);
        }
        $currency->delete();
        Cache::forget('active_currencies'); // <-- CLEAR CACHE
        return response()->json(['success' => true]);
    }

    public function setDefault(Currency $currency)
    {
        Currency::query()->update(['is_default' => false, 'exchange_rate' => null]); 
        $currency->update(['is_default' => true, 'exchange_rate' => 1.0]);
        Cache::forget('active_currencies'); // <-- CLEAR CACHE
        return response()->json(['success' => true]);
    }

    public function toggleActive(Currency $currency)
    {
        if ($currency->is_default) {
            return response()->json(['message' => 'Default currency must remain active.'], 400);
        }
        $currency->update(['is_active' => !$currency->is_active]);
        Cache::forget('active_currencies'); // <-- CLEAR CACHE
        return response()->json(['success' => true]);
    }

    public function saveSettings(Request $request)
    {
        $request->validate(['exchangerate_api_key' => 'required|string']);
        Setting::updateOrCreate(['key' => 'exchangerate_api_key'], ['value' => $request->exchangerate_api_key]);
        return back()->with('success', 'API Key saved successfully.');
    }

    public function syncRates(CurrencyService $currencyService)
    {
        try {
            $currencyService->syncExchangeRates();
            Cache::forget('active_currencies'); // <-- CLEAR CACHE
            return response()->json(['message' => 'Exchange rates updated successfully!']);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 400);
        }
    }
}