<?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' => '최고관리자 또는 판매자센터만 이용가능합니다.'
    ));
    exit;
}

$nickname = isset($_POST['it_spec_mgr_nickname']) ? trim($_POST['it_spec_mgr_nickname']) : '';
$current_it_id = isset($_POST['it_id']) ? trim($_POST['it_id']) : '';
$owner_id = isset($_POST['owner_id']) ? trim($_POST['owner_id']) : '';

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

$nickname_sql = sql_real_escape_string($nickname);

$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
           from {$g5['g5_shop_item_table']}
                    where (pt_id = '{$mb_id_sql}' or it_spec_partner_id = '{$mb_id_sql}')
            and it_spec_mgr_nickname = '{$nickname_sql}'
            {$where_current}
          order by it_update_time desc, it_time desc
          limit 10 ";

$result = sql_query($sql);
$items = array();
while ($row = sql_fetch_array($result)) {
	if($current_it_id !== '' && (string)$row['it_id'] === (string)$current_it_id) {
		continue;
	}
    $items[] = array(
        'it_id' => $row['it_id'],
        'it_name' => $row['it_name']
    );
}

$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 = '중복된 관리컴퓨터별명입니다. [이미 존재하는 품번/상품명: ' . implode(', ', $dups) . ']';
}

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