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

if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
}

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '제조 통계 (출고 예정까지 포함)';
$title_prefix = '스크린 + 철재(스라트)';
?>
  
<title><?= $title_prefix ?> <?= $title_message ?></title>
</head>
<body>
    <?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>
    <?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>

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

    $tablename = 'output';
    $today = date("Y-m-d");
    $monthAgo = date("Y-m-d", strtotime("-1 month"));

    $fromdate = isset($_REQUEST['fromdate']) && $_REQUEST['fromdate'] ? $_REQUEST['fromdate'] : $monthAgo;
    $todate = isset($_REQUEST['todate']) && $_REQUEST['todate'] ? $_REQUEST['todate'] : date("Y") . "-12-31";
    $transtodate = date("Y-m-d", strtotime($todate . '+1 day'));

    $sql = "SELECT * FROM " . $DB . "." . $tablename . " WHERE outdate BETWEEN :fromdate AND :transtodate AND is_deleted ='0' and (devMode <> '1' OR devMode IS NULL) ORDER BY outdate DESC";

    try {
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(':fromdate', $fromdate);
        $stmh->bindValue(':transtodate', $transtodate);
        $stmh->execute();
        $rows = $stmh->fetchAll(PDO::FETCH_ASSOC);

        $chartData = [];
        $screenData = [];
        $slatData = [];
        foreach ($rows as $row) {
            $date = date("Y-m-d", strtotime($row['outdate']));
            $screen_m2 = intval(trim($row['screen_m2']));
            $slat_m2 = intval(trim($row['slat_m2']));
            if (!isset($chartData[$date])) {
                $chartData[$date] = 0;
                $screenData[$date] = 0;
                $slatData[$date] = 0;
            }
            $chartData[$date] += $screen_m2 + $slat_m2;
            $screenData[$date] += $screen_m2;
            $slatData[$date] += $slat_m2;
        }

        $jsonChartData = json_encode($chartData);
        $jsonScreenData = json_encode($screenData);
        $jsonSlatData = json_encode($slatData);

    } catch (PDOException $Exception) {
        print "오류: " . $Exception->getMessage();
    }
    ?>

    <form id="board_form" name="board_form" method="post" action="statistics.php?mode=search">
        <input type="hidden" id="active_tab" name="active_tab" value="<?= $active_tab ?>">
        <div class="container mt-3 mb-5">
            <div class="card mb-2 mt-2">
                <div class="card-body">
                    <div class="d-flex p-1 m-1 mt-1 justify-content-center align-items-center">
                        <h5><?= $title_message ?></h5>
                    </div>

                    <div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
                        <span id="showdate" class="btn btn-dark btn-sm"> 기간 </span> &nbsp;
                        <div id="showframe" class="card">
                            <div class="card-header" style="padding:2px;">
                                <div class="d-flex justify-content-center align-items-center">
                                    기간 설정
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="d-flex justify-content-center align-items-center">
                                    <button type="button" id="preyear" class="btn btn-outline-primary btn-sm me-1 change_dateRange" onclick='pre_year()'> 전년도 </button>
                                    <button type="button" id="premonth" class="btn btn-dark btn-sm me-1 change_dateRange" onclick='pre_month()'> 전월 </button>
                                    <button type="button" id="thismonth" class="btn btn-dark btn-sm me-1 change_dateRange" onclick='this_month()'> 당월 </button>
                                    <button type="button" id="thisyear" class="btn btn-dark btn-sm me-1 change_dateRange" onclick='this_year()'> 당해년도 </button>
                                </div>
                            </div>
                        </div>
                        <input type="date" id="fromdate" name="fromdate" class="form-control" style="width:100px;" value="<?= $fromdate ?>"> &nbsp; ~ &nbsp;
                        <input type="date" id="todate" name="todate" class="form-control me-1" style="width:100px;" value="<?= $todate ?>"> &nbsp;
                        
						<input type="hidden" id="search" name="search" value="<?= $search ?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off" class="form-control mx-1" style="width:150px;">
                        <button id="searchBtn" type="button" class="btn btn-dark btn-sm"> <i class="bi bi-search"></i> 검색 </button>
                    </div>

                    <div class="row">
                        <div class="col-sm-4">
                            <div class="card mb-2 mt-2">
                                <div class="card-body">
                                    <div id="screenChart" style="height: 500px;"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="card mb-2 mt-2">
                                <div class="card-body">
                                    <div id="slatChart" style="height: 500px;"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="card mb-2 mt-2">
                                <div class="card-body">
                                    <div id="totalChart" style="height: 500px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

<script>
	document.addEventListener('DOMContentLoaded', function() {
		const screenData = <?= $jsonScreenData ?>;
		const slatData = <?= $jsonSlatData ?>;
		const totalData = <?= $jsonChartData ?>;

		const sortedScreenLabels = Object.keys(screenData).sort((a, b) => new Date(a) - new Date(b));
		const sortedSlatLabels = Object.keys(slatData).sort((a, b) => new Date(a) - new Date(b));
		const sortedTotalLabels = Object.keys(totalData).sort((a, b) => new Date(a) - new Date(b));

		const sortedScreenData = sortedScreenLabels.map(label => parseFloat(screenData[label]));
		const sortedSlatData = sortedSlatLabels.map(label => parseFloat(slatData[label]));
		const sortedTotalData = sortedTotalLabels.map(label => parseFloat(totalData[label]));

		const chartOptions = (renderTo, titleText, dataLabels, data, chartcolor) => ({
			chart: {
				type: 'line',
				renderTo: renderTo
			},
			title: {
				text: titleText
			},
			xAxis: {
				categories: dataLabels,
				crosshair: true,
				labels: {
					formatter: function() {
						const date = new Date(this.value);
						return (date.getMonth() + 1) + '/' + date.getDate();
					}
				}
			},
			yAxis: {
				min: 0,
				title: {
					text: '면적 (m²)'
				}
			},
			tooltip: {
				headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
				pointFormatter: function() {
					return '<tr><td style="color:' + this.series.color + ';padding:0">' + this.series.name + ': </td>' +
						'<td style="padding:0;"><b>' + Highcharts.numberFormat(this.y, 2, '.', ',') + ' m²</b></td></tr>';
				},
				footerFormat: '</table>',
				shared: true,
				useHTML: true,
				style: {
					padding: '1px',
					minWidth: '180px'
				}
			},
			plotOptions: {
				line: {
					dataLabels: {
						enabled: true
					},
					enableMouseTracking: true
				}
			},
			series: [{
				name: '면적',
				data: data,
				color : chartcolor
			}]
		});

		Highcharts.chart(chartOptions('screenChart', '스크린 면적', sortedScreenLabels, sortedScreenData, 'blue'));
		Highcharts.chart(chartOptions('slatChart', '철재 스라트 면적', sortedSlatLabels, sortedSlatData, 'green'));
		Highcharts.chart(chartOptions('totalChart', '(스크린+스라트) 면적', sortedTotalLabels, sortedTotalData, 'gray'));
	});
</script>

<script>
var ajaxRequest_write = null;

$(document).ready(function(){
    $('#loadingOverlay').hide();
   // 방문기록 남김
   saveMenuLog('제조 통계보기');
});

function saveMenuLog(title) {        
    if (ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }            
    
    var formData = new FormData();
    formData.append('menu', title);

    ajaxRequest_write = $.ajax({
        enctype: 'multipart/form-data', // file을 서버에 전송하려면 이렇게 해야 함 주의
        processData: false,    
        contentType: false,      
        cache: false,           
        timeout: 600000,             
        url: "/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>
