<?php

namespace OxygenApp\Utils;
if (!defined('ABSPATH')) exit;

use OxygenApp\Models\User;
use OxygenApp\Utils\OxySession;


class UserUtil {

    private static ?UserUtil $instance = null;
    private ?array $liveUserData = [];

    private function __construct() {
        $this->liveUserData = self::getUserData(self::getCurrentUserId());
    }

    static function isLoggedIn(): bool {
        OxySession::initSession();
        return isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] === true;
    }

    static function getCurrentUserId(): ?int {
        return isset($_SESSION['user_id']) ? absint($_SESSION['user_id']) : null;
    }

    public function getUserFromSession(): array {
        OxySession::initSession();

        $userData = [];
        $userData['user_id'] = isset($_SESSION['user_id']) ? absint($_SESSION['user_id']) : '';
        $userData['user_email'] = isset($_SESSION['user_email']) ? sanitize_email($_SESSION['user_email']) : '';
        $userData['is_logged_in'] = isset($_SESSION['is_logged_in']) ? (bool)$_SESSION['is_logged_in'] : false;
        $userData['logged_in_with_google'] = isset($_SESSION['logged_in_with_google']) ? (bool)$_SESSION['logged_in_with_google'] : false;

        return array_merge($userData, $this->liveUserData);
    }

    static function getUserData(mixed $user_id): ?array {
        if (!is_numeric($user_id)) {
            return [];
        }
        $user = new User();
        $userData = $user->find('id', $user_id);
        if (!is_array($userData)) {
            return [];
        }

        $userMeta = $userData['meta'] ?? '';
        try {
            $userMeta = json_decode($userMeta);
        } catch (\Throwable $th) {}
        
        $fieldsToKeep = ['is_active', 'meta'];
        $filteredUserData = array_intersect_key($userData, array_flip($fieldsToKeep));
        $filteredUserData['meta'] = $userMeta;

        $filteredUserData['is_active'] = (bool)($filteredUserData['is_active'] ?? false);

        return $filteredUserData;
    }

    static function login(array $userData, bool $loggedInWithGoogle = false) {
        OxySession::initSession();

        $_SESSION['user_id'] = $userData['id'] ?? '';
        $_SESSION['user_email'] = $userData['email'] ?? '';
        $_SESSION['is_logged_in'] = true;
        $_SESSION['logged_in_with_google'] = $loggedInWithGoogle;
        
        $user = new User();
        $lang = $user->getUserMetaByKey($userData['id'], 'lang', null);
        if ($lang) {
            $_SESSION['current_language_code'] = $lang;
        }
    }

    static function logout(): void {
        OxySession::initSession();

        if (isset($_SESSION['user_id'])) {
            unset($_SESSION['user_id']);
            unset($_SESSION['user_email']);
            unset($_SESSION['is_logged_in']);
            unset($_SESSION['logged_in_with_google']);
        }
    }

    // Prevent cloning of the instance.
    private function __clone() {}

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new UserUtil();
        }
        return self::$instance;
    }
}