<?php
if (php_sapi_name() !== 'cli') {
    echo "This script must be run from CLI.\n";
    exit(1);
}

$baseDir = dirname(__DIR__);
require_once $baseDir . '/_common.php';
require_once $baseDir . '/mylib/ikev2_provision.lib.php';

vpnlink_ikev2_create_tables();

$days = 7;
$limit = 100;
$onlyUnresolved = false;

foreach (array_slice($argv, 1) as $arg) {
    if (strpos($arg, '--days=') === 0) {
        $days = (int)substr($arg, 7);
    } elseif (strpos($arg, '--limit=') === 0) {
        $limit = (int)substr($arg, 8);
    } elseif ($arg === '--only-unresolved') {
        $onlyUnresolved = true;
    }
}

if ($days <= 0) {
    $days = 7;
}
if ($limit <= 0) {
    $limit = 100;
}
if ($limit > 2000) {
    $limit = 2000;
}

$since = date('Y-m-d H:i:s', time() - ($days * 86400));

$totalConflictRow = sql_fetch("SELECT COUNT(*) AS cnt
                                 FROM app_ikev2_id_conflict_history
                                WHERE created_at >= '" . sql_escape_string($since) . "'", false);
$totalConflictCount = (int)($totalConflictRow['cnt'] ?? 0);

$byServer = array();
$resServer = sql_query("SELECT server_ip, COUNT(*) AS cnt
                          FROM app_ikev2_id_conflict_history
                         WHERE created_at >= '" . sql_escape_string($since) . "'
                         GROUP BY server_ip
                         ORDER BY cnt DESC, server_ip ASC", false);
if ($resServer) {
    for ($i = 0; $row = sql_fetch_array($resServer); $i++) {
        $byServer[] = array(
            'server_ip' => trim((string)($row['server_ip'] ?? '')),
            'count' => (int)($row['cnt'] ?? 0)
        );
    }
}

$unresolvedWhere = "final_status <> 'success' AND (last_error = 'auto_order_user_scope_violation' OR last_error LIKE 'auto_order_user_scope_violation:%')";
$unresolvedCntRow = sql_fetch("SELECT COUNT(*) AS cnt FROM app_ikev2_provision_queue WHERE " . $unresolvedWhere, false);
$unresolvedCount = (int)($unresolvedCntRow['cnt'] ?? 0);

$recentResolved = array();
if (!$onlyUnresolved) {
    $resResolved = sql_query("SELECT conflict_id, created_at, od_id, it_id, server_ip, protocol, original_user_id, resolved_user_id, trigger_source
                                FROM app_ikev2_id_conflict_history
                               WHERE created_at >= '" . sql_escape_string($since) . "'
                               ORDER BY conflict_id DESC
                               LIMIT " . $limit, false);
    if ($resResolved) {
        for ($i = 0; $row = sql_fetch_array($resResolved); $i++) {
            $recentResolved[] = array(
                'conflict_id' => (int)($row['conflict_id'] ?? 0),
                'created_at' => trim((string)($row['created_at'] ?? '')),
                'od_id' => trim((string)($row['od_id'] ?? '')),
                'it_id' => trim((string)($row['it_id'] ?? '')),
                'server_ip' => trim((string)($row['server_ip'] ?? '')),
                'protocol' => trim((string)($row['protocol'] ?? '')),
                'original_user_id' => trim((string)($row['original_user_id'] ?? '')),
                'resolved_user_id' => trim((string)($row['resolved_user_id'] ?? '')),
                'trigger_source' => trim((string)($row['trigger_source'] ?? ''))
            );
        }
    }
}

$recentUnresolved = array();
$resUnresolved = sql_query("SELECT queue_id, updated_at, od_id, it_id, server_ip, protocol, vpn_user_id, fail_count, last_error
                              FROM app_ikev2_provision_queue
                             WHERE " . $unresolvedWhere . "
                             ORDER BY updated_at DESC, queue_id DESC
                             LIMIT " . $limit, false);
if ($resUnresolved) {
    for ($i = 0; $row = sql_fetch_array($resUnresolved); $i++) {
        $recentUnresolved[] = array(
            'queue_id' => (int)($row['queue_id'] ?? 0),
            'updated_at' => trim((string)($row['updated_at'] ?? '')),
            'od_id' => trim((string)($row['od_id'] ?? '')),
            'it_id' => trim((string)($row['it_id'] ?? '')),
            'server_ip' => trim((string)($row['server_ip'] ?? '')),
            'protocol' => trim((string)($row['protocol'] ?? '')),
            'vpn_user_id' => trim((string)($row['vpn_user_id'] ?? '')),
            'fail_count' => (int)($row['fail_count'] ?? 0),
            'last_error' => trim((string)($row['last_error'] ?? ''))
        );
    }
}

$output = array(
    'ok' => true,
    'generated_at' => date('c'),
    'window_days' => $days,
    'since' => $since,
    'summary' => array(
        'resolved_conflict_count' => $totalConflictCount,
        'unresolved_scope_conflict_count' => $unresolvedCount
    ),
    'by_server' => $byServer,
    'recent_resolved' => $recentResolved,
    'recent_unresolved' => $recentUnresolved
);

echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
