@extends('views.layouts.master')
<!-- Flatpickr CSS -->

<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>


<!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/moment/min/moment.min.js"></script> -->
@section('content')
<!-- page-title -->

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

<!-- popup  -->
<div id="dabory-banner"></div>

<!-- 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($widget['C4']) }})">
                <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>
        @php date_default_timezone_set('Asia/Seoul'); $today = date('Y-m-d'); @endphp
        <div class="tabs">
            <input type="text" id="search_date" readonly>
        </div>

		<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" 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">
        @for ($i = 0; $i < 3; $i++)
                @foreach (['golf', 'condo', 'fitness'] as $type)
                    @if(isset($youtubeTypes['Page'][$type][$i]))
                        @php
                            $mainYoutube = $youtubeTypes['Page'][$type][$i];
                            $href = '';
                            if($mainYoutube){
                                $src = $mainYoutube['Pt1'];
                                $parts = explode('embed/', $src);
                                if(count($parts) == 2) {
                                    $href = $parts[0].'watch?v='.$parts[1];
                                }
                            }
                        @endphp
                        <li data-category="{{ $type }}">
                            <div class="img_box">
                                <a href="{{ $href }}" target="_blank"></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>
                    @else
                        <li>
                            <div class="img_box">{{ $type }}유튜브</div>
                        </li>
                    @endif
                @endforeach
            @endfor
        </ul>
		<div class="btn_wrap">
			<button type="button" class="btn m_more" 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">
            @for ($i = 0; $i < 3; $i++)
                @foreach (['golf', 'condo', 'fitness'] as $type)
                    @if(isset($blogTypes['Page'][$type][$i]))
                        @php
                            $mainBlog = $blogTypes['Page'][$type][$i];
                            $href = $mainBlog['Pt1'];
                            $date = DateTime::createFromFormat('Ymd', $mainBlog['OfficialDate']);
                            $formattedDate = $date->format('Y.m.d');
                        @endphp
                        <li data-category="{{ $type }}">
                            <!-- <a href="{{ route('dbrbbs.details', [$mainBlog['PostCode'], $mainBlog['PostSlug']]) }}"> -->
                            <a href="{{ $href }}" target="_blank">
                                <div class="img_box">
									<img src="{{ asset($mainBlog['TurboThumb']) }}"class="w-md-50" alt="blog">
								</div>
                                <div class="conts_box">
									<!-- <h4 class="ellipsis">{!! strip_tags(mb_strimwidth($mainBlog['PostTitle'], 0, 25, '...')) !!}</h4>
									<p class="ellipsis_multi desc">{!! strip_tags(mb_strimwidth($mainBlog['PostContents'], 0, 550, '...')) !!}</p> -->
									<p class="date">{{ $formattedDate }}</p>
								</div>
                            </a>
                        </li>
                    @else
                        <li>
                            <div class="img_box" style="display:none">데이터가 존재하지 않습니다.</div>
                        </li>
                    @endif
                @endforeach
            @endfor
		</ul>
		<div class="btn_wrap">
			<button type="button" class="btn m_more blog" onclick="loadMoreBlog()">더보기</button>
		</div>
	</div>
</div>
<!--// 블로그 끝 -->

@push('js')
<script src="/dabory/js/widget.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/ko.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" />
<script>
currentSiseType = 'golf';
$(document).ready(function() {
    $('#search_date').flatpickr({
        dateFormat: 'Y-m-d', // 날짜 및 시간 형식 설정 (예: 2023-09-12 15:30)
		defaultDate: 'today',    // 초기 날짜 설정 (현재 날짜와 시간)
		locale: 'ko',            // 한국어로 지역화
        disableMobile: true,

		// onOpen: function(selectedDates, dateStr, instance) {
		// 	console.log('test');
		// },
		// onClose: function(selectedDates, dateStr, instance) {
		// 	// 위젯이 닫힐 때 실행할 코드
		// },
		// onChange: function(selectedDates, dateStr, instance) {
		// 	console.log('change');
		// },
	});


    @if (session()->get('ConnectionDevice'))
        const connectionDevice = "{{ session()->get('ConnectionDevice') }}";
    @endif

    $.fn.widget.loadModule(function () {
        const bannerWidth = (connectionDevice === 'mobile') ? 300 : 500;
        $('#dabory-banner').bannerPopup({
            width: bannerWidth,
            hide: false,
            connectionDevice : connectionDevice
        })
        $('#dabory-banner').find('.dabory-bannermanager').show()
    })

    const cook = $.cookie('multi-popup');
        if (cook  === 'ok') {
            $('.main_notice_pop').hide()
        }
        else {
            $('.main_notice_pop').show()
        }

        // 닫기버튼 클릭 이벤트
        $('.pop_cls').click(function () {
            $(this).parent('.main_notice_pop').fadeOut();

            // 오늘하루 보지않기 체크 확인
            if ($("input:checkbox[name=today_close1]").is(":checked") == true) {
                $.cookie('multi-popup', 'ok', { expires: 1, path: '/' });
            }

            // name으로 해당 팝업창 닫기
            $(this).parent("div[name=" + 'popup1' + "]").fadeOut();
        })

    function adjustListForMobile() {
        if (connectionDevice == 'mobile') { // mobile
            if($('.m_youtube .list li')){
                showLimitedItemsForCategory('golf', 1, $('.m_youtube .list li[data-category="golf"]'));
                showLimitedItemsForCategory('condo', 1, $('.m_youtube .list li[data-category="condo"]'));
                showLimitedItemsForCategory('fitness', 1, $('.m_youtube .list li[data-category="fitness"]'));
            }
            if($('.m_blog .list li')){
                showLimitedItemsForCategory('golf', 1, $('.m_blog .list li[data-category="golf"]'));
                showLimitedItemsForCategory('condo', 1, $('.m_blog .list li[data-category="condo"]'));
                showLimitedItemsForCategory('fitness', 1, $('.m_blog .list li[data-category="fitness"]'));
            }
            // $('.flatpickr-input').attr('type', 'text');
        } else {
            $('.list li').show(); // PC
        }
    }

    function showLimitedItemsForCategory(category, limit, $items) {
        $items.each(function(index) {
            if (index >= limit) {
                $(this).hide();
            }
        });
    }

    $(window).resize(adjustListForMobile);
    adjustListForMobile();

    changeSiseListByDefault(currentSiseType);
	$('.main-header').addClass('main_header');
	$('.main-header .logo img').attr("src", "/themes/kbgolf/pro/resources/images/logo_wh.png");
});

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

    currentSiseType = $(e).attr('data-sise');

    if(currentSiseType === 'golf'){
        if(!mainSiseList || mainSiseList.length ===0){
            var tbody = $('#sise-list');
            tbody.html('<tr><td colspan="5">회원권이 존재하지 않습니다.</td></tr>');
            return;
        }else{
            var filteredSiseList = mainSiseList.filter(function(mainsise) {
                return mainsise['Pc5'].includes(currentSiseType);
            });
        }
    }else{
        if(!filteredSiseList || filteredSiseList.length === 0){
            let date = document.getElementById('search_date').value;
            var monday = formatDate(date);
            // console.log('monday : ', monday);
            findMondayData(monday);
        }
    }

    renderMainSiseList(filteredSiseList);
    // sise 더보기 버튼 list를 change할 때마다 활성화
    $('.m_quote .btn_wrap .m_more').show();
}
// defalut 가져오기
function changeSiseListByDefault(currentSiseType) {
    if(!mainSiseList || mainSiseList.length ===0){
        // console.log('no mainSise');
    }
    var filteredSiseList = mainSiseList.filter(function(mainsise) {
        return mainsise['Pc5'].includes(currentSiseType);
    });
    renderMainSiseList(filteredSiseList);
    // sise 더보기 버튼 list를 change할 때마다 활성화
    $('.m_quote .btn_wrap .m_more').show();
}

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

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

    // Pc1:회원권 코드 중복값 체크
    var uniquePc1Values = new Set();
        var uniqueSiseList = [];

    siseList.forEach(function(sise) {
        if (!uniquePc1Values.has(sise['Pc1'])) {
            uniquePc1Values.add(sise['Pc1']);
            uniqueSiseList.push(sise);
        }
    });

    uniqueSiseList.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-pc5="${sise['Pc5']}"
                    onclick="window.location.href = '/contactus-custom/${sise['Pc5']}/${encodeURIComponent(sise['PostTitle'])}'">상담신청
                </button>
            </td>
        `);

        tbody.append(tr);
    })
}

    function findMondayData(date){
        siseType = currentSiseType;
        var siseDate = dateFormat(date);
        var offset = 0;
        var limit = 30;

        $.ajax({
            url: '/load-more-sise',
            method: 'GET',
            data: { offset: offset, limit: limit, siseType: currentSiseType, siseDate:siseDate },

            success: function(response) {
                console.log(response);
                var siseList = response.Page;
                if (siseList!=null) {
                    // appendMainSiseList(siseList);
                    renderMainSiseList(siseList);
                } else {
                    $('.m_quote .btn_wrap .m_more').hide();
                }
            },
            error: function(error) {
                console.error('Error loading more sise:', error);
            }
        });
    }
    // 시세 더보기
    function loadMoreSise(){
        siseType = currentSiseType;
        var url = '';
        if (siseType === 'golf') {
            url = '/sise/golf/all';
        } else if (siseType === 'condo') {
            url = '/sise/condo/all';
        } else if (siseType === 'fitness') {
            url = '/sise/fitness/all';
        }

        window.location.href = url;

        // var offset = $('#sise-list tr').length;
        // var limit = 12;

        // $.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 url = "/kb-bbs/list/golf-youtube";
        window.location.href = url;
        // var offset = $('.m_youtube .list li').length;
        // 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 url = "/kb-bbs/list/golf-blog";
        window.location.href = url;
        // 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) {
        //         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 (사용안함 x)
    // 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-pc5="${sise['Pc5']}"
    //                         onclick="window.location.href = '/contactus-custom/${sise['Pc5']}/${encodeURIComponent(sise['PostTitle'])}'">상담신청
    //                 </button>
    //             </td>
    //         `);
    //         tbody.append(tr);
    //     });
    // }

// youtube 더보기 list add (사용안함 x)
// 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 (사용안함 x)
// 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);
}

function dateFormat(date) {
    var formattedDate = '';
    if (date) {
        var parts = date.split('-');
        formattedDate = parts.join('');
    }
    return formattedDate;
}

function formatDate(date) {
    const selectedDate = new Date(date); // Date 객체로 변환
    const dayOfWeek = selectedDate.getDay(); // (0: 일요일, 1: 월요일, ..., 6: 토요일)
    const monday = new Date(selectedDate); // 해당 주의 월요일
    monday.setDate(selectedDate.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
    const year = monday.getFullYear();
    const month = String(monday.getMonth() + 1).padStart(2, '0');
    const day = String(monday.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
// 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 youtubeTypes = {!! json_encode($youtubeTypes['Page']) !!};
const mainBlogList = {!! json_encode($mainBlogList['Page']) !!};

</script>
@endpush
@endsection
