<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$today = date("Y-m-d");
$title_message = '월별 출고 일정';
?>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php' ?>
<title> <?=$title_message?> </title>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/myheader.php'; ?>
<style>
.red-day {
  color: red !important;
}
.today {
  background-color: red !important;
}
td, th {
    vertical-align: top !important;
    text-align: left !important;
}
</style>

<div class="card mt-2 mb-2">
  <div class="row mt-4">
    <div class="col-sm-3">
    </div>
    <div class="col-sm-5">
      <div class="d-flex justify-content-center  mb-4">    
        <button id="prev-month" class="btn btn-primary btn-sm me-1"> <i class="bi bi-arrow-left"></i>   전월 </button>
        <button id="next-month" class="btn btn-primary btn-sm me-1">   다음 달  <i class="bi bi-arrow-right"></i> </button>
        <button id="current-month" class="btn btn-outline-primary btn-sm me-5 ">이번 달</button>   
        <h4 id="clickableText_motor"> <?=$title_message?> </h4>
		 <button type="button" class="btn btn-dark btn-sm mx-3"  onclick='location.reload();' title="새로고침"> <i class="bi bi-arrow-clockwise"></i> </button>  
      </div>
      <div class="d-flex justify-content-center items-center" style="vertical-align: center">    
        <span id="current-period" class="text-primary fs-6 me-3"></span>          
      </div>  
    </div>  
    <div class="col-sm-3">
      <div class="d-flex justify-content-center mb-2">
        <span class="badge bg-success fs-6 me-1"> 월별 출고 수량(출고일 기준) </span>
      </div>
      <div class="d-flex justify-content-center">
        <table class="table table-bordered table-striped w-75">
          <thead class="table-success">
            <tr>
              <th class="text-center text-primary">스크린면적</th>
              <th class="text-center text-primary">철재스라트면적</th>              
            </tr>
          </thead>
          <tbody>
            <tr>
              <td class="text-center"><span id="screen_sum"></span></td>
              <td class="text-center"><span id="slat_sum"></span></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="col-sm-1">
    </div>
  </div>
  <div id="calendar-container" class="d-flex p-2 justify-content-center"></div>
</div>

<script>

$(document).ready(function() {
    let currentMonth = new Date().getMonth();
    let currentYear = new Date().getFullYear();

    function fetchCalendarData(month, year) {
        $.ajax({
            url: "/output/fetch_date.php",
            type: "post",
            data: { month: month + 1, year: year, dateType: 'outdate' },
            dataType: "json",
            success: function(response) {
				console.log(response);
                updateCalendar(month + 1, year, response.data_order);
            },
            error: function(error) {
                console.log(error);
                alert('출고 기준 데이터를 불러올 수 없습니다.');
            }
        });
    }

    function updateCalendar(month, year, data) {
        let calendarHtml = generateCalendarHtml(data);
        $('#calendar-container').html(calendarHtml);

        $.ajax({
            url: "/output/fetch_date.php",
            type: "post",
            data: { month: month, year: year, dateType: 'outdate' },
            dataType: "json",
            success: function(response) {
				console.log(response);				
                let data_order = response.data_order;

                let screen_sum = 0;
                let slat_sum = 0;

                if (Array.isArray(data_order)) {
                    data_order.forEach(item => {
                        screen_sum += parseFloat(item.screen_m2) || 0;
                        slat_sum += parseFloat(item.slat_m2) || 0;
                    }); 

                    $('#screen_sum').text(screen_sum.toFixed(2));
                    $('#slat_sum').text(slat_sum.toFixed(2));
                } else {
                    console.error("Unexpected response format:", response);
                    alert('Unexpected response format');
                }
            },
            error: function(error) {
                console.log(error);
                alert('출고일자 기준 데이터를 불러올 수 없음');
            }
        });
    }

    function generateCalendarHtml(data) {
        const daysOfWeek = ['일', '월', '화', '수', '목', '금', '토'];
        let date = new Date(currentYear, currentMonth, 1);
        let firstDay = date.getDay();
        let lastDate = new Date(currentYear, currentMonth + 1, 0).getDate();
        
        let today = new Date();
        
        let todayYear = today.getFullYear();
        let todayMonth = today.getMonth();
        let todayDate = today.getDate();        

        // console.log('data',data);
        let deliveryMethodOrder = [
            "상차(선불)", "상차(착불)", "경동화물(선불)", "경동화물(착불)", "경동택배(선불)", "경동택배(착불)",
            "직접배차", "직접수령", "대신화물(선불)", "대신화물(착불)", "대신택배(선불)", "대신택배(착불)"
        ];

        let calendarHtml = '<table class="table table-condensed table-tight">';
        calendarHtml += '<thead class="table-primary"><tr>';
        
        daysOfWeek.forEach(day => {
            calendarHtml += '<th class="fs-6">' + day + '</th>';
        });

        calendarHtml += '</tr></thead><tbody>';

        let day = 1;
        for (let i = 0; i < 6; i++) {
            calendarHtml += '<tr>';
            for (let j = 0; j < 7; j++) {
                if (i === 0 && j < firstDay) {
                    calendarHtml += '<td></td>';
                } else if (day > lastDate) {
                    calendarHtml += '<td></td>';
                } else {
					// 여기서 설정하는 날짜에 따라 데이터가 나온다. 주의요함
					// 여기서 설정하는 날짜에 따라 데이터가 나온다. 주의요함 ****** 중요함)
                    let dayData = data.filter(item => new Date(item.outdate).getDate() === day);
                    let dayClass = (j === 0 || j === 6) ? 'red-day' : '';
                    
                    let currentDate = new Date(currentYear, currentMonth, day);                    
                    
                    if (currentDate.getFullYear() === todayYear && currentDate.getMonth() === todayMonth && currentDate.getDate() === todayDate) {
                        dayClass += ' today-bg';
                    }                    
                                    
                    calendarHtml += '<td class="' + dayClass + '"><div class="fw-bold fs-6">' + day + '</div>';
                    
                    dayData.sort((a, b) => {
                        let methodA = a.delivery;
                        let methodB = b.delivery;
                        return deliveryMethodOrder.indexOf(methodA) - deliveryMethodOrder.indexOf(methodB);
                    });

                    dayData.forEach(item => {
                        let screen_sum = parseFloat(item.screen_m2) || 0;
                        let slat_sum = parseFloat(item.slat_m2) || 0;
                        let totalsum = screen_sum + slat_sum;

                        let statusClass = item.regist_state === '완료' ? 'text-dark' : 'text-primary';
                        let deliveryClass = 'bg-secondary';
                        switch (item.delivery) {
                            case '상차(선불)':
                                deliveryClass = 'bg-info';
                                break;
                            case '상차(착불)':
                                deliveryClass = 'bg-dark';
                                break;
                            case '경동화물(선불)':
                                deliveryClass = 'bg-primary';
                                break;
                            case '경동화물(착불)':
                                deliveryClass = 'bg-success';
                                break;
                            case '경동택배(선불)':
                                deliveryClass = 'bg-warning';
                                break;
                            case '경동택배(착불)':
                                deliveryClass = 'bg-danger';
                                break;
                            case '직접배차':
                                deliveryClass = 'bg-secondary';
                                break;
                            case '직접수령':
                                deliveryClass = 'bg-secondary';
                                break;
                            case '대신화물(선불)':
                                deliveryClass = 'bg-dark';
                                break;
                            case '대신화물(착불)':
                                deliveryClass = 'bg-secondary';
                                break;
                            case '대신택배(선불)':
                                deliveryClass = 'bg-primary';
                                break;
                            case '대신택배(착불)':
                                deliveryClass = 'bg-info';
                                break;
                        }                  
                        
                        var statustag = '';
                        switch (item.regist_state) {
                            case '완료':
                                statustag = '<span class="text-danger fw-bold">완료</span>';
                                break;
                            default:
                                statustag = item.regist_state;
                                break;
                        }   
						var secondord = '';		
                        if(item.secondord !== null && item.secondord !== '' )
							secondord = '[' + item.secondord + ']' ;
                        calendarHtml += '<div class="event" data-id="' + item.num + '"><span class="badge ' + deliveryClass + '"> ' + item.delivery + 
						' </span> <span class="' + statusClass + '">' + secondord + item.outworkplace + ' ' + totalsum.toFixed(2) + '㎡ ' + statustag + '</span></div>';
                    });

                    calendarHtml += '</td>';
                    day++;
                }
            }
            calendarHtml += '</tr>';
        }

        calendarHtml += '</tbody></table>';

        let startDate = new Date(currentYear, currentMonth, 1);
        let endDate = new Date(currentYear, currentMonth, lastDate);
        $('#current-period').text(startDate.toLocaleDateString() + ' ~ ' + endDate.toLocaleDateString());

        return calendarHtml;
    }

    $('#calendar-container').on('click', '.event', function() {
        let id = $(this).data('id');
        if (id) {
            popupCenter('../output/write_form.php?mode=view&tablename=output&num=' + id, '수주내역', 1850, 900);
        }
    });

    $('#prev-month').click(function() {
        currentMonth--;
        if (currentMonth < 0) {
            currentMonth = 11;
            currentYear--;
        }
        fetchCalendarData(currentMonth, currentYear);
    });

    $('#next-month').click(function() {
        currentMonth++;
        if (currentMonth > 11) {
            currentMonth = 0;
            currentYear++;
        }
        fetchCalendarData(currentMonth, currentYear);
    });

    $('#current-month').click(function() {
        currentMonth = new Date().getMonth();
        currentYear = new Date().getFullYear();
        fetchCalendarData(currentMonth, currentYear);
    });

    fetchCalendarData(currentMonth, currentYear);
});
</script>


<script>
var ajaxRequest_write = null;

$(document).ready(function(){
    $('#loadingOverlay').hide();
   // 방문기록 남김
   saveData();
});

function saveData() {        
    if (ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }            
    
    var formData = new FormData();
    formData.append('menu', '월별 출고일정');

    ajaxRequest_write = $.ajax({
        enctype: 'multipart/form-data', // file을 서버에 전송하려면 이렇게 해야 함 주의
        processData: false,    
        contentType: false,      
        cache: false,           
        timeout: 600000,             
        url: "/output/insert_logmenu.php",
        type: "post",        
        data: formData,          
        dataType: "json",     
        success: function(data){
            console.log(data);
        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
            alert("An error occurred: " + error); // Display error message
        }                    
    });
}
</script>


</body>
</html>
