<?php // (2022.7.31, 차재복, Cha Jae Bok, http://www.ktword.co.kr) 
# 세션 스타트 (매 웹페이지 마다 필요)
	session_start();
# db 접속
	include_once "../base_utils/db_conn.php";
# 전달 변수
	$no = $_REQUEST['no'];
		if ( isset($_REQUEST['no']) and !empty($no) and !is_numeric($no) or $no<0 ) exit; // 해킹방지 (수치>0)
		$no = substr($no,0,10);  // 해킹 방지 (글자 수 제한)
//		if(empty($no)) $no=0; // 디폴트
	$id = $_REQUEST['id'];
		if ( isset($_REQUEST['id']) and !empty($id) and !is_numeric($id) or $id<0 ) exit; // 해킹방지 (수치>0)
# http 헤더 (json 포멧)
	header('content-type: application/json; charset=utf-8');
# 쿼리문 
	// id 아닌 no 일 경우에,
	if ( !empty($no) ) {
		$query = "select a.abbr,b.origin,b.in_no,b.type 
						from dict_anchor a left join embed b on a.no=b.no 
						where a.no=$no";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";}
		// 추출 내용 중 링크 주소 변경, 이미지 링크 삽입 등
		$i = 0;
		while ( $matched = mysqli_fetch_assoc($result) ) {
			// 초기값 설정
			if ($i == 0) $abbr = $matched['abbr'];
			// 이미지 연결 있다면, 해당 삽입
			if ( $matched['type'] =='g' ) 
				$abbr = str_replace("{[(".$matched['in_no'].")]}",
									"<img src='/img_data/".$matched['origin']."' border=0>",
									$abbr);
			$i = $i + 1;
		}
		// a 링크 변경
		$abbr = str_replace('abbr_view.php?m_temp1=','../yoyak/yoyak.php?no=',$abbr);
		// 만일, abbr 비었으면 리턴
		if (empty($abbr)) return;
		// mathjax 요소 있으면, display 경우에, div 감쌈
		$abbr = mathjax_div_wrap($abbr);
		// 단위 구절(항)마다 분리 추출하여 배열화시키는 함수 호출
		$substr = seperate($abbr); 
		// 외곽선 style
		$border = "border:1px gray dotted";
	// no 아닌 id 일 경우에,
	} else {
//		$query = "select detail as abbr from gubun_tree_v2 where id=$id";
		$query = "select id,sub_id,sub_name,detail from detail where id={$id} order by sub_id";
		$result = mysqli_query($dbi,$query);
			if (mysqli_errno($dbi)) { echo mysqli_errno($dbi)." : ".mysqli_error($dbi)."\n";}
		while ( $matched = mysqli_fetch_assoc($result) ) {
			$substr[$matched['sub_id']] = $matched['detail'];
			$subname[$matched['sub_id']] = $matched['sub_name'];
		}
		if (mysqli_num_rows($result) == 0) return;
		// 외곽선 style
		$border = "border:1px red solid";
	}
# html 구조로 상단 div(버튼),하단 div(내용출력)을 구분하여 출력하는 스트링
	$html = "";
	// 상단 번호 헤더 버튼 (일련의 버튼들)
	$html .= "<div >"; // style=''width:100%'
		// 매 소항목별로 버튼 처리
		if ( !empty($no) ) {
			$arr = $substr;
		} else {
			$arr = $subname;
		}
		
		foreach($arr as $key => $value) {
			// 폰트 강조
			if ( !empty($no) and $key == 1 ) {
				$bold = "font-weight:bold;";
			} else if ( empty($no) and $key == 1 ) {
				$bold = "font-weight:bold; color:red;";
			} else {
				$bold = '';
			}
			$html .= "<button class='sub_no_click' data-id='{$id}' data-no='{$no}' data-sub_no='{$key}' style='display:inline-block; float:left; {$bold}' >";
				// 각 항목별 첫 줄 항목 명칭 중 18개 문자 만 추출
				if ( !empty($no) ) {
					$str = strip_tags($value);
					$str = substr($str,0,strpos($str,PHP_EOL)+1);
					$html .=  mb_substr($str,0,18,'utf-8')." ... ";
					$html .= "   "; 
				} else {
					$html .= $value;
				}
			$html .= "</button> ";
		}
		// 제일 우측단에 전체보기 버튼 삽입
		$html .= "<button style='display:inline-block; float:left; border:1px gray dotted;'>";
			$html .= "<a href='../view/view.php?nav=2&no={$no}&id={$id}' style='color:blue;'>전체보기</a>";
		$html .= "</button>";
	$html .= "</div>";
	// 하단 내용 출력
	$html .= "<div class='sub_div' data-id='{$id}' data-no='{$no}' id='sub_div_{$id}_{$no}' style='padding-left:10px;clear:both; {$border}'><pre>";
		$html .= $substr[1];
	$html .= "</pre></div>";
	// 배열 첫 원소에 위의 html 구조 스트링 저장
	$substr[0] = $html;
# json 포멧으로 송출
	echo json_encode($substr,JSON_UNESCAPED_UNICODE);
	// json 포멧 : "1" : $substr[0], "1" : $substr[1], ... , "n" : $substr[n] 
	// $substr[0] : 버튼 리스트 <div> <button>(1번 항목 명)</button> ... </div>
	// $substr[1~n] : 각 번호 1~n 별 항목 세부내용 <div><pre> ... </pre></div>
?>
<?php
// 단위 구절마다 분리 추출하여 배열화시키는 함수
function seperate($abbr) {
	// 용어해설 설명 단위 구절(항) 마다 추출
	$rest = $abbr;
	$i=1;
	while ( ($pos = strpos($rest,PHP_EOL.($i+1).". ")) !== false ) {
		$first = ( $i==1 ? 0 : 2 );
		$len = $pos - $first + 1;
		$substr[$i] = trim(substr($rest, $first, $len)); 
		$rest = substr($rest, $pos);
		$substr[$i+1] = trim($rest);
		$i += 1;
	}
	if ($i <= 1) {
		$substr[1] = $rest;
	} 
	return $substr;
}
// mathjax 경우에, div inline-block 요소로 감쌈
function mathjax_div_wrap($abbr) {
	$right_bk = 0;
	while (($left_bk=strpos($abbr,'[#',$right_bk)) and ($right_bk=strpos($abbr,'#]',$left_bk))) {
			$left_str = substr($abbr,0,$left_bk);
			$right_str = substr($abbr,$right_bk+strlen('#]'));
			$math_word_len = $right_bk + strlen('#]') - $left_bk;
			$math_word = substr($abbr, $left_bk, $math_word_len);
			$replaced = "<div style='display:inline-block;'>".$math_word."</div>"; // ."sp={$sp},ln={$ln}"
			$abbr = $left_str . $replaced . $right_str;
			$right_bk = $left_bk + strlen($replaced);
	}
	return $abbr;
}
?>