<?php
// pages/license.php
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\Router;
use Components\Base;
use Components\Ui\PageHeader;
use Components\Ui\Tabs;
use Components\Ui\Card;
use Components\Ui\Badge;
use Components\Ui\LicenseCard;
use Components\Resources\ResourceList;
use Components\Button;
use Components\Notification;

$pageKey = 'license';

// Load legacy classes
require_once(MH_DIR_CONFIG . 'config_cloudbeez/classes/api_cloudbeez_consumer.php');
require_once(MH_DIR_CONFIG . 'config_cloudbeez/classes/cloudbeez_status_handler.php');

// Load language files
mh_load_modules_language_files(MH_DIR_CONFIG, 'config_cloudbeez');

$pageTab = (string) mh_get('license_tab', 'license', 'string');
$listUrl = Router::url('license', ['partial' => 1]);
$tabItems = [
    [ 'value' => 'license', 'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_LABEL_LICENSE', 'License') ],
    [ 'value' => 'versions', 'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_LABEL_VERSIONS', 'Installed Versions') ],
];

// Handle Actions
if (mh_get('op') === 'save_api_key' && mh_post('api_key') !== null) {
    $apiKey = trim(mh_post('api_key'));
    mh_update_config_value([
        'configuration_key' => 'CLOUDLOADER_API_KEY',
        'configuration_value' => $apiKey
    ]);
    $_SESSION['cloudloader_refresh_connection'] = true;
    cloudbeez_status_handler::getStatus(false, false);
    header('HX-Refresh: true');
    mh_exit();
}

if (mh_get('op') === 'refresh_confirm') {
    ?>
    <div class="p-6 text-center">
        <h3 class="text-lg font-medium text-zinc-900"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_REFRESH_MODAL_TITLE', 'Refreshing Connection') ?></h3>
        <p class="mt-2 text-sm text-zinc-500"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_REFRESH_MODAL_DESC', 'Please wait while we refresh your license status...') ?></p>
        <div class="mt-6 flex justify-center">
            <div class="h-8 w-8 animate-spin rounded-full border-4 border-zinc-300 border-t-blue-600"></div>
        </div>
        <div hx-get="<?= \Components\Router::url('license', ['op' => 'refresh_execute', 'partial' => 1]) ?>" hx-trigger="load delay:500ms" data-no-global-loader="true" data-no-local-loader="true"></div>
    </div>
    <?php
    mh_exit();
}

if (mh_get('op') === 'refresh_execute') {
    cloudbeez_status_handler::getStatus(false, false, true);
    $_SESSION['refresh_execute'] = true;
    header('HX-Refresh: true');
    mh_exit();
}

if (mh_get('op') === 'refresh') {
    dd('deprecated refresh');
    $_SESSION['cloudloader_refresh_connection'] = true;
    cloudbeez_status_handler::getStatus(false, false);
    header('HX-Refresh: true');
    mh_exit();
}

$apiKey = mh_cfg('CLOUDLOADER_API_KEY');
$status = cloudbeez_status_handler::getStatus(true, false);
list($show_select_package, $show_waiting_info, $show_install_package, $show_update_package, $show_update_package_ok, $show_invalid_license, $show_api_error) = $status;

$subscriptions = cloudBeezApiConsumer::getSubscriptionInfo();



$lastSync = isset($_SESSION['cache_cloudbeez_status_handler_time']) ? $_SESSION['cache_cloudbeez_status_handler_time'] : null;
$isConnected = !empty($apiKey) && is_array($subscriptions) && !isset($subscriptions['error']) && !$show_api_error;
$domain = mh_cloudbeez_basedomain(HTTP_SERVER);

$lastSyncIso = $lastSync ? date('c', $lastSync) : null;
$syncTimeAgo = $lastSync ? date('H:i', $lastSync) : '';

// Collect installed modules grouped by area
$moduleAreas = [
    'mailbeez' => ['label' => \mh_lng('MAILBEEZ_LABEL_MAILBEEZ', 'MailBeez'), 'ver_key' => 'MAILBEEZ_INSTALLED_VERSIONS'],
    'filterbeez' => ['label' => \mh_lng('MAILBEEZ_LABEL_FILTERBEEZ', 'FilterBeez'), 'ver_key' => 'MAILBEEZ_FILTER_INSTALLED_VERSIONS'],
    'reportbeez' => ['label' => \mh_lng('MAILBEEZ_LABEL_REPORTBEEZ', 'ReportBeez'), 'ver_key' => 'MAILBEEZ_REPORT_INSTALLED_VERSIONS'],
    'configbeez' => ['label' => \mh_lng('MAILBEEZ_LABEL_CONFIGBEEZ', 'ConfigBeez'), 'ver_key' => 'MAILBEEZ_CONFIG_INSTALLED_VERSIONS'],
    'dashboardbeez' => ['label' => \mh_lng('MAILBEEZ_LABEL_DASHBOARDBEEZ', 'DashboardBeez'), 'ver_key' => 'MAILBEEZ_DASHBOARD_INSTALLED_VERSIONS'],
];

$groupedModules = [];
foreach ($moduleAreas as $area => $info) {
    $verList = mh_cfg($info['ver_key']);
    if (!$verList) continue;

    $entries = explode(';', $verList);
    foreach ($entries as $entry) {
        $parts = explode('|', $entry);
        $code = $parts[0] ?? '';
        $version = $parts[1] ?? '';
        $check = (int)($parts[2] ?? 0);

        if ($check > 0 && $code) {
            $groupedModules[$area]['label'] = $info['label'];
            $groupedModules[$area]['modules'][] = [
                'code' => $code,
                'version' => $version,
            ];
        }
    }
}

// Prepare Pro Package ResourceList items
list($select_package, $install_package, $update_package) = cloudbeez_status_handler::getActionUrls();

$proPackageItems = [];
if ($show_install_package || $show_update_package || $show_update_package_ok || $show_select_package) {
    $statusText = 'Unknown';
    $statusVariant = 'secondary';
    $action = null;

    if ($show_update_package_ok) {
        $statusText = \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_STATUS_UPTODATE', 'Up to date');
        $statusVariant = 'success';
        $action = [
            'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ACTION_REINSTALL', 'Re-install'),
            'url' => $install_package,
            'variant' => 'ghost',
            'icon' => Base::SVG_REFRESH
        ];
    } elseif ($show_update_package) {
        $statusText = \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_STATUS_UPDATE_AVAILABLE', 'Update available');
        $statusVariant = 'warning';
        $action = [
            'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ACTION_UPDATE', 'Update Now'),
            'url' => $update_package,
            'variant' => 'primary',
            'icon' => Base::SVG_ARROW_DOWN_SQUARE
        ];
    } elseif ($show_install_package) {
        $statusText = \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_STATUS_READY', 'Ready to install');
        $statusVariant = 'info';
        $action = [
            'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ACTION_INSTALL', 'Install Now'),
            'url' => $install_package,
            'variant' => 'primary',
            'icon' => Base::SVG_PLUS
        ];
    } elseif ($show_select_package) {
        $statusText = \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_STATUS_NO_PLAN', 'No Plan Selected');
        $statusVariant = 'secondary';
        $action = [
            'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ACTION_SELECT_PLAN', 'Select Plan'),
            'url' => $select_package,
            'variant' => 'primary',
            'icon' => Base::SVG_CHART_BAR
        ];
    }

    if ($statusText) {
        $proPackageItems[] = [
            'id' => 'pro_package',
            'label' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_PRO_PACKAGE_TITLE', 'MailBeez Pro Package'),
            'description' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_PRO_PACKAGE_DESC', 'Core premium functionality and modules'),
            'status' => $statusText,
            'status_variant' => $statusVariant,
            'action' => $action,
            'icon' => ['svg' => Base::SVG_GEAR, 'color' => 'brand', 'size' => 'md']
        ];
    }
}

ob_start();
?>

<?php if (!mh_get('partial')): ?>
<div x-data="{ license_tab: '<?= $pageTab ?>' }"
     @hashchange.window="if(location.hash) license_tab = location.hash.substring(1)">
    <?php
    $statusBadge = $isConnected ? Badge::render('success', \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_CONNECTED', 'Connected'), [
        'variant' => 'soft',
        'icon' => '<span class="h-2 w-2 rounded-full bg-green-500"></span>'
    ]) : Badge::render('error', \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_DISCONNECTED', 'Disconnected'), [
        'variant' => 'soft',
        'icon' => '<span class="h-2 w-2 rounded-full bg-red-500"></span>'
    ]);

    $headerRight = '<div class="flex items-center gap-3">';
    $headerRight .= '<div id="license-header-status">' . $statusBadge . '</div>';
    $headerRight .= Button::render(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_REFRESH_BUTTON', 'Refresh Connection'), [
        'variant' => 'outline',
        'size' => 'sm',
        'attrs' => [
            'command' => 'show-modal',
            'commandfor' => 'config-modal',
            'data-size' => 'md',
            'data-no-global-loader' => 'true',
            'data-no-local-loader' => 'true',
            'hx-get' => \Components\Router::url('license', ['op' => 'refresh_confirm', 'partial' => 1]),
            'hx-target' => '#config-modal-body',
            'hx-swap' => 'innerHTML',
        ],
    ]);
    $headerRight .= '</div>';

    echo PageHeader::render((string) \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_HEADING', 'License & Installation'), [
        'subtitle' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_SUBTITLE', 'Manage your MailBeez CloudLoader license and connected services.'),
        'right' => $headerRight
    ]);
    ?>
<?php endif; ?>

<?php if (mh_get('partial')): ?>
    <div id="license-header-status" hx-swap-oob="true">
        <?php
        echo $isConnected ? Badge::render('success', \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_CONNECTED', 'Connected'), [
            'variant' => 'soft',
            'icon' => '<span class="h-2 w-2 rounded-full bg-green-500"></span>'
        ]) : Badge::render('error', \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_DISCONNECTED', 'Disconnected'), [
            'variant' => 'soft',
            'icon' => '<span class="h-2 w-2 rounded-full bg-red-500"></span>'
        ]);
        ?>
    </div>
<?php endif; ?>

<div id="license-page-container"
     x-cloak
     class="space-y-6"
     hx-get="<?= Base::h($listUrl) ?>"
     hx-trigger="refresh"
     hx-swap="outerHTML"
     :hx-vals="JSON.stringify({license_tab: license_tab})">

    <?= Tabs::mobile('license_tab', $tabItems, ['ariaLabel' => \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_SELECT_TAB', 'Select license tab')]) ?>

    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-divider">
        <div class="hidden sm:block">
            <?= Tabs::desktopNavOnly('license_tab', $tabItems) ?>
        </div>
    </div>

    <div class="mt-4">
        <?php if ($show_api_error): ?>
            <div class="mb-6">
                <?= Notification::render(\mh_lng('MAILBEEZ_MAILHIVE_CLOUDLOADER_API_ERROR'), ['variant' => 'danger']) ?>
            </div>
        <?php endif; ?>

        <!-- Tab: License -->
        <div x-show="license_tab === 'license'" x-cloak class="space-y-6">
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
                <!-- Active Licenses Card -->
                <div class="@container lg:col-span-2 ">
                    <div class="flex items-start justify-between gap-4 ">
                        <div>
                            <p class="text-sm font-medium text-zinc-500"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ACTIVE_LICENSES', 'Active Licenses') ?></p>
                            <h2 class="mt-2 text-lg font-semibold text-zinc-900">
                                <?= is_array($subscriptions) ? count($subscriptions) : 0 ?> <?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_LICENSES_CONNECTED', 'Licenses connected') ?>
                            </h2>
                        </div>

                        <?php if ($isConnected): ?>
                            <?= Badge::render('success', \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_STATUS_OK', 'Active'), ['variant' => 'soft']) ?>
                        <?php endif; ?>
                    </div>

                    <div class="mt-1 grid grid-cols-1 gap-4 @md:grid-cols-2 ">
                        <?php if (is_array($subscriptions) && !empty($subscriptions)): ?>
                            <?php foreach ($subscriptions as $subscr):

//                                $expired = ($subscr['expires_in'] == -1);
                                $expired = ($subscr['expired'] == 1) || ((int)$subscr['expires_in'] === -1);
                                $status = $subscr['status']; // ACTIVE EXPIRED CANCELED PASTDUE
                                $isValid = $subscr['valid_license'] && !$expired;
                                $title = (mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_' . strtoupper($subscr['data']['title'])) ?
                                    mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_' . strtoupper($subscr['data']['title'])) : $subscr['data']['title']
                                );
                                echo LicenseCard::render([
                                    'title'          => $title,
                                    'subtitle'       => $subscr['data']['title'],
                                    'level'          => $subscr['data']['title'],
                                    'valid_until'    => $subscr['expiration_date'],
                                    'customer_limit' => number_format((int)$subscr['data']['max_customers'], 0, ',', '.'),
                                    'is_valid'       => $isValid,
                                    'status'         => $status,
                                ]);
                            endforeach; ?>
                        <?php else: ?>
                            <div class="col-span-full">
                                <?php if ($show_api_error): ?>
                                    <?= Notification::render(\mh_lng('MAILBEEZ_MAILHIVE_CLOUDLOADER_API_ERROR'), ['variant' => 'error']) ?>
                                <?php else: ?>
                                    <?= Notification::render(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_NO_SUBSCRIPTIONS', 'No active subscriptions found.'), ['variant' => 'info']) ?>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>


                <!-- Cloud Connection Card -->
                <div class="<?= Card::baseContainerClass(false, 'p-5 flex flex-col') ?>">
                    <p class="text-sm font-medium text-zinc-500"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_CLOUD_CONNECTION_TITLE', 'Cloud Connection') ?></p>
                    <h2 class="mt-2 text-lg font-semibold text-zinc-900"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_TEXT_TITLE', 'MailBeez Cloud') ?></h2>

                    <dl class="mt-5 space-y-3 text-sm flex-1">
                        <div class="flex justify-between gap-4">
                            <dt class="text-zinc-500"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_DOMAIN', 'Domain') ?></dt>
                            <dd class="font-medium text-zinc-900"><?= Base::h($domain) ?></dd>
                        </div>
                        <div class="flex justify-between gap-4">
                            <dt class="text-zinc-500"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_LAST_CHECK', 'Last check') ?></dt>
                            <dd class="font-medium text-zinc-900">
                                <?php if ($lastSyncIso): ?>
                                    <time datetime="<?= $lastSyncIso ?>" x-data="{ date: new Date('<?= $lastSyncIso ?>') }" x-timeago="date"><?= Base::h($syncTimeAgo) ?></time>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </dd>
                        </div>
                    </dl>

                    <div x-data="{ showInput: false }" class="mt-5">
                        <template x-if="!showInput">
                            <?= Button::render(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_CHANGE_API_KEY', 'Change API-Key'), [
                                    'variant' => 'primary',
                                    'fullWidth' => true,
                                    'attrs' => ['@click' => 'showInput = true']
                            ]) ?>
                        </template>
                        <template x-if="showInput">
                            <div class="flex gap-2">
                                <input type="text" name="api_key" id="api_key" value="<?= Base::h($apiKey) ?>"
                                       class="input flex-1 font-mono text-xs" placeholder="<?= Base::h(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_API_KEY_PLACEHOLDER', 'Paste your API key here')) ?>">
                                <?= Button::render(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_SAVE_KEY', 'Save'), [
                                        'variant' => 'primary',
                                        'attrs' => [
                                                'hx-post' => Router::url('license', ['op' => 'save_api_key', 'partial' => 1]),
                                                'hx-include' => '#api_key',
                                                'hx-target' => '#license-page-container',
                                                'hx-swap' => 'outerHTML'
                                        ]
                                ]) ?>
                                <?= Button::render('?', [
                                        'variant' => 'ghost',
                                        'attrs' => ['@click' => 'showInput = false']
                                ]) ?>
                            </div>
                        </template>
                    </div>
                </div>




            </div>

            <?php if (!empty($proPackageItems)): ?>
            <?php foreach ($proPackageItems as $it): ?>
                <div class="<?= Card::baseContainerClass(false, 'p-5') ?>">
                    <div class="flex items-center justify-between gap-4">
                        <div class="flex items-center gap-4">
                            <div class="flex h-11 w-11 items-center justify-center rounded-xl bg-blue-50 text-blue-600">
                                <?= Base::SVG_GEAR ?>
                            </div>
                            <div>
                                <h2 class="font-semibold text-zinc-900"><?= Base::h($it['label']) ?></h2>
                                <p class="text-sm text-zinc-500">
                                    <?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_PRO_PACKAGE_DESC', 'Premium features, automations and advanced modules.') ?>
                                </p>
                            </div>
                        </div>

                        <div class="flex items-center gap-3">
                            <?= Badge::render($it['status_variant'] ?? 'default', $it['status'], ['variant' => 'soft']) ?>
                            
                            <?php if ($it['action']): ?>
                                <?= Button::render($it['action']['label'], [
                                    'variant' => 'primary',
                                    'class' => 'bg-zinc-900 hover:bg-zinc-800 text-white',
                                    'attrs' => [
                                        'command' => 'show-modal',
                                        'commandfor' => 'config-modal',
                                        'data-title' => $it['action']['label'],
                                        'data-size' => 'full-margin',
                                        'data-url' => $it['action']['url'],
                                        'hx-target' => '#config-modal-body',
                                        'hx-swap' => 'innerHTML'
                                    ]
                                ]) ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php endif; ?>

        </div>

        <!-- Tab: Versions -->
        <div x-show="license_tab === 'versions'" x-cloak class="space-y-6">
            <div class="<?= Card::baseContainerClass(false, 'shadow-sm') ?>">
                <div class="border-b border-divider p-5">
                    <div class="flex items-center justify-between gap-4">
                        <div>
                            <h2 class="font-semibold text-zinc-900"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_INSTALLED_MODULES', 'Installed Modules') ?></h2>
                            <p class="mt-1 text-sm text-zinc-500">
                                <?php
                                $totalModules = 0;
                                foreach ($groupedModules as $info) $totalModules += count($info['modules']);
                                ?>
                                <?= $totalModules ?> <?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_MODULES_INSTALLED', 'modules installed') ?> - <?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_LAST_CHECK', 'last check') ?>
                                <?php if ($lastSyncIso): ?>
                                    <time datetime="<?= $lastSyncIso ?>" x-data="{ date: new Date('<?= $lastSyncIso ?>') }" x-timeago="date"><?= Base::h($syncTimeAgo) ?></time>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </p>
                        </div>

                        <?= Button::render(\mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_SEARCH_UPDATES', 'Search for updates'), [
                            'variant' => 'outline',
                            'size' => 'md',
                            'attrs' => [
                                'hx-get' => Router::url('license', ['op' => 'refresh', 'partial' => 1]),
                                'hx-target' => '#license-page-container',
                                'hx-swap' => 'outerHTML'
                            ]
                        ]) ?>
                    </div>
                </div>

                <div class="divide-y divide-zinc-100">
                    <?php foreach ($groupedModules as $area => $info): ?>
                        <div class="bg-zinc-50/50 px-5 py-2 text-xs font-bold text-zinc-400 uppercase tracking-wider">
                            <?= Base::h($info['label']) ?>
                        </div>
                        <?php foreach ($info['modules'] as $mod): ?>
                            <div class="flex items-center justify-between px-5 py-4 hover:bg-zinc-50/50 transition-colors">
                                <span class="font-medium text-zinc-900"><?= Base::h($mod['code']) ?></span>
                                <span class="rounded-md bg-zinc-100 px-2 py-1 text-xs text-zinc-600">v<?= Base::h($mod['version']) ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if ($show_waiting_info): ?>
               <?php
               echo Notification::render(\mh_lng('MAILBEEZ_MAILHIVE_CLOUDLOADER_WAIT_IPN', 'Your purchase is being processed. Please wait a few minutes and refresh.'), [
                   'variant' => 'warning'
               ]);
               ?>
            <?php endif; ?>

            <div class="mt-6 text-sm text-secondary bg-secondary/5 p-4 rounded-xl border border-divider">
               <h4 class="font-bold text-primary mb-2"><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ABOUT_TITLE', 'About MailBeez CloudLoader') ?></h4>
               <p><?= \mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_ABOUT_DESC', 'CloudLoader is the central mechanism to keep your MailBeez installation up-to-date and manage your premium subscriptions. It securely connects to the MailBeez Cloud to fetch the latest versions of your modules.') ?></p>
            </div>
        </div>
    </div>
</div>

<?php if (!mh_get('partial')): ?>
</div>
<?php endif; ?>

<?php
$content = ob_get_clean();

if (mh_get('partial')) {
    echo $content;
} else {
    echo layout($pageKey, $content);
}
