<?php
require_once __DIR__ . '/../../functions/security.php';

$tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? (defined('TENANT_URL') ? TENANT_URL : ''));
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

require_once __DIR__ . '/log_functions.php';

if (!headers_sent()) {
    header('Content-Type: application/json; charset=utf-8');
}

if (function_exists('enrep_require_admin')) {
    enrep_require_admin();
}

if (!enrep_log_is_super_admin()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Super admin access required']);
    exit;
}

$action = trim((string)($_POST['action'] ?? ''));

if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id < 1) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid log entry']);
        exit;
    }

    echo json_encode(['ok' => enrep_log_delete($id), 'id' => $id]);
    exit;
}

if ($action === 'clear_category') {
    $category = trim((string)($_POST['category'] ?? ''));
    if ($category === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid category']);
        exit;
    }

    echo json_encode(['ok' => enrep_log_clear_category($category), 'category' => $category]);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid action']);
