@extends('views.layouts.master')
<link rel="stylesheet" href="{{ asset('/themes/kbgolf/pro/resources/js/swiper/swiper-bundle.min.css') }}"/>
<script src="{{ asset('/themes/kbgolf/pro/resources/js/swiper/swiper-bundle.min.js') }}"></script>

@section('content')
<!-- page-title -->

@push('meta')
    {!! $seoHtml !!}
@endpush

<!-- main slice -->
<!-- main visual 시작 -->
<div class="main_visual">
	<div class="swiper">
	  <div class="swiper-wrapper">
		<!-- Slides -->
        @forelse($maMainSlider ?? [] as $widget)
		<div class="swiper-slide"  style="background-image:url({{ asset('/themes/kbgolf/pro/resources/images/main_visual.webp') }})">
			<div>
				<strong>
					신뢰할 수 있는 회원권 거래소
					<em>KB MEMBERSHIP CLUB</em>
				</strong>
				<p>{!! $widget['C6'] !!}</p>
			</div>
		</div>
        @empty
        @endforelse
	  </div>
	  <!-- If we need pagination -->
	  <div class="swiper-pagination"></div>
	</div>
</div>
<!--// main visual 끝 -->

<!-- 회원권 매매 신청 시작 -->
<div class="m_sell">
	<div class="container">
		<label>회원권 매매신청</label>
		<input type="text" id="membership-name" placeholder="회원권명">
		<button type="button" class="btn" onclick="contactForMembership()">상담신청하기</button>
	</div>
</div>
<!--// 회원권 매매 신청 끝 -->

<!-- 시세 시작 -->
<div class="m_quote">
	<div class="container">
		<ul class="tabs nav nav-tabs">
			<li class="active"><a data-toggle="tab" data-sise="golf" href="#" onclick="changeSiseList(this)">골프 시세</a></li>
			<li><a data-toggle="tab" href="#" data-sise="condo" onclick="changeSiseList(this)">콘도 시세</a></li>
			<li><a data-toggle="tab" href="#" data-sise="fitness" onclick="changeSiseList(this)">휘트니스 시세</a></li>
		</ul>
		<div class="tab-content">
			<!-- 골프 -->
			<div id="golf" class="tab-pane fade in active show">
				<div class="tb_res tb_vertical">
					<table cellspacing="0" cellpadding="0">
						<caption>단위: 만원</caption>
						<thead>
							<tr>
								<th>회원권명</th>
								<th>금일시세</th>
								<th>전일시세</th>
								<th>등락</th>
								<th>상담</th>
							</tr>
						</thead>
						<tbody id="sise-list"></tbody>
					</table>
				</div>
				<div class="btn_wrap">
					<button type="button" class="btn m_more sise" onclick="loadMoreSise()">더보기</button>
				</div>
			</div>
		</div>
	</div>
</div>
<!--// 시세 끝 -->

<!-- 유투브 시작 -->
<div class="m_youtube">
	<div class="container">
		<div class="tit_main">
			<em>KB Membership Club</em>
			<h2>YOUTUBE</h2>
		</div>
		<ul class="list">
            @forelse($mainYoutubeList['Page'] ?? [] as $mainYoutube)
			<li>
				<div class="img_box">
					<a href="{{ $mainYoutube['Pt1'] }}" target="_blak"></a>
					<iframe src="{{ $mainYoutube['Pt1'] }}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
				</div>
			</li>
            @empty
                <li>
                    <div class="img_box">데이터가 존재하지 않습니다.</div>
                </li>
            @endforelse
		</ul>
		<div class="btn_wrap">
			<button type="button" class="btn m_more youtube" onclick="loadMoreYoutube()">더보기</button>
		</div>
	</div>
</div>
<!--// 유투브 끝 -->

<!-- 블로그 시작 -->
<div class="m_blog">
	<div class="container">
		<div class="tit_main">
			<em>KB Membership Club</em>
			<h2>BLOG</h2>
		</div>
		<ul class="list">
            @forelse($mainBlogList['Page'] ?? [] as $mainBlog)
                <li>
                    <a href="{{ route('dbrbbs.details', [$mainBlog['PostCode'], $mainBlog['PostSlug']]) }}">
                        <h4 class="ellipsis_multi">{{ $mainBlog['PostTitle'] }}</h4>
                        <p class="ellipsis_multi">{!! strip_tags(mb_strimwidth($mainBlog['PostContents'], 0, 1500, '...')) !!}</p>
                    </a>
                </li>
            @empty
                <li>데이터가 존재하지 않습니다.</li>
            @endforelse
		</ul>
		<div class="btn_wrap">
			<button type="button" class="btn m_more blog" onclick="loadMoreBlog()">더보기</button>
		</div>
	</div>
</div>
<!--// 블로그 끝 -->

<script>
currentSiseType = 'golf';
$(document).ready(function() {
    // 필터링된 리스트를 렌더링하는 함수 호출
    changeSiseListByDefault(currentSiseType);
	$('.main-header').addClass('main_header');
	$('.main-header .logo img').attr("src", "/themes/kbgolf/pro/resources/images/logo_wh.png");
    console.log('mainSiseList : ', mainSiseList);
    console.log('mainYoutubeList : ', mainYoutubeList);
    console.log('mainBlogList : ', mainBlogList);

});

// siseType별로 tbody 생성
function changeSiseList(e) {
    // 다른 li태그 active class 제거
    $('.tabs li').removeClass('active');
    // 클릭한 태그의 li active class 추가
    $(e).parent().addClass('active');

    currentSiseType = $(e).attr('data-sise');
    var filteredSiseList = mainSiseList.filter(function(mainsise) {
        return mainsise['Pc1'].includes(currentSiseType);
    });
    console.log('filteredSiseList : ', filteredSiseList);
    renderMainSiseList(filteredSiseList);
}
// defalut 가져오기
function changeSiseListByDefault(currentSiseType) {
    console.log('default is golf');
    var filteredSiseList = mainSiseList.filter(function(mainsise) {
        return mainsise['Pc1'].includes(currentSiseType);
    });
    renderMainSiseList(filteredSiseList);
}

// tbody 생성
function renderMainSiseList(siseList){
    // console.log('siseList : ', siseList);
    var tbody = $('#sise-list');
    fluctuationClass='';
    tbody.empty();

    if(siseList.length === 0){
        tbody.html('<tr><td colspan="5">데이터가 존재하지 않습니다.</td></tr>');
        return;
    }

    siseList.forEach(function(sise){
        if (sise['fluctuation'] > 0) {
            fluctuationClass = 'up';
            fluctuationIcon = 'fa-sort-up';
        } else if (sise['fluctuation'] < 0) {
            fluctuationClass = 'down';
            fluctuationIcon = 'fa-sort-down';
        }

        var fluctuationText = sise['fluctuation'] !== 0 ?
        `<i class="fa-solid ${fluctuationIcon}"></i> ${number_format(Math.abs(sise['fluctuation']))}`
        : `${number_format(sise['fluctuation'])}`;

        var tr = $('<tr>');
        tr.html(`
            <td scope="row" data-label="${sise['PostTitle']}">${sise['PostTitle']}</td>
            <td data-label="${sise['Pc3']}">${number_format(sise['Pc3'])}</td>
            <td data-label="${sise['Pc4']}">${number_format(sise['Pc4'])}</td>
            <td data-label="등락" class="${fluctuationClass}">
                ${fluctuationText}
            </td>
            <td data-label="상담신청">
                <button type="button" class="btn consult-btn"
                    data-post-title="${sise['PostTitle']}"
                    data-pc1="${sise['Pc1']}"
                    onclick="window.location.href = '/contactus-custom/${sise['Pc1']}/${encodeURIComponent(sise['PostTitle'])}'">상담신청
                </button>
            </td>
        `);

        tbody.append(tr);
    })
}
    // 시세 더보기
    function loadMoreSise(){
        var offset = $('#sise-list tr').length;
        console.log('offset : ', offset);
        var limit = 3;

        $.ajax({
            url: '/load-more-sise',
            method: 'GET',
            data: { offset: offset, limit: limit, siseType: currentSiseType },
            success: function(response) {
                var siseList = response.Page;

                if (siseList!=null) {
                    appendMainSiseList(siseList);
                } else {
                    alert('더이상 데이터가 없습니다.')
                    $('.m_quote .btn_wrap .m_more').hide();
                }
            },
            error: function(error) {
                console.error('Error loading more sise:', error);
            }
        });
    }

    // 유튜브 더보기
    function loadMoreYoutube(){
        var offset = $('.m_youtube .list li').length;
        console.log('offset : ', offset);
        var limit = 12;

        $.ajax({
            url: '/load-more-youtube',
            method: 'GET',
            data: { offset: offset, limit: limit},
            success: function(response) {
                var youtubeList = response.Page;

                if (youtubeList!=null) {
                    appendMainYoutubeList(youtubeList);
                } else {
                    alert('더이상 데이터가 없습니다.')
                    $('.m_youtube .btn_wrap .m_more').hide();
                }
            },
            error: function(error) {
                console.error('Error loading more sise:', error);
            }
        });
    }

    // 블로그 더보기
    function loadMoreBlog() {
        var offset = $('.m_blog .list li').length;
        var limit = 12;

        $.ajax({
            url: '/load-more-blog',
            method: 'GET',
            data: { offset: offset, limit: limit },
            success: function(response) {
                console.log('response :', response);
                var blogList = response.Page;

                if (blogList!=null) {
                    appendMainBlogList(blogList);
                } else {
                    alert('더이상 데이터가 없습니다.');
                    $('.m_blog .btn_wrap .m_more').hide();
                }
            },
            error: function(error) {
                console.error('Error loading more blogs:', error);
            }
        });
    }

    // sise 더보기 list add
    function appendMainSiseList(siseList) {
        var tbody = $('#sise-list');

        siseList.forEach(function(sise) {
            if (sise['fluctuation'] > 0) {
                fluctuationClass = 'up';
                fluctuationIcon = 'fa-sort-up';
            } else if (sise['fluctuation'] < 0) {
                fluctuationClass = 'down';
                fluctuationIcon = 'fa-sort-down';
            } else {
                fluctuationClass = '';
                fluctuationIcon = '';
            }

            var fluctuationText = sise['fluctuation'] !== 0 ?
            `<i class="fa-solid ${fluctuationIcon}"></i> ${number_format(Math.abs(sise['fluctuation']))}`
            : `${number_format(sise['fluctuation'])}`;

            var tr = $('<tr>');
            tr.html(`
                <td scope="row" data-label="${sise['PostTitle']}">${sise['PostTitle']}</td>
                <td data-label="${sise['Pc3']}">${number_format(sise['Pc3'])}</td>
                <td data-label="${sise['Pc4']}">${number_format(sise['Pc4'])}</td>
                <td data-label="등락" class="${fluctuationClass}">
                    ${fluctuationText}
                </td>
                <td data-label="상담신청">
                    <button type="button" class="btn consult-btn"
                            data-post-title="${sise['PostTitle']}"
                            data-pc1="${sise['Pc1']}"
                            onclick="window.location.href = '/contactus-custom/${sise['Pc1']}/${encodeURIComponent(sise['PostTitle'])}'">상담신청
                    </button>
                </td>
            `);
            tbody.append(tr);
        });
    }

// youtube 더보기 list add
function appendMainYoutubeList(youtubeList) {
    var ul = $('.m_youtube .list');

    youtubeList.forEach(function(youtube) {
        var li = $('<li>');
        li.html(`
            <div class="img_box">
                <a href="${youtube['Pt1']}" target="_blank"></a>
                <iframe src="${youtube['Pt1']}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
            </div>
        `);
        ul.append(li);
    });
}

// blog 더보기 리스트 add
function appendMainBlogList(blogList) {
    var ul = $('.m_blog .list');

    blogList.forEach(function(blog) {
        var li = $('<li>');
        li.html(`
            <a href="/bbs/details/${blog['PostCode']}/${blog['PostSlug']}">
                <h4 class="ellipsis_multi">${blog['PostTitle']}</h4>
                <p class="ellipsis_multi">${stripTags(truncateText(blog['PostContents'], 1500))}</p>
            </a>
        `);
        ul.append(li);
    });
}

// 회원권명으로 상담신청
function contactForMembership(){
    var membershipName = $('#membership-name').val();
    var url = '{{ route('contactus-custom', ':membershipName') }}';
    url = url.replace(':membershipName', membershipName);
    // console.log('url :', url);
    window.location.href = url;
}

var swiper = new Swiper(".main_visual .swiper", {
	loop: true,
	autoplay: {
        delay: 5000,
        disableOnInteraction: false,
     },
    pagination: {
        el: ".swiper-pagination",
		clickable: true,
     },
});

// format 함수
function number_format(number) {
    return new Intl.NumberFormat().format(number);
}
// HTML 태그 제거
function stripTags(html) {
    return html.replace(/(<([^>]+)>)/gi, "");
}
// 글자수 maxLength
function truncateText(text, maxLength, suffix = '...') {
    if (text.length <= maxLength) {
        return text;
    }
    return text.substr(0, maxLength) + suffix;
}

const mainSiseList = {!! json_encode($mainSiseList['Page']) !!};
const mainYoutubeList = {!! json_encode($mainYoutubeList['Page']) !!};
const mainBlogList = {!! json_encode($mainBlogList['Page']) !!};

</script>
@endsection
