<?php
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    echo 'forbidden';
    exit;
}

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

include_once(__DIR__ . '/../_common.php');
include_once(G5_PATH . '/lib/etc.lib.php');
include_once(G5_PATH . '/mylib/ikev2_provision.lib.php');

$opts = getopt('', array('apply', 'limit::', 'od_id::'));
$applyMode = isset($opts['apply']);
$limit = isset($opts['limit']) ? (int)$opts['limit'] : 100;
if ($limit <= 0) {
    $limit = 100;
}
if ($limit > 1000) {
    $limit = 1000;
}
$onlyOdId = isset($opts['od_id']) ? trim((string)$opts['od_id']) : '';

$where = array();
$where[] = "q.final_status <> 'success'";
$where[] = "(q.last_error LIKE '%payload_invalid_json%' OR q.last_error = 'decrypt_password_failed')";
if ($onlyOdId !== '') {
    $where[] = "q.od_id = '" . sql_escape_string($onlyOdId) . "'";
}

$sql = "SELECT DISTINCT q.od_id
          FROM app_ikev2_provision_queue q
          LEFT JOIN {$g5['g5_shop_order_table']} o ON o.od_id = q.od_id
         WHERE " . implode(' AND ', $where) . "
         ORDER BY q.updated_at DESC, q.queue_id DESC
         LIMIT " . $limit;

$res = sql_query($sql, false);
$targets = array();
if ($res) {
    while ($row = sql_fetch_array($res)) {
        $odId = isset($row['od_id']) ? trim((string)$row['od_id']) : '';
        if ($odId !== '') {
            $targets[] = $odId;
        }
    }
}

$result = array(
    'ok' => true,
    'mode' => $applyMode ? 'apply' : 'dry-run',
    'target_count' => count($targets),
    'targets' => $targets,
    'processed' => 0,
    'requeue_ok' => 0,
    'requeue_fail' => 0,
    'details' => array(),
    'ts' => date('Y-m-d H:i:s')
);

if ($applyMode) {
    foreach ($targets as $odId) {
        $ret = vpnlink_ikev2_queue_order($odId, 'batch_requeue_after_secret_rotate');
        $isOk = (!empty($ret['ok']) && (int)$ret['attempt_fail'] === 0);

        $result['processed']++;
        if ($isOk) {
            $result['requeue_ok']++;
        } else {
            $result['requeue_fail']++;
        }

        $result['details'][] = array(
            'od_id' => $odId,
            'ok' => !empty($ret['ok']),
            'queued_count' => isset($ret['queued_count']) ? (int)$ret['queued_count'] : 0,
            'attempt_success' => isset($ret['attempt_success']) ? (int)$ret['attempt_success'] : 0,
            'attempt_fail' => isset($ret['attempt_fail']) ? (int)$ret['attempt_fail'] : 0,
            'error' => isset($ret['error']) ? (string)$ret['error'] : ''
        );
    }
}

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