<?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 = '경동기업 수주 List';   

?>  
<title>  <?=$title_message?>  </title> 
</head>
<body> 
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>   
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>       	 
<?php
$tablename = 'output'; 
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();  

// 검색 조건 설정
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$fromdate = isset($_REQUEST['fromdate']) ? $_REQUEST['fromdate'] : '';  
$todate = isset($_REQUEST['todate']) ? $_REQUEST['todate'] : '';  
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$SettingDate = isset($_REQUEST['SettingDate']) ? $_REQUEST['SettingDate'] :  " regist_day ";  

if(isset($_REQUEST["separate_date"]))  
	$separate_date=$_REQUEST["separate_date"];	 

$rstate=$_GET['rstate'];

require_once("../lib/mydb.php");
$pdo = db_connect();	

if($separate_date=="") $separate_date="1";
 
// 현재 날짜
$currentDate = date("Y-m-d");

// fromdate 또는 todate가 빈 문자열이거나 null인 경우
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
    $fromdate = date("Y-m-d", strtotime("-1 months", strtotime($currentDate))); // 1개월 이전 날짜
    $todate =  date("Y-m-d", strtotime("+3 months", strtotime($currentDate))); // 3개월 이전 날짜
	$Transtodate = $todate;
} else {
    // fromdate와 todate가 모두 설정된 경우 (기존 로직 유지)
    $Transtodate = $todate;
}

if($separate_date=="1") 
	$SettingDate="outdate ";
else
	$SettingDate="indate ";

?>


<form id="board_form" name="board_form" method="post" action="list.php?mode=search">
    <input type="hidden" id="mode" name="mode" value="<?=$mode?>">
    <input type="hidden" id="num" name="num">
    <input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>">
    <input type="hidden" id="header" name="header" value="<?=$header?>">

    <div class="container-fluid">
        <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>&nbsp;&nbsp;&nbsp;&nbsp;
                </div>
                <div class="row">
                    <div class="col-sm-2">
                        <div class="d-flex p-1 m-1 mt-1 justify-content-start align-items-center">
                            <a href="?rstate=1"><span class="btn_state color-red">등록</span></a>
                            <a href="?rstate=2"><span class="btn_state color-green">접수</span></a>
                            <a href="?rstate=3"><span class="btn_state color-black">완료</span></a>
                        </div>
                    </div>
                    <div class="col-sm-10">
                        <div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-start align-items-center">
                            <ion-icon name="caret-forward-outline"></ion-icon> <?=$total_row?> &nbsp;
                            <label>&nbsp; 출고일 <input type="radio" name="separate_date" value="1" <?= $separate_date == "1" ? 'checked' : '' ?>></label>
                            <label>&nbsp; 접수일 <input type="radio" name="separate_date" class="me-3" value="2" <?= $separate_date == "2" ? 'checked' : '' ?>></label>

                            <button type="button" id="premonth" class="btn btn-dark btn-sm me-1" onclick='yesterday()'> 전일 </button>
                            <button type="button" class="btn btn-outline-dark btn-sm me-1" onclick='this_today()'> 금일 </button>
                            <button type="button" class="btn btn-dark btn-sm me-4" onclick='this_tomorrow()'> 익일 </button>

                            <input type="checkbox" id="setRange" name="setRange" value="기간">
                            <label for="setRange" class="me-1"> 기간 </label>
                            <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;

                            <div class="inputWrap">
                                <input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off" class="form-control" style="width:150px;"> &nbsp;
                                <button class="btnClear"></button>
                            </div>

                            <div id="autocomplete-list"></div>
                              &nbsp;
                              <button id="searchBtn" type="button" class="btn btn-dark btn-sm"> <ion-icon name="search"></ion-icon> </button>
                              &nbsp;&nbsp;&nbsp;
                              <button type="button" class="btn btn-dark btn-sm me-1" id="writeBtn"> <i class="bi bi-pencil-fill"></i> 신규 </button>
                              <button type="button" class="btn btn-dark btn-sm me-1" onclick="popupCenter('delivery.php','경동 출고List',1800,900);"> <i class="bi bi-print"></i> 화물/택배 출고List </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div id="myGrid" class="ag-theme-alpine" style="height: 600px; width: 100%;"></div>
    </div>
</form>

document.addEventListener('DOMContentLoaded', function() {
    var columnDefs = [
        { headerName: "번호", field: "num", width: 80 },
        { headerName: "출고일자", field: "outdate", width: 120 },
        { headerName: "접수일", field: "indate", width: 120 },
        { headerName: "진행", field: "regist_state", width: 100, cellRenderer: function(params) {
            if (params.value == "1") {
                return '<span class="badge bg-danger">등록</span>';
            } else if (params.value == "2") {
                return '<span class="badge bg-success">접수</span>';
            } else if (params.value == "3") {
                return '<span class="badge bg-dark">완료</span>';
            }
        }},
        { headerName: "구분", field: "root", width: 100, cellClass: function(params) {
            return params.value == "주일" ? "text-dark" : "text-primary";
        }},
        { headerName: "절곡", field: "steel", width: 100 },
        { headerName: "모터", field: "motor", width: 100 },
        { headerName: "현장명", field: "outworkplace", width: 180 },
        { headerName: "수신자", field: "receiver", width: 100 },
        { headerName: "수신 주소", field: "outputplace", width: 200 },
        { headerName: "수신 연락처", field: "phone", width: 120 },
        { headerName: "운송방식", field: "delivery", width: 120 },
        { headerName: "담당", field: "orderman", width: 100 },
        { headerName: "틀수", field: "number", width: 80 },
        { headerName: "면적", field: "area", width: 100 },
        { headerName: "비고", field: "comment", width: 200 }
    ];

    var gridOptions = {
        columnDefs: columnDefs,
        rowModelType: 'infinite',
        paginationPageSize: 50,
        cacheBlockSize: 50,
        datasource: {
            getRows: function(params) {
                console.log('Requesting rows: ', params.startRow, ' to ', params.endRow);
                $.ajax({
                    url: 'loadpage.php',
                    type: 'GET',
                    data: {
                        startRow: params.startRow,
                        endRow: params.endRow,
                        fromdate: $('#fromdate').val(),
                        todate: $('#todate').val(),
                        SettingDate: $("input[name='separate_date']:checked").val(),
                        setRange: $('#setRange').is(':checked'),
                        search: $('#search').val()
                    },
                    success: function(data) {
                        console.log(data);
                        if (data.error) {
                            alert('Error: ' + data.error);
                        } else {
                            params.successCallback(data.rowsThisPage, data.lastRow);
                        }
                    },
                    error: function() {
                        params.failCallback();
                    }
                });
            }
        }
    };

    var eGridDiv = document.querySelector('#myGrid');
    const gridApi = agGrid.createGrid(eGridDiv, gridOptions);

    $('#searchBtn').on('click', function() {
        gridApi.setDatasource(gridOptions.datasource);
    });

    $('#fromdate, #todate, #setRange, input[name="separate_date"]').on('change', function() {
        gridApi.setDatasource(gridOptions.datasource);
    });

    $('#premonth').on('click', function() {
        $('#fromdate').val(new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]);
        gridApi.setDatasource(gridOptions.datasource);
    });

    $('#this_today').on('click', function() {
        $('#fromdate').val(new Date().toISOString().split('T')[0]);
        gridApi.setDatasource(gridOptions.datasource);
    });

    $('#this_tomorrow').on('click', function() {
        $('#fromdate').val(new Date(new Date().setDate(new Date().getDate() + 1)).toISOString().split('T')[0]);
        gridApi.setDatasource(gridOptions.datasource);
    });

    $("input:radio[name=separate_date]").click(function() {
        gridApi.setDatasource(gridOptions.datasource);
    });
});

</script>

<script>
// 페이지 로딩
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
    loader.style.display = 'none';
});

$(document).ready(function(){	
	$("#writeBtn").click(function(){ 		
		var tablename = '<?php echo $tablename; ?>';		
		var url = "write_form.php?tablename=" + tablename; 				
		customPopup(url, '수주내역', 1850, 900); 	
	 });	  
});	  

</script>
</body>
</html>













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

header('Content-Type: application/json');

$pdo = db_connect();
$tablename = 'output';
$DB = 'chandj';

try {
    // 파라미터 값 읽기
    $startRow = isset($_GET['startRow']) ? intval($_GET['startRow']) : 0;
    $endRow = isset($_GET['endRow']) ? intval($_GET['endRow']) : 50;
    $search = isset($_GET['search']) ? $_GET['search'] : '';
    $fromdate = isset($_GET['fromdate']) ? $_GET['fromdate'] : '';
    $todate = isset($_GET['todate']) ? $_GET['todate'] : '';
    $SettingDate = isset($_GET['SettingDate']) ? $_GET['SettingDate'] : 'regist_day';
    $setRange = isset($_GET['setRange']) ? filter_var($_GET['setRange'], FILTER_VALIDATE_BOOLEAN) : false;

    // 기본 쿼리 설정
    $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM $DB.$tablename WHERE is_deleted = '0'";
    $params = [];
    
    if ($setRange && !empty($fromdate) && !empty($todate)) {
        $sql .= " AND $SettingDate BETWEEN :fromdate AND :todate";
        $params[':fromdate'] = $fromdate;
        $params[':todate'] = $todate;
    }
    if (!empty($search)) {
        $sql .= " AND searchtag LIKE :search";
        $params[':search'] = "%$search%";
    }

    // 정렬 파라미터 추가
    $sortField = isset($_GET['sortField']) ? $_GET['sortField'] : $SettingDate;
    $sortOrder = isset($_GET['sortOrder']) && strtolower($_GET['sortOrder']) === 'asc' ? 'ASC' : 'DESC';
    $sql .= " ORDER BY $sortField $sortOrder LIMIT :startRow, :pageSize";

    $params[':startRow'] = $startRow;
    $params[':pageSize'] = $endRow - $startRow;

    // 데이터 페칭
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rowsThisPage = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 전체 데이터 개수 계산
    $totalQuery = "SELECT FOUND_ROWS()";
    $totalStmt = $pdo->query($totalQuery);
    $totalRows = $totalStmt->fetchColumn();

    // JSON 형식으로 결과 반환
    echo json_encode([
        'rowsThisPage' => $rowsThisPage,
        'lastRow' => $totalRows
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'error' => $e->getMessage()
    ]);
}
?>
