<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

// add_stylesheet('css 구문', 출력순서); 숫자가 작을 수록 먼저 출력됨
add_stylesheet('<link rel="stylesheet" href="'.$search_skin_url.'/style.css">', 0);
?>

<form name="fsearch" onsubmit="return fsearch_submit(this);" method="get">
<input type="hidden" name="srows" value="<?php echo $srows ?>">
<fieldset id="sch_res_detail">
    <legend>상세검색</legend>
    <div class="sch_wr">
<!-- 기존 dslcub230428에서 수정한 코드{
        <?php echo $group_select ?>
        <script>document.getElementById("gr_id").value = "<?php echo $gr_id ?>";</script>
}기존코드끝-->

        <label for="sfl" class="sound_only" style="position: absolute;width: 0;height: 0;font-size: 0;line-height: 0;overflow: hidden;">검색조건</label>
        <select name="sfl" id="sfl" style="position: absolute;width: 0;height: 0;font-size: 0;line-height: 0;overflow: hidden;">
            <option value="wr_subject||wr_content||mb_id||wr_name||wr_datetime||wr_last||wr_ip"<?php echo get_selected($_GET['sfl'], "wr_subject||wr_content||mb_id||wr_name||wr_datetime||wr_last||wr_ip") ?>>통합검색</option>
            <option value="wr_subject"<?php echo get_selected($_GET['sfl'], "wr_subject") ?>>제목</option>
            <option value="wr_content"<?php echo get_selected($_GET['sfl'], "wr_content") ?>>내용</option>
            <option value="mb_id"<?php echo get_selected($_GET['sfl'], "mb_id") ?>>회원아이디</option>
            <option value="wr_name"<?php echo get_selected($_GET['sfl'], "wr_name") ?>>이름</option>
        </select>
        
        <label for="stx" class="sound_only">검색어<strong class="sound_only"> 필수</strong></label>
        <input type="text" name="stx" id="stx" value="<?php echo $text_stx ?>" class="frm_input" required  maxlength="20">
        <button type="submit" class="btn_submit" value="검색"><i class="fa fa-search" aria-hidden="true"></i></button>

        <script>
        function fsearch_submit(f)
        {
            if (f.stx.value.length < 2) {
                alert("검색어는 두글자 이상 입력하십시오.");
                f.stx.select();
                f.stx.focus();
                return false;
            }

            // 검색에 많은 부하가 걸리는 경우 이 주석을 제거하세요.
            var cnt = 0;
            for (var i=0; i<f.stx.value.length; i++) {
                if (f.stx.value.charAt(i) == ' ')
                    cnt++;
            }

            if (cnt > 1) {
                alert("빠른 검색을 위하여 공백은 한 개만 가능합니다.");
                f.stx.select();
                f.stx.focus();
                return false;
            }

            f.action = "";
            return true;
        }
        </script>
    </div>
<!-- 기존 dslcub230428에서 수정한 코드{
    <div class="switch_field chk_box">
        <input type="radio" value="or" <?php echo ($sop == "or") ? "checked" : ""; ?> id="sop_or" name="sop">
        <label for="sop_or"><span></span>OR</label>
        <input type="radio" value="and" <?php echo ($sop == "and") ? "checked" : ""; ?> id="sop_and" name="sop">
        <label for="sop_and"><span></span>AND</label>
    </div>
}기존코드 끝-->
</fieldset>
</form>


<div id="sch_result">
    <?php
    if ($stx) {
        if ($board_count) {
    ?>
    <!-- 검색 결과를 각 게시판별 버튼 그룹으로 표시 {-->
<style>
#sch_res_board_buttons {
        display: flex;
        overflow-x: auto;
        white-space: nowrap;
        padding: 10px;
        margin: 15px 0;
        /*border-bottom: 1px solid #f1f1f1;*/
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* Internet Explorer 10+ */
    }
    #sch_res_board_buttons::-webkit-scrollbar {
        display: none; /* Chrome, Safari, Opera */
    }
    #sch_res_board_buttons ul {
        list-style: none;
        padding: 0;
        margin: 0;
        display: inline-flex;
    }
    #sch_res_board_buttons ul li {
        margin-right: 8px;
        flex-shrink: 0;
    }
    #sch_res_board_buttons ul li a {
        display: inline-block;
        padding: 8px 16px;
        background: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 50px;
        text-decoration: none;
        color: #333;
        font-weight: 500;
        white-space: nowrap;
        transition: background 0.3s, color 0.3s, border-color 0.3s;
    }
    #sch_res_board_buttons ul li a:hover,
    #sch_res_board_buttons ul li a.btn_group.active {
        background: #ff8800;
        color: #fff;
        font-weight:600;
        border-color: #fff;
    }
#sch_res_board_buttons .profile_button {
        display: inline-block;
        padding: 8px 16px;
        background: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 50px;
        text-decoration: none;
        color: #333;
        font-weight: 500;
        white-space: nowrap;
        transition: background 0.3s, color 0.3s, border-color 0.3s;
        margin-right: 8px; /* Adds space between profile button and other elements */
    }
    #sch_res_board_buttons .profile_button:hover {
        background: #ff8800;
        color: #fff;
        font-weight:600;
        border-color: #fff;
    }
</style>

<div id="sch_res_board_buttons">
    <a href="#" id="profileButton" class="profile_button">프로필</a>
    <ul>
        <li><a href="?<?php echo $search_query ?>&amp;gr_id=<?php echo $gr_id ?>" class="btn_group <?php echo $sch_all ?>">전체게시판</a></li>
        
        <?php echo $str_board_list; // 각 게시판별 링크 ?>
    </ul>
</div>

<script>
    document.getElementById('profileButton').addEventListener('click', function(event) {
        event.preventDefault();
        let currentUrl = window.location.href;
        if (!currentUrl.includes('&profile=true')) {
            let newUrl = currentUrl.includes('?') ? currentUrl + '&profile=true' : currentUrl + '?profile=true';
            window.location.href = newUrl;
        }
    });
</script>

    <!-- }검색 결과를 각 게시판별 버튼 그룹으로 표시 -->

<!-- 프로필 검색 기능{ -->
<?php
$stx = isset($_GET['stx']) ? $_GET['stx'] : '';
$profile = isset($_GET['profile']) ? $_GET['profile'] : '';

// URL 인코딩이 되어 있는지 확인하고 디코딩
if (urldecode($stx) !== $stx) {
    $stx = urldecode($stx);
}

// '@' 또는 URL 인코딩된 '%40' 제거
$original_stx = $stx;
$stx = preg_replace('/^(@|%40)/', '', $stx);

// 영문+숫자 또는 영문으로만 구성된 경우 검사
if (preg_match('/^[a-zA-Z0-9]+$/', $stx)) {
    // '@'가 포함되어 있거나 `&profile=true`가 설정된 경우
    if (strpos($original_stx, '@') !== false || $profile === 'true') {
        // 실제 회원 확인
        $sql = "SELECT mb_id, mb_nick FROM {$g5['member_table']} WHERE mb_id = '{$stx}' LIMIT 1";
        $result = sql_query($sql);

        if ($row = sql_fetch_array($result)) {
            // 회원 정보가 확인되었을 경우
            $member_id = $row['mb_id'];
            $member_nick = $row['mb_nick'];

            // 회원 프로필 이미지 경로 설정
            $subdir = substr($member_id, 0, 2); // 회원 아이디의 앞 두 글자
            $profile_image_path = G5_DATA_PATH . "/member_image/{$subdir}/{$member_id}.gif";
            $profile_image_url = G5_DATA_URL . "/member_image/{$subdir}/{$member_id}.gif";

            // 이미지 존재 여부 확인
            if (!file_exists($profile_image_path)) {
                // 기본 이미지 경로 설정
                $profile_image_url = G5_IMG_URL . '/no_profile.gif'; // 기본 프로필 이미지 경로
            }

            // HTML 출력
            echo "
<a href='<?php echo G5_BBS_URL ?>/profile.php?mb_id={$member_id}'>
<div class='member-info' style='margin-top:10px; border:1px solid #eee; display: flex; align-items: center; padding: 10px 12px; font-family: Arial, sans-serif;'>
    <div class='profile-image' style='margin-right: 12px;'>
        <img src='{$profile_image_url}' alt='회원 프로필 이미지' style='width: 48px; height: 48px; border-radius: 50%; border: 1px solid #ccc;'>
    </div>
    <div style='display: flex; flex-direction: column;'>
        <p style='font-size: 16px; color: #333; margin: 0; font-weight: bold;'>{$member_nick}</p>
        <p style='font-size: 14px; color: #777; margin: 0;'>@{$member_id}</p>
    </div>
</div>
</a>
            ";
        } else {
            // 회원 정보가 없을 경우 메시지 출력 (옵션)
            echo "<p>프로필이 없습니다.</p>";
        }
    }
}
?>
    <?php
        } else {
     ?>
    <div class="empty_list">검색된 자료가 하나도 없습니다.</div>
    <?php } }  ?>
    <hr>
    <div class="list_01">
    <?php if ($stx && $board_count) { ?><section class="sch_res_list"><?php }  ?>
    <?php
    $k=0;
    for ($idx=$table_index, $k=0; $idx<count($search_table) && $k<$rows; $idx++) {
     ?>
        <h2><a href="<?php echo get_pretty_url($search_table[$idx], '', $search_query); ?>"><?php echo $bo_subject[$idx] ?> 게시판 내 결과</a></h2>
        <ul>
        <?php
        for ($i=0; $i<count($list[$idx]) && $k<$rows; $i++, $k++) {
            if ($list[$idx][$i]['wr_is_comment'])
            {
                $comment_def = '<span class="cmt_def"><i class="fa fa-commenting-o" aria-hidden="true"></i><span class="sound_only">댓글</span></span> ';
                $comment_href = '#c_'.$list[$idx][$i]['wr_id'];
            }
            else
            {
                $comment_def = '';
                $comment_href = '';
            }
         ?>
            <li class="sch_ccontent">
                <div  class="sch_res_title">
                    <a href="<?php echo $list[$idx][$i]['href'] ?><?php echo $comment_href ?>"><?php echo $comment_def ?><?php echo $list[$idx][$i]['subject'] ?></a>
                    <!-- <a href="<?php echo $list[$idx][$i]['href'] ?><?php echo $comment_href ?>" target="_blank" class="sch_res_new"><i class="fa fa-share-square-o" aria-hidden="true"></i><span class="sound_only">새창</span></a> -->
                </div>
                <!-- 0 : 본문 글자 중 어디서 부터 시작할 지, 0이 처음이라는 뜻, 100: 100자만큼 출력-->
                <p><?php echo mb_substr(strip_tags($list[$idx][$i]['content']), 0, 100); ?></p>
                <div class="sch_res_info">
                    <?php echo $list[$idx][$i]['name'] ?>
                    <span class="sch_datetime"><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $list[$idx][$i]['wr_datetime'] ?></span>
                </div>
            </li>
        <?php }  ?>
        </ul>
        <!--기존 코드{
        <div class="sch_more"><a href="<?php echo get_pretty_url($search_table[$idx], '', $search_query); ?>"><strong><?php echo $bo_subject[$idx] ?></strong> 결과 더보기</a></div>
        }기존코드-->
    <?php }  ?>

    <?php if ($stx && $board_count) {  ?></section><?php }  ?>
    </div>
    <?php echo $write_pages ?>
</div>
