<?php
// usage:
//   php __CRON/cron_ikev2_extend_sync_trace_cli.php --order_no=2026041712452889
//   php __CRON/cron_ikev2_extend_sync_trace_cli.php --od_id=2026041712452889
//   php __CRON/cron_ikev2_extend_sync_trace_cli.php --order_no=... --od_id=... --tail=300

@chdir(__DIR__ . '/..');

include_once(__DIR__ . '/../_common.php');

function cli_arg_value($argv, $key, $default = '')
{
    $prefix = '--' . $key . '=';
    foreach ($argv as $arg) {
        if (strpos((string)$arg, $prefix) === 0) {
            return trim((string)substr((string)$arg, strlen($prefix)));
        }
    }
    return $default;
}

function trace_table_exists($tableName)
{
    $tableName = trim((string)$tableName);
    if ($tableName === '') {
        return false;
    }

    $safe = str_replace('`', '', $tableName);
    $row = sql_fetch("SHOW TABLES LIKE '" . sql_escape_string($safe) . "'", false);
    return is_array($row) && !empty($row);
}

function trace_table_has_column($tableName, $columnName)
{
    $tableName = trim((string)$tableName);
    $columnName = trim((string)$columnName);
    if ($tableName === '' || $columnName === '') {
        return false;
    }

    $safeTable = str_replace('`', '', $tableName);
    $safeCol = str_replace('`', '', $columnName);
    $row = sql_fetch("SHOW COLUMNS FROM `{$safeTable}` LIKE '" . sql_escape_string($safeCol) . "'", false);
    return is_array($row) && !empty($row);
}

function trace_match_log_lines($filePath, $needles, $tail = 200)
{
    $out = array(
        'file' => $filePath,
        'exists' => is_file($filePath),
        'readable' => is_readable($filePath),
        'matched_count' => 0,
        'lines' => array(),
    );

    if (!$out['exists'] || !$out['readable']) {
        return $out;
    }

    $all = @file($filePath, FILE_IGNORE_NEW_LINES);
    if (!is_array($all)) {
        return $out;
    }

    $tail = (int)$tail;
    if ($tail < 1) {
        $tail = 200;
    }
    if ($tail > 2000) {
        $tail = 2000;
    }

    $start = max(0, count($all) - $tail);
    $segment = array_slice($all, $start);

    $matched = array();
    foreach ($segment as $i => $line) {
        $lineText = (string)$line;
        $ok = false;
        foreach ($needles as $needle) {
            $needle = trim((string)$needle);
            if ($needle !== '' && strpos($lineText, $needle) !== false) {
                $ok = true;
                break;
            }
        }
        if ($ok) {
            $matched[] = array(
                'line_no' => $start + $i + 1,
                'text' => $lineText,
            );
        }
    }

    $out['matched_count'] = count($matched);
    $out['lines'] = $matched;
    return $out;
}

$orderNo = cli_arg_value($argv, 'order_no', '');
$odId = cli_arg_value($argv, 'od_id', '');
$tail = (int)cli_arg_value($argv, 'tail', '250');

if ($orderNo === '' && $odId === '') {
    echo json_encode(array(
        'ok' => false,
        'error' => 'order_no 또는 od_id 중 하나는 필요합니다.',
        'usage' => array(
            'php __CRON/cron_ikev2_extend_sync_trace_cli.php --order_no=2026041712452889',
            'php __CRON/cron_ikev2_extend_sync_trace_cli.php --od_id=2026041712452889',
            'php __CRON/cron_ikev2_extend_sync_trace_cli.php --order_no=... --od_id=... --tail=300',
        ),
        'ts' => date('Y-m-d H:i:s')
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
    exit(1);
}

$needles = array();
if ($orderNo !== '') {
    $needles[] = $orderNo;
}
if ($odId !== '') {
    $needles[] = $odId;
}
$needles[] = 'approve_remote_sync';
$needles[] = 'sync_error';
$needles[] = 'sync_ok';

$basePath = defined('G5_PATH') ? G5_PATH : dirname(__DIR__);
$logTargets = array(
    $basePath . '/mylib/data/strongswan_profile_extended_order_debug.log',
    $basePath . '/mylib/data/ikev2_provision.log',
    $basePath . '/IKEv2SellerOffice4U/logs/admin_actions.log',
);

$logs = array();
foreach ($logTargets as $logFile) {
    $logs[] = trace_match_log_lines($logFile, $needles, $tail);
}

$db = array(
    'vpn_extend_orders' => array(),
    'shop_cart' => array(),
    'shop_item' => array(),
    'vpnid_list' => array(),
);

if (trace_table_exists('vpn_extend_orders')) {
    if ($orderNo !== '') {
        $db['vpn_extend_orders'][] = sql_fetch(
            "SELECT * FROM vpn_extend_orders WHERE order_no='" . sql_escape_string($orderNo) . "' LIMIT 1",
            false
        );
    }

    if ($odId !== '') {
        $res = sql_query(
            "SELECT * FROM vpn_extend_orders WHERE memo LIKE '%" . sql_escape_string($odId) . "%' ORDER BY id DESC LIMIT 20",
            false
        );
        if ($res) {
            while ($row = sql_fetch_array($res)) {
                if (is_array($row)) {
                    $db['vpn_extend_orders'][] = $row;
                }
            }
        }
    }

    $db['vpn_extend_orders'] = array_values(array_filter($db['vpn_extend_orders'], 'is_array'));
}

$cartTable = isset($g5['g5_shop_cart_table']) ? (string)$g5['g5_shop_cart_table'] : '';
$itemTable = isset($g5['g5_shop_item_table']) ? (string)$g5['g5_shop_item_table'] : '';

if ($odId !== '' && $cartTable !== '' && trace_table_exists($cartTable)) {
    $res = sql_query(
        "SELECT * FROM {$cartTable} WHERE od_id='" . sql_escape_string($odId) . "' ORDER BY ct_id DESC LIMIT 30",
        false
    );
    if ($res) {
        while ($row = sql_fetch_array($res)) {
            if (is_array($row)) {
                $db['shop_cart'][] = $row;
            }
        }
    }
}

if (!empty($db['shop_cart']) && $itemTable !== '' && trace_table_exists($itemTable)) {
    $seenItem = array();
    foreach ($db['shop_cart'] as $cartRow) {
        $itId = isset($cartRow['it_id']) ? trim((string)$cartRow['it_id']) : '';
        if ($itId === '' || isset($seenItem[$itId])) {
            continue;
        }
        $seenItem[$itId] = true;
        $row = sql_fetch(
            "SELECT * FROM {$itemTable} WHERE it_id='" . sql_escape_string($itId) . "' LIMIT 1",
            false
        );
        if (is_array($row)) {
            $db['shop_item'][] = $row;
        }
    }
}

if (trace_table_exists('vpnid_list')) {
    if ($odId !== '' && trace_table_has_column('vpnid_list', 'od_id')) {
        $res = sql_query(
            "SELECT * FROM vpnid_list WHERE od_id='" . sql_escape_string($odId) . "' ORDER BY no DESC LIMIT 20",
            false
        );
        if ($res) {
            while ($row = sql_fetch_array($res)) {
                if (is_array($row)) {
                    $db['vpnid_list'][] = $row;
                }
            }
        }
    }

    if (empty($db['vpnid_list']) && !empty($db['shop_cart'])) {
        $seenItName = array();
        foreach ($db['shop_cart'] as $cartRow) {
            $itId = isset($cartRow['it_id']) ? trim((string)$cartRow['it_id']) : '';
            if ($itId === '') {
                continue;
            }
            $itName = 'VPN-' . $itId;
            if (isset($seenItName[$itName])) {
                continue;
            }
            $seenItName[$itName] = true;

            $res = sql_query(
                "SELECT * FROM vpnid_list WHERE it_name='" . sql_escape_string($itName) . "' ORDER BY no DESC LIMIT 20",
                false
            );
            if ($res) {
                while ($row = sql_fetch_array($res)) {
                    if (is_array($row)) {
                        $db['vpnid_list'][] = $row;
                    }
                }
            }
        }
    }
}

$out = array(
    'ok' => true,
    'query' => array(
        'order_no' => $orderNo,
        'od_id' => $odId,
        'tail' => $tail,
    ),
    'version_hint' => 'strongswan_profile_extended_order.php?vcheck=1',
    'logs' => $logs,
    'db' => $db,
    'summary' => array(
        'log_hits' => array(
            'extended_debug' => isset($logs[0]['matched_count']) ? (int)$logs[0]['matched_count'] : 0,
            'provision_log' => isset($logs[1]['matched_count']) ? (int)$logs[1]['matched_count'] : 0,
            'ikev2_admin_actions' => isset($logs[2]['matched_count']) ? (int)$logs[2]['matched_count'] : 0,
        ),
        'db_hits' => array(
            'vpn_extend_orders' => count($db['vpn_extend_orders']),
            'shop_cart' => count($db['shop_cart']),
            'shop_item' => count($db['shop_item']),
            'vpnid_list' => count($db['vpnid_list']),
        ),
    ),
    'ts' => date('Y-m-d H:i:s')
);

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