@extends('views.layouts.master')
@section('content')

@php
    date_default_timezone_set('Asia/Seoul');
    $today = date('Y-m-d');
@endphp

<div class="sub golf">
	<div class="container">
		<div class="navi">
			<a href="/"><i class="fa-solid fa-house"></i> 홈</a> > {{ $title_dir }} > {{ $title }}
		</div>
		<div class="title">
			<h2> {{ $title }} </h2>
		</div>
	</div>

	<!-- 회원권 검색 시작 -->
	<div class="search_ticket">
		<div class="container">
			<label>회원권 검색</label>
			<input type="text" id="membership-name" placeholder="회원권명">
			<button type="button" class="btn" onclick="searchMemberShip()">검색</button>
		</div>
	</div>
	<!--// 회원권 검색 끝 -->

	<!-- 시세 시작 -->
	<div class="quote">
		<div class="container">
			<ul class="tabs nav nav-tabs">
                <li class="{{ request('area', 'all') === 'all' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, 'all']) }}">전체</a></li>
                @if($siseType === 'golf')
                    <li class="{{ request('area', 'all') === '100' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '100']) }}">수도권/강원/충청권</a></li>
                    <li class="{{ request('area', 'all') === '200' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '200']) }}">영남/제주권</a></li>
                    <li class="{{ request('area', 'all') === '300' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '300']) }}">호남권</a></li>
                @elseif($siseType === 'condo')
                    <li class="{{ request('area', 'all') === '400' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '400']) }}">체인형콘도</a></li>
                    <li class="{{ request('area', 'all') === '500' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '500']) }}">스키장콘도</a></li>
                @else
                    <li class="{{ request('area', 'all') === '600' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '600']) }}">강남권</a></li>
                    <li class="{{ request('area', 'all') === '700' ? 'active' : '' }}"><a href="{{ route('sise', [$siseType, '700']) }}">강북권</a></li>
                @endif
			</ul>

            <div class="tabs">
                <!-- <input type="date" id="search_date" value="{{$today}}" autocomplete="off" style="cursor: pointer;"> -->
                <input type="text" id="search_date">
            </div>


			<div class="tab-content">
				<div 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>

			</div>
		</div>

        <div id="loader" style="display: none;">Loading...</div>
	</div>
    <!--// 시세 끝 -->

</div>

@push('js')
<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>
    var filteredSiseList = [];
    var allSiseList = [];
    var loadingData = false; // 데이터 로딩 중인지 여부를 나타내는 플래그 변수
    var page = 1;

    // 스크롤 이벤트 핸들러
    function handleScroll() {
        let scrollTop = $(document).scrollTop();
        let offsetHeight = $(document).height();
        let innerHeight = $(window).height();

        if (innerHeight + scrollTop >= offsetHeight) {
            page++;
            loadMoreData(10);
        }else{
            if ((offsetHeight - (innerHeight + scrollTop)) <= 1) {  // 사용자 스크린의 크기가 달라짐에 따라 오차범위 1 이내 일때

                page++;
                loadMoreData(10);
            }else if((offsetHeight - (innerHeight + scrollTop)) == 1.25){

                page++;
                loadMoreData(10);
            }
        }
    }

    function loadMoreData(limit) {
        let date = dateFormat($('#search_date').val());
        if(siseType != 'golf'){
            const monday = dateFormat(formatDate($('#search_date').val()));
            // console.log('monday : ', monday);
            date = monday;
        }

        // console.log('siseType : ', siseType);
        let data = {
            "siseType": siseType,
            "areaType": areaType,
            "siseDate": date
        };

        if (limit) {
            data.page = page;
            data.limit = limit;
        }

        $.ajax({
            url: '/load-scroll-sise',
            method: 'GET',
            data: data,
            success: function(response) {
                var newSiseList = response.Page;
                if (newSiseList != null) {
                    if(limit){
                        filteredSiseList = filteredSiseList.concat(newSiseList);
                        console.log(newSiseList);
                        renderSiseList(filteredSiseList);
                    }else{
                        allSiseList = newSiseList;
                    }

                } else {
                    renderSiseList(filteredSiseList);
                }
            },
            error: function(error) {
                console.error('Error loading more data:', error);
            }
        });
    }

     // 회원권 검색
    function searchMemberShip() {
        $(window).off('scroll', handleScroll);
        var membershipName = $('#membership-name').val().toLowerCase();
        var date = dateFormat($('#search_date').val());
        if(siseType != 'golf'){
            const monday = dateFormat(formatDate($('#search_date').val()));
            date = monday;
        }
        if (!membershipName) {
            $(window).on('scroll', handleScroll);
            // alert('회원권명을 입력해주세요');
            // page = 1;
            // loadMoreData(10);
            renderSiseList(filteredSiseList);
        }else{
            var searchMemberShipList = allSiseList.filter(function(sise) {
                var postTitleMatch = sise['PostTitle'].toLowerCase().includes(membershipName);
                var dateMatch = date ? (sise['Pc6'] && sise['Pc6'] === date) : true;
                return postTitleMatch && dateMatch;
            });
            renderSiseList(searchMemberShipList);
        }
    }

    $(document).ready(function() {
        $('#search_date').flatpickr({
        dateFormat: 'Y-m-d',
		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');
		// },
	});
    $('#search_date').attr('type', 'text');

    // console.log('pickr : ', flatpickr);
        // console.log(siseList);
        loadMoreData();
        loadMoreData(10);
        // 스크롤 이벤트 설정
        $(window).on('scroll', handleScroll);
        // $(window).on('scroll', handleScrollWithDate);

        $('#search_date').on('change', function() {
            // if(siseType != 'golf'){
            //     const monday = formatDate($(this).val());
            //     // $(this).val(monday);
            // }

            page = 1;
            filteredSiseList = [];
            $(window).on('scroll', handleScroll);
            loadMoreData();
            loadMoreData(10);
        });

        if ($('div').hasClass('chatbot') == true) {
            $('.main-footer').addClass('chatbot');
        }
    });



    // 동적으로 tbody 생성
    function renderSiseList(siseList) {
        // console.log('renderSiseList : ', siseList);
        var tbody = $('#sise-list');
        tbody.empty(); // Clear existing rows

        if (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) {
            var fluctuationClass = '';
            var fluctuationIcon = '';

            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 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}`;
    }

    let siseList = {!! json_encode($siseList['Page']) !!};
    const siseType = {!! json_encode($siseType) !!};
    const areaType = {!! json_encode($area) !!};
</script>
@endpush
@endsection
