<?php
/**
 * Home Module - AJAX Handler
 *
 * Handles AJAX requests for the home dashboard.
 */

// Dispatcher
if (isset($_POST['acc']) && function_exists($_POST['acc'])) {
    $_POST['acc']();
}

/**
 * Gets dashboard statistics.
 */
function getStats(): void
{
    $response = _response(true);
    $log_type = 'error';
    $log_data = [];

    try {
        $es_index = getEsIndex();

        // Count users
        $usersQuery = json_decode(es_execute("/$es_index/_count?q=slm.type:user"), true);
        $users = $usersQuery['count'] ?? 0;

        // Count active users
        $activeQuery = json_decode(es_execute("/$es_index/_count?q=(slm.type:user)AND(status.keyword:active)"), true);
        $active = $activeQuery['count'] ?? 0;

        // Count items
        $itemsQuery = json_decode(es_execute("/$es_index/_count?q=slm.type:item"), true);
        $items = $itemsQuery['count'] ?? 0;

        $response = _response(false, '', [
            'users' => $users,
            'active' => $active,
            'items' => $items,
            'activity' => rand(10, 100) // Placeholder for activity
        ]);

        $log_type = 'success';

    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    } finally {
        $log_data['return'] = $response;
        addToLog($log_type, 'home', __FUNCTION__, $log_data);
    }

    exit(json_encode($response));
}
