<?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']) : '';

if (!isset($_POST['chk']) || !is_array($_POST['chk']) || count($_POST['chk']) < 1) {
    alert('처리할 항목을 하나 이상 선택하세요.');
}

$done = 0;
$fail = 0;
$item_ids = array();

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

    if ($act_button === '선택 자동재시도 중지' || $act_button === '선택 자동재시도 재개') {
        $row = sql_fetch("SELECT it_id FROM app_ikev2_provision_queue WHERE queue_id = '{$queue_id}' LIMIT 1");
        if ($row && isset($row['it_id'])) {
            $tmp_it_id = trim((string)$row['it_id']);
            if ($tmp_it_id !== '') {
                $item_ids[$tmp_it_id] = true;
            }
        }
        continue;
    }

    $ret = vpnlink_ikev2_attempt_queue($queue_id, 'admin_manual');
    if (!empty($ret['ok'])) {
        $done++;
    } else {
        $fail++;
    }
}

$status = isset($_POST['status']) ? trim((string)$_POST['status']) : '';
$it_id = isset($_POST['it_id']) ? trim((string)$_POST['it_id']) : '';
$item_type = isset($_POST['item_type']) ? trim((string)$_POST['item_type']) : '';
$show_unknown = isset($_POST['show_unknown']) ? (int)$_POST['show_unknown'] : 0;
$od_id = isset($_POST['od_id']) ? trim((string)$_POST['od_id']) : '';
$mb_id = isset($_POST['mb_id']) ? trim((string)$_POST['mb_id']) : '';
$sfl = isset($_POST['sfl']) ? trim((string)$_POST['sfl']) : '';
$stx = isset($_POST['stx']) ? trim((string)$_POST['stx']) : '';
$sort1 = isset($_POST['sort1']) ? trim((string)$_POST['sort1']) : 'next_retry_at';
$sort2 = isset($_POST['sort2']) ? trim((string)$_POST['sort2']) : 'asc';
$auto_refresh = isset($_POST['auto_refresh']) ? (int)$_POST['auto_refresh'] : 10;
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
if ($page < 1) $page = 1;

$qstr = 'status=' . urlencode($status)
      . '&it_id=' . urlencode($it_id)
      . '&item_type=' . urlencode($item_type)
      . '&show_unknown=' . (int)$show_unknown
      . '&od_id=' . urlencode($od_id)
      . '&mb_id=' . urlencode($mb_id)
      . '&sfl=' . urlencode($sfl)
      . '&stx=' . urlencode($stx)
      . '&sort1=' . urlencode($sort1)
      . '&sort2=' . urlencode($sort2)
    . '&auto_refresh=' . $auto_refresh
      . '&page=' . $page;

if ($act_button === '선택 자동재시도 중지' || $act_button === '선택 자동재시도 재개') {
    if (count($item_ids) < 1) {
        alert('선택한 항목에서 상품번호를 확인할 수 없습니다.', './ikev2_provision_monitor.php?' . $qstr);
    }

    $esc_item_ids = array();
    foreach (array_keys($item_ids) as $tmp_it_id) {
        $esc_item_ids[] = "'" . sql_escape_string($tmp_it_id) . "'";
    }
    $in_sql = implode(',', $esc_item_ids);

    if ($act_button === '선택 자동재시도 중지') {
        sql_query("UPDATE app_ikev2_provision_queue
                      SET is_retry_enabled = 0,
                          updated_at = NOW()
                    WHERE it_id IN ({$in_sql})
                      AND final_status <> 'success'", false);

        foreach (array_keys($item_ids) as $tmp_it_id) {
            vpnlink_ikev2_insert_control_history_by_item($tmp_it_id, 'retry_stopped', isset($member['mb_id']) ? $member['mb_id'] : '', isset($member['mb_name']) ? $member['mb_name'] : '');
        }

        $item_count = count($item_ids);
        $msg = '자동재시도 중지 완료: 상품번호 ' . $item_count . '건';
    } else {
        sql_query("UPDATE app_ikev2_provision_queue
                      SET is_retry_enabled = 1,
                          next_retry_at = NOW(),
                          updated_at = NOW()
                    WHERE it_id IN ({$in_sql})
                      AND final_status <> 'success'", false);

        foreach (array_keys($item_ids) as $tmp_it_id) {
            vpnlink_ikev2_insert_control_history_by_item($tmp_it_id, 'retry_resumed', isset($member['mb_id']) ? $member['mb_id'] : '', isset($member['mb_name']) ? $member['mb_name'] : '');
        }

        $item_count = count($item_ids);
        $msg = '자동재시도 재개 완료: 상품번호 ' . $item_count . '건';
    }
} else {
    $msg = '수동 재시도 완료: 성공 ' . $done . '건 / 실패 ' . $fail . '건';
}

alert($msg, './ikev2_provision_monitor.php?' . $qstr);
