<?php
namespace OxygenApp\Controllers;

if ( ! defined( 'ABSPATH' ) ) exit;

use OxygenApp\Utils\LanguagesHelper;
use OxygenApp\Utils\UserUtil;
use OxygenApp\Utils\Sanitizer;
use OxygenApp\Models\User;
use OxygenApp\Utils\OxySession;

class LangCtrl {

    static function create(\WP_REST_Request $request): \WP_REST_Response {
        
        $lang = $request->get_param('lang');
        $lang = Sanitizer::sanitize_data($lang);
        if (!$lang || !LanguagesHelper::getInstance()->isValidLanguageCode($lang)) {
            return new \WP_REST_Response(['message' => esc_html__('Invalid language.', 'oxyleaf-app-working-and-relaxing-app')], 400);
        }
        if (UserUtil::isLoggedIn()) {
            
            $userData = UserUtil::getInstance()->getUserFromSession();
            $user_id = $userData['user_id'] ?? null;
            if (!$user_id) {
                return new \WP_REST_Response(['message' => esc_html__('User not found.', 'oxyleaf-app-working-and-relaxing-app')], 400);
            }
            $user = new User();
            $userData = $user->find('id', $user_id);
            if (!$userData) {
                return new \WP_REST_Response(['message' => esc_html__('User not found.', 'oxyleaf-app-working-and-relaxing-app')], 400);
            }
            
            
            $user->updateUserMeta($user_id, 'lang', $lang);
        }

        // Set the language in the session
        OxySession::initSession();
        $_SESSION['current_language_code'] = $lang;

        return new \WP_REST_Response([], 200);
    }
}