<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class LanguageController extends Controller
{
    /**
     * Return basic language data used by the client
     */
    public function getLanguageData(Request $request)
    {
        $user = Auth::user();

        return response()->json([
            'isAuthenticated' => (bool) $user,
            'currentLanguage' => $user ? ($user->lang ?? 'en') : ($request->session()->get('preferred-language') ?? 'en'),
            'userId' => $user ? $user->JID : null,
            'browserLanguage' => substr($request->server('HTTP_ACCEPT_LANGUAGE') ?? 'en', 0, 2),
        ]);
    }

    /**
     * Update language preference for authenticated users or store in session for guests
     */
    public function updateLanguage(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'language' => 'required|string|max:10',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => 'Invalid language code'], 422);
        }

        $lang = $request->input('language');

        try {
            $user = Auth::user();

            // Always store in session regardless of authentication
            $request->session()->put('preferred-language', $lang);

            if ($user) {
                // If authenticated, also store in database
                try {
                    // Use direct DB query as fallback if model save doesn't work
                    DB::connection('sqlsrv')->table('users')
                        ->where('JID', $user->JID)
                        ->update(['lang' => $lang]);

                    Log::info('Language updated for authenticated user', ['user_id' => $user->JID, 'lang' => $lang]);
                } catch (\Exception $dbError) {
                    // If database update fails, at least session is saved
                    Log::warning('Failed to update language in database, but session saved', [
                        'error' => $dbError->getMessage(),
                        'user_id' => $user->JID ?? 'unknown',
                        'lang' => $lang
                    ]);
                }
            } else {
                Log::info('Language updated in session for guest', ['lang' => $lang]);
            }

            // Update the application locale for the current request
            App::setLocale($lang);

            return response()->json(['success' => true, 'message' => 'Language updated successfully']);
        } catch (\Exception $e) {
            Log::error('Failed to update user language', ['error' => $e->getMessage(), 'lang' => $lang]);
            return response()->json(['success' => false, 'message' => 'Server error'], 500);
        }
    }
}
