<?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['start']) ? intval($_GET['start']) : 0;
    $length = isset($_GET['length']) ? intval($_GET['length']) : 50; // DataTables는 length를 사용
    $search = isset($_GET['search']['value']) ? $_GET['search']['value'] : '';
    $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 num, outdate, indate, regist_state, root, steel, motor, outworkplace, receiver, outputplace, phone, delivery, orderman, bend_state , motor_state , comment 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, :length";

    // 데이터 페칭
    $stmt = $pdo->prepare($sql);

    // MySQL의 LIMIT 절에서는 바인딩된 변수를 직접 사용할 수 없으므로 바인딩된 변수를 인라인으로 처리
    $stmt->bindValue(':startRow', (int) $startRow, PDO::PARAM_INT);
    $stmt->bindValue(':length', (int) $length, PDO::PARAM_INT);

    foreach ($params as $key => &$val) {
        $stmt->bindParam($key, $val);
    }
    
    $stmt->execute();
    $rowsThisPage = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    // JSON 형식으로 결과 반환
	echo json_encode([
		'draw' => isset($_GET['draw']) ? intval($_GET['draw']) : 0,
		'recordsTotal' => $totalRows,
		'recordsFiltered' => $totalRows,
		'data' => $rowsThisPage
	]);

} catch (PDOException $e) {
    echo json_encode([
        'error' => $e->getMessage()
    ]);
}


$response = [
    'draw' => isset($_GET['draw']) ? intval($_GET['draw']) : 0,
    'recordsTotal' => $totalRows,
    'recordsFiltered' => $totalRows,
    'data' => $rowsThisPage
];
echo json_encode($response);

// 디버그용: JSON 응답을 로그에 기록하거나 화면에 출력
error_log(json_encode($response));



?>
