<?php

namespace App\Http\Controllers;

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

class StorePreferenceController extends Controller
{
    public function currency(Request $request)
    {
        $data = $request->validate([
            'currency' => ['required', 'string', 'size:3', 'exists:currencies,code'],
        ]);

        session(['store_currency' => strtoupper($data['currency'])]);

        if ($request->expectsJson()) {
            $currency = Currency::where('code', strtoupper($data['currency']))->first();

            return response()->json([
                'ok' => true,
                'type' => 'currency',
                'currency' => strtoupper($data['currency']),
                'symbol' => $currency?->symbol,
                'symbol_position' => $currency?->symbol_position ?? 'after',
                'exchange_rate' => (float) ($currency?->exchange_rate ?? 1),
                'flag' => match (strtoupper($data['currency'])) {
                    'AED' => asset('images/flags/ae.png'),
                    'EUR' => asset('images/flags/eu.png'),
                    'SAR' => asset('images/flags/sa.png'),
                    'USD' => asset('images/flags/us.png'),
                    default => asset('images/flags/eg.png'),
                },
            ]);
        }

        return back();
    }

    public function locale(Request $request)
    {
        $data = $request->validate([
            'locale' => ['required', 'string', 'in:ar,en'],
        ]);

        session(['store_locale' => $data['locale']]);
        App::setLocale($data['locale']);

        if ($request->expectsJson()) {
            return response()->json([
                'ok' => true,
                'type' => 'locale',
                'locale' => $data['locale'],
                'label' => $data['locale'] === 'en' ? 'English' : 'عربي',
                'flag' => asset('images/flags/'.($data['locale'] === 'en' ? 'us.png' : 'sa.png')),
                'dir' => $data['locale'] === 'en' ? 'ltr' : 'rtl',
            ]);
        }

        return back();
    }
}
