<?php
$sub_menu = '400460';
include_once('./_common.php');

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

auth_check($auth[$sub_menu], 'w');
check_admin_token();

$act_button = isset($_POST['act_button']) ? trim((string)$_POST['act_button']) : '';
$server_name = isset($_POST['server_name']) ? trim((string)$_POST['server_name']) : '';
$limit = isset($_POST['limit']) ? (int)$_POST['limit'] : 5000;
if ($limit <= 0) {
    $limit = 5000;
}

if ($act_button !== '선택 강제동기화') {
    alert('잘못된 요청입니다.', './ikev2_server_compare.php?server_name=' . urlencode($server_name) . '&limit=' . $limit);
}

if ($server_name === '') {
    alert('서버 정보가 없습니다.', './ikev2_server_compare.php');
}

if (!isset($_POST['chk']) || !is_array($_POST['chk']) || count($_POST['chk']) < 1) {
    alert('동기화할 항목을 하나 이상 선택하세요.', './ikev2_server_compare.php?server_name=' . urlencode($server_name) . '&limit=' . $limit);
}

$success = 0;
$fail = 0;
$error_list = array();

for ($i = 0; $i < count($_POST['chk']); $i++) {
    $k = (int)$_POST['chk'][$i];
    $vpn_user_id = isset($_POST['vpn_user_id'][$k]) ? trim((string)$_POST['vpn_user_id'][$k]) : '';
    if ($vpn_user_id === '') {
        continue;
    }

    $ret = vpnlink_ikev2_force_sync_vpnid_member($server_name, $vpn_user_id);
    if (!empty($ret['ok'])) {
        $success++;
        continue;
    }

    $fail++;
    $error = isset($ret['error']) ? trim((string)$ret['error']) : 'sync_failed';
    $error_list[] = $vpn_user_id . ':' . $error;
}

$msg = '강제동기화 완료: 성공 ' . $success . '건 / 실패 ' . $fail . '건';
if ($fail > 0 && count($error_list) > 0) {
    $msg .= '\n실패사유: ' . implode(', ', array_slice($error_list, 0, 5));
}

alert($msg, './ikev2_server_compare.php?server_name=' . urlencode($server_name) . '&limit=' . $limit);
