<?php
use Components\Base;
use Components\Button;
use Components\Dropdown;
use Components\Ui\Badge;

// Gather Updates
$updateItems = [];

// Core Update
$test_core = false;$test_pro = false;
//$test_core = true;$test_pro = true;

$show_update_core = mh_session('mh_version_core_check');
if ($test_core || $show_update_core && (mh_session('mh_version_core_check') > mh_cfg('MAILBEEZ_VERSION'))) {
    $new_version = mh_session('mh_version_core_check');
    $updateItems[] = [
        'label' => sprintf(mh_lng('UI_BUTTON_CORE_UPDATE', 'Update Core to %s'), $new_version),
        'description' => mh_lng('UI_CORE_UPDATE_DESC', 'A new version of MailBeez Core is available.'),
        'url' => mh_href_link(FILENAME_MAILBEEZ, 'cloudloader_mode=update_core'),
        'badge' => $new_version,
    ];
}

// Pro Update
if (!class_exists('cloudbeez_status_handler')) {
    $handler_file = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'configbeez/config_cloudbeez/classes/cloudbeez_status_handler.php';
    if (file_exists($handler_file)) {
        include_once($handler_file);
    }
}

if (class_exists('cloudbeez_status_handler')) {
    $show_update_package = false;
    $cache_ok = false;
    if (isset($_SESSION['cache_cloudbeez_status_handler']) && isset($_SESSION['cache_cloudbeez_status_handler_time'])) {
        if (time() - 300 < $_SESSION['cache_cloudbeez_status_handler_time']) {
            $cache_ok = true;
        }
    }

    // Only call getStatus if cache is valid or we explicitly want to force a check
    // This avoids synchronous slow calls during page render
    if ($cache_ok || (isset($force_check) && $force_check)) {
        list(,,, $show_update_package) = cloudbeez_status_handler::getStatus(true, false);
    }

    if ($test_pro || $show_update_package) {
        list(,, $update_package_url,,,) = cloudbeez_status_handler::getActionUrls();
        $updateItems[] = [
            'label' => mh_lng('UI_BUTTON_PRO_UPDATE', 'Update Pro'),
            'description' => mh_lng('UI_PRO_UPDATE_DESC', 'A new version of MailBeez Pro is available.'),
            'url' => $update_package_url,
        ];
    }
}

$updatesDropdown = '';
$updatesCount = count($updateItems);
if ($updatesCount > 0) {
    $dropdownItems = [];
    foreach ($updateItems as $item) {
        ob_start(); ?>
        <div class="flex flex-col">
          <div class="flex justify-between items-center gap-4">
            <div class="inline-flex items-center gap-2">
              <span class="inline-flex size-5 items-center justify-center text-brand group-focus/item:text-white"><?php echo Base::SVG_REFRESH; ?></span>
              <p class="font-semibold"><?php echo Base::h($item['label']); ?></p>
            </div>
            <?php if (!empty($item['badge'])): ?>
              <?php echo Badge::render('primary', $item['badge'],
                    [
                        'variant' => 'solid',
                    ]

                ); ?>
            <?php endif; ?>
          </div>
          <p class="mt-1 text-xs text-secondary group-focus/item:text-brand-100 dark:group-focus/item:text-brand-100"><?php echo Base::h($item['description']); ?></p>
        </div>
        <?php
        $itemHtml = ob_get_clean();

        $dropdownItems[] = [
            'content' => '<a href="' . $item['url'] . '" target="_top" role="menuitem" class="group/item flex flex-col w-full text-left px-4 py-3 text-sm text-primary focus:bg-brand focus:text-white focus:outline-hidden dark:text-white dark:focus:bg-brand" ' .
                Base::attrs([
                    'onmousedown' => 'event.stopPropagation();',
                    'onclick' => 'event.stopPropagation();',
                ]) . '>' . $itemHtml . '</a>'
        ];
    }

    $updatesLabel = ($updatesCount === 1)
        ? mh_lng('UI_UPDATE_LABEL_SINGLE', '1 Update')
        : sprintf(mh_lng('UI_UPDATE_LABEL_MULTIPLE', '%d Updates'), $updatesCount);

    $updatesDropdown = Dropdown::render([
        'trigger_tag' => 'div',

        'trigger_html' => Button::render($updatesLabel, [
            'variant' => 'primary',
            'size' => 'xs',
            'rounded' => 'xl',
            'icon' => Base::SVG_CHEVRON_DOWN,
            'iconPosition' => 'back',
            'class' => 'px-3'
        ]),
        'items' => $dropdownItems,
        'anchor' => 'bottom ',
    ]);
}

echo $updatesDropdown;
