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

use OxygenApp\Utils\OptionUtils;
use OxygenApp\Models\Background;
use OxygenApp\Utils\UserUtil;
use OxygenApp\Models\User;

class BackgroundUtils {

    static function getSysDefaultBackground(): ?array {

        $out = null;
        // get default background
        $default_background = OptionUtils::getInstance()->getOption('default_background', '');
        if ($default_background && is_numeric($default_background)) {
            $backgroundPost = Background::getById($default_background);
            if ($backgroundPost) {
                $out = Background::getPretty($backgroundPost);
            }
        } else {
            $allBackgrounds = Background::getAll();
            if (count($allBackgrounds) > 0) {
                $randomKey = array_rand($allBackgrounds);
                $randomPost = $allBackgrounds[$randomKey];
                $out = Background::getPretty($randomPost);
            }
        }
        return $out;
    }

    static function getUserDefaultBackground(): ?array {
        $out = null;
        if (UserUtil::isLoggedIn()) {
            $userSessionData = UserUtil::getInstance()->getUserFromSession();
            $user_id = $userSessionData['user_id'] ?? '';
            $user = new User();
            $userbackgroundid = $user->getUserMetaByKey($user_id, 'userbackgroundid', null);


            if (!$userbackgroundid || $userbackgroundid === -1) {
                return null;
            }

            $existingBackground = Background::getPretty(Background::getById($userbackgroundid));
            if ($existingBackground) {
                $out = $existingBackground;
            }
        }
        return $out;
    }

    static function getBackgrounds(): array {
        $out = [];
        $allBackgrounds = Background::getAll();

        if (is_array($allBackgrounds)) {
            foreach ($allBackgrounds as $backgroundPost) {
                $bkPretty = Background::getPretty($backgroundPost);
                $out[] = $bkPretty;
            }
        }

        return $out;
    }
}