<?php
include_once('./_common.php');

header('Content-Type: application/json; charset=utf-8');

if($is_admin == 'super' || IS_PARTNER) {
    ;
} else {
    echo json_encode(array(
        'error' => '최고관리자 또는 판매자센터만 이용가능합니다.'
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function vpn_conn_norm($value) {
    $value = trim((string)$value);
    if($value === '') {
        return '';
    }

    if(function_exists('mb_strtolower')) {
        return mb_strtolower($value, 'UTF-8');
    }

    return strtolower($value);
}

function vpn_extract_conn_rows($jsonText) {
    $list = array();
    $rows = json_decode((string)$jsonText, true);
    if(!is_array($rows)) {
        return $list;
    }

    foreach ($rows as $row) {
        if(!is_array($row)) {
            continue;
        }

        $protocol = '';
        $server = '';
        $vpnId = '';

        foreach ($row as $k => $v) {
            if(strpos($k, 'Program__') === 0 && $protocol === '') {
                $protocol = trim((string)$v);
                continue;
            }

            if(preg_match('/^RemoteIP__\\d+$/', $k) && $server === '') {
                $server = trim((string)$v);
                continue;
            }

            if(preg_match('/_ID__\\d+$/', $k) && $vpnId === '') {
                $vpnId = trim((string)$v);
                continue;
            }
        }

        if($protocol === '' || $server === '' || $vpnId === '') {
            continue;
        }

        $normProtocol = vpn_conn_norm($protocol);
        $normServer = vpn_conn_norm($server);
        $normId = vpn_conn_norm($vpnId);

        if($normProtocol === '' || $normServer === '' || $normId === '') {
            continue;
        }

        $list[] = array(
            'protocol' => $protocol,
            'server' => $server,
            'vpn_id' => $vpnId,
            'norm_key' => $normProtocol . '|' . $normServer . '|' . $normId
        );
    }

    return $list;
}

$protocol = isset($_POST['protocol']) ? trim($_POST['protocol']) : '';
$server = isset($_POST['server']) ? trim($_POST['server']) : '';
$vpnId = isset($_POST['vpn_id']) ? trim($_POST['vpn_id']) : '';
$current_it_id = isset($_POST['it_id']) ? trim($_POST['it_id']) : '';
$owner_id = isset($_POST['owner_id']) ? trim($_POST['owner_id']) : '';

$normProtocol = vpn_conn_norm($protocol);
$normServer = vpn_conn_norm($server);
$normId = vpn_conn_norm($vpnId);

if($normProtocol === '' || $normServer === '' || $normId === '') {
    echo json_encode(array(
        'error' => '',
        'duplicate' => false,
        'items' => array(),
        'message' => ''
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$target_owner_id = $member['mb_id'];
if($owner_id !== '') {
    if($is_admin == 'super' || $owner_id === $member['mb_id']) {
        $target_owner_id = $owner_id;
    }
}

$mb_id_sql = sql_real_escape_string($target_owner_id);
$current_it_id_sql = sql_real_escape_string($current_it_id);

$where_current = '';
if($current_it_id_sql !== '') {
    $where_current = " and it_id <> '{$current_it_id_sql}' ";
}

$sql = " select it_id, it_name, it_spec_remote_sw
           from {$g5['g5_shop_item_table']}
          where (pt_id = '{$mb_id_sql}' or it_spec_partner_id = '{$mb_id_sql}')
            and it_spec_remote_sw <> ''
            {$where_current}
          order by it_update_time desc, it_time desc
          limit 500 ";

$result = sql_query($sql);
$items = array();
$targetKey = $normProtocol . '|' . $normServer . '|' . $normId;

while ($row = sql_fetch_array($result)) {
    $it_id = isset($row['it_id']) ? (string)$row['it_id'] : '';
    if($current_it_id !== '' && $it_id === (string)$current_it_id) {
        continue;
    }

    $connRows = vpn_extract_conn_rows(isset($row['it_spec_remote_sw']) ? $row['it_spec_remote_sw'] : '');
    foreach ($connRows as $connRow) {
        if(!isset($connRow['norm_key']) || $connRow['norm_key'] !== $targetKey) {
            continue;
        }

        $items[] = array(
            'it_id' => $it_id,
            'it_name' => isset($row['it_name']) ? $row['it_name'] : '',
            'protocol' => $connRow['protocol'],
            'server' => $connRow['server'],
            'vpn_id' => $connRow['vpn_id']
        );

        break;
    }

    if(count($items) >= 10) {
        break;
    }
}

$duplicate = (count($items) > 0);
$message = '';
if($duplicate) {
    $dups = array();
    foreach ($items as $item) {
        $it_id_text = isset($item['it_id']) ? $item['it_id'] : '';
        $it_name_text = isset($item['it_name']) ? trim($item['it_name']) : '';
        if($it_name_text !== '') {
            $dups[] = $it_id_text . ' (' . $it_name_text . ')';
        } else {
            $dups[] = $it_id_text;
        }
    }

    $message = '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이미 존재합니다. [품번/상품명: ' . implode(', ', $dups) . ']';
}

echo json_encode(array(
    'error' => '',
    'duplicate' => $duplicate,
    'items' => $items,
    'message' => $message
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
?>
