<?php

if (!defined('WHMCS')) {
    die('This file cannot be accessed directly');
}

use WHMCS\Database\Capsule;

/**
 * Copy this file to WHMCS includes/hooks/hexagamecloud.php
 */
add_hook('DailyCronJob', 1, function () {
    $rows = Capsule::table('tbladdonmodules')
        ->where('module', 'hexagamecloud')
        ->pluck('value', 'setting');

    $apiUrl = trim((string) ($rows['api_url'] ?? ''));
    $integrationId = trim((string) ($rows['integration_id'] ?? ''));
    $apiSecret = trim((string) ($rows['api_secret'] ?? ''));

    if ($apiUrl === '' || $integrationId === '' || $apiSecret === '') {
        return;
    }

    require_once ROOTDIR . '/modules/addons/hexagamecloud/lib/ApiClient.php';
    require_once ROOTDIR . '/modules/addons/hexagamecloud/lib/ModuleStorage.php';
    require_once ROOTDIR . '/modules/addons/hexagamecloud/lib/EventPoller.php';

    try {
        $client = new HexaGameCloudAddonApiClient($apiUrl, $integrationId, $apiSecret);
        $storage = new HexaGameCloudModuleStorage();
        $limit = (int) ($rows['event_poll_limit'] ?? 50);
        $poller = new HexaGameCloudEventPoller($client, $storage, max(1, min($limit, 100)));
        $poller->pollAndAcknowledge();

        if (!empty($rows['auto_reconcile'])) {
            $client->reconcileAll(['dryRun' => true]);
        }
    } catch (Throwable $exception) {
        logActivity('HexaGameCloud cron poll failed: ' . $exception->getMessage());
    }
});
