<?php
include_once 'src/inc/db/function.php';
log_use("DataList");
$fields = [];
if ($_SERVER["REQUEST_METHOD"] == "POST" || $_SERVER["REQUEST_METHOD"] == "GET") {
    foreach ($_REQUEST as $key => $value) {
        $fields[$key] = htmlspecialchars($value); // 转义输入值以防止 XSS 攻击
    }
    /*  if (!empty($fields)) {
        $response['message'] = "成功提交以下数据: " . json_encode($fields);
    } */
}
$categories = !empty($fields['msel_attr']) ? explode(',', $fields['msel_attr']) : [];  //資料類別 WA,WE
$mStartDate = !empty($fields['StartDate']) ? explode('-', $fields['StartDate']) : [];  //資料時間-- 開始時間
$mEndDate = !empty($fields['EndDate']) ? explode('-', $fields['EndDate']) : [];  //資料時間--結束時間 
$fileFormats = !empty($fields['msel_format']) ? explode(',', $fields['msel_format']) : [];  // 資料格式 csv,zip...

$mkey = $_REQUEST['mkey'] ?? '';
if (!empty($mkey)) {
    log_DataKey($mkey); //熱門關鍵字
}
$mkey = '%' . $mkey . '%'; // 添加通配符到查詢字串中

// 設定每頁顯示的資料數量
$itemsPerPage = 10; // 每頁顯示 10 筆資料

// 取得當前頁碼，若無設定則預設為第 1 頁
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page); // 確保頁碼不小於 1

$params = ["$mkey", "$mkey", "$mkey"];
$mWhere = "";
if (count($categories) > 0) {  //資料類別
    // 使用 array_fill() 來生成多個佔位符，並使用 implode() 來建立佔位符的字串
    $mcategories = implode(',', array_fill(0, count($categories), '?'));
    $mWhere .= " AND dataCategory IN ($mcategories)"; // 正確地將佔位符插入到 SQL 語句中
    $params = array_merge($params, $categories); // 將 $categories 的值合併到 $params 陣列中
}

if (!empty($fields['StartDate'])) {  //資料時間-- 開始時間
    $mWhere .= " AND StartDate >= '" . $fields['StartDate'] . (strlen($fields['StartDate']) > 4 ? "-01'" :  "-01-01'");
}
if (!empty($fields['EndDate'])) {  //資料時間--結束時間 
    $mWhere .= " AND (EndDate <= '" . $fields['EndDate'] . (strlen($fields['EndDate']) > 4 ? "-01'" :  "-01-01'") . " OR EndDate IS null )";
}
// 計算總筆數
if (count($fileFormats) > 0) {  //資料格式 csv,zip... 
    $mfileFormats = implode(',', array_fill(0, count($fileFormats), '?'));
    $mWhere .= " AND b.fileFormat IN ($mfileFormats)"; // 正確地將佔位符插入到 SQL 語句中
    $params = array_merge($params, $fileFormats); // 將 $categories 的值合併到 $params 陣列中

    $sqlTotal = "SELECT COUNT(*) FROM data_service as a ";
    $sqlTotal .= ' INNER JOIN (SELECT DISTINCT data_id, fileFormat FROM data_service_detail) AS b ON a.data_id = b.data_id ';
    $sqlTotal .= " WHERE (dataTitle LIKE ? OR dataNo LIKE ? OR dataSummary LIKE ?)  ";
    $sqlTotal .= $mWhere; // 正確地將佔位符插入到 SQL 語句中

} else {
    $sqlTotal = "SELECT COUNT(*) FROM data_service ";
    $sqlTotal .= " WHERE (dataTitle LIKE ? OR dataNo LIKE ? OR dataSummary LIKE ?)  ";
    $sqlTotal .= $mWhere; // 正確地將佔位符插入到 SQL 語句中
}

$stmt = $conn->prepare($sqlTotal);
$stmt->execute($params);
$totalItems = $stmt->fetchColumn(); // 資料筆數
$totalPages = ceil($totalItems / $itemsPerPage); // 計算總頁數

// 計算查詢起始位置（OFFSET）
$offset = ($page - 1) * $itemsPerPage;
// 查詢目前頁面所需的資料
if (count($fileFormats) > 0) {  //資料格式 csv,zip...
    $sql = 'SELECT a.*, GROUP_CONCAT(DISTINCT b.fileFormat) AS fileFormats, GROUP_CONCAT(DISTINCT b.downloadType) AS downloadTypes ';
    $sql .= ' FROM data_service  AS a ';
    $sql .= ' INNER JOIN (SELECT DISTINCT data_id, fileFormat, downloadType FROM data_service_detail) AS b ON a.data_id = b.data_id ';
    $sql .= " WHERE (a.dataTitle LIKE ? OR a.dataNo LIKE ? OR a.dataSummary LIKE ?)  ";
    $sql .= $mWhere; // 正確地將佔位符插入到 SQL 語句中
    $sql .= ' GROUP BY a.data_id';
} else {
    $sql = 'SELECT a.*, GROUP_CONCAT(DISTINCT b.fileFormat) AS fileFormats, GROUP_CONCAT(DISTINCT b.downloadType) AS downloadTypes ';
    $sql .= ' FROM data_service  AS a ';
    $sql .= ' LEFT JOIN (SELECT DISTINCT data_id, fileFormat, downloadType FROM data_service_detail) AS b ON a.data_id = b.data_id ';
    $sql .= " WHERE (a.dataTitle LIKE ? OR a.dataNo LIKE ? OR a.dataSummary LIKE ?)  ";
    $sql .= $mWhere; // 正確地將佔位符插入到 SQL 語句中
    $sql .= ' GROUP BY a.data_id';
}

if (!empty($fields['msel_order'])) {
    $sql .= ' Order BY a.' . $fields['msel_order'];
}
$sql .= ' LIMIT ' . $itemsPerPage . ' OFFSET ' . $offset; // 直接使用變數

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 計算顯示的頁碼範圍
$displayPages = 3; // 每次最多顯示的頁碼數量
$startPage = max(1, $page - floor($displayPages / 2));
$endPage = min($totalPages, $startPage + $displayPages - 1);

// 確保顯示頁碼範圍不超過總頁數
if ($endPage - $startPage + 1 < $displayPages) {
    $startPage = max(1, $endPage - $displayPages + 1);
}

$ary_dataCategory = ['WE' => '氣象', 'WA' => '波浪', 'OC' => '洋流', 'GE' => '地(震測)'];
$ary_downloadType = ["original" => "原始資料", 'processed' => "處理後資料", 'results' => "模擬成果", 'simulation' => "資料使用 / 模擬教學"]; //檔案下載類型
$ary_fileFormat = ['csv' => 0, 'grib2' => 0, 'seg-y' => 0, 'nc4' => 0, 'nc' => 0, 'wrf' => 0, 'stl' => 0, 'zip' => 0];
//$fileExtension = strtolower(pathinfo($file_upload, PATHINFO_EXTENSION));
$sql = ' SELECT b.fileFormat, count(1) as qty FROM data_service_detail as b ';
$sql .= ' INNER JOIN data_service as a on b.data_id = a.data_id ';
$sql .= " WHERE (a.dataTitle LIKE ? OR a.dataNo LIKE ? OR a.dataSummary LIKE ?)  ";
$sql .= $mWhere;
$sql .= ' GROUP BY b.fileFormat';
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$format_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($format_list as $row) {
    $fileFormat = strtolower($row['fileFormat']); // 確保格式一致性（小寫）
    if (array_key_exists($fileFormat, $ary_fileFormat)) {
        $ary_fileFormat[$fileFormat] = $row['qty']; // 更新對應格式的計數
    }
}

//熱門關鍵字
$sql = 'SELECT keyWord, count(1) as qty FROM log_datakey GROUP BY keyWord ORDER BY qty desc Limit 5 ';
$stmt = $conn->prepare($sql);
$stmt->execute();
$keyWord_list = $stmt->fetchAll(PDO::FETCH_ASSOC);


?>
<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <?php include_once "template_css.php"; ?>
    <!--  <title>資料服務</title> -->

</head>

<body class="d-flex flex-column min-vh-100">
    <!--BEGIN HEADER-->
    <?php include_once "template_header.php"; ?>
    <!--END HEADER-->

    <!--BEGIN SIDEBAR-->
    <?php include_once "template_sidebar.php"; ?>
    <!--END SIDEBAR-->

    <main id="main" class="main">
        <div class="pagetitle d-flex  justify-content-between align-items-center">
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item "><a href="index.php"><i class="bi bi-house-door-fill"></i> 首頁</a></li>
                    <li class="breadcrumb-item active">資料服務</li>
                </ol>
            </nav>
            <span class="float: right;">
                <a href="#" onclick="window.history.back();" class="btn btn-sm  btn-outline-primary"><i class="bi bi-arrow-90deg-left"></i> 回上一頁</a>          
            </span>
        </div>
        <div class="row mb-3" style="background-color: #EAF5FF; height: 116px; border-radius: 8px; display: flex; flex-direction: column; justify-content: center;  text-align: left;">
            <form id="ajaxForm" action="" method="POST">
                <input type='hidden' id="msel_order" name='msel_order'>
                <input type='hidden' id="msel_attr" name='msel_attr'>
                <input type='hidden' id="msel_format" name='msel_format'>
                <input type='hidden' id="mStartDate" name='StartDate'>
                <input type='hidden' id="mEndDate" name='EndDate'>

                <div class="input-group mb-2" style="width: 50%;">
                    <input type="text" id="mkey" name="mkey" class="form-control" placeholder="請輸入關鍵字搜尋..." value="<?= $fields['mkey'] ?? ''; ?>">
                    <button type="submit" onclick="btn_Search()" class="input-group-text" title="Search"><i class="bi bi-search"></i></button>
                </div>
                <span style="margin-left: 1rem;">熱門關鍵字：<!-- OOO<?= $response['message'] ?? ''; ?> -->
                    <?php foreach ($keyWord_list as $row) {
                        echo "<code class='badge data-mode'>" . ($row['keyWord'] ?? '') . "</code>";
                    } ?>
                </span>
            </form>
        </div>
        <section class="section">
            <div class="row ">
                <div class="col-md-2 card" style="min-width:200px;">
                    <div class="title-type">資料類別</div>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($ary_dataCategory as $key => $value): ?>
                            <li class="list-group-item">
                                <input type="checkbox" id="checkbox_<?php echo htmlspecialchars($key); ?>" name="dataCategory[]" value="<?php echo htmlspecialchars($key); ?>"
                                    <?php echo (in_array($key, $categories)) ? 'checked' : ''; ?> onchange="btn_Search()">
                                &nbsp;<?php echo htmlspecialchars($value); ?>
                            </li>
                        <?php endforeach; ?>
                        <!-- <li class="list-group-item"><input type="checkbox" id="checkbox1" name="checkbox1" value="風力">&nbsp;氣象</li>
                        <li class="list-group-item"><input type="checkbox" id="checkbox3" name="checkbox2" value="波浪">&nbsp;波浪</li>
                        <li class="list-group-item"><input type="checkbox" id="checkbox3" name="checkbox3" value="波浪">&nbsp;洋流</li>
                        <li class="list-group-item"><input type="checkbox" id="checkbox3" name="checkbox4" value="波浪">&nbsp;地(震測)</li> -->
                    </ul>
                    <hr style="background-color: #CFCFCF;margin-bottom: 5px; ">
                    <div class="title-type">資料時間</div>
                    <div class=" form-group ">
                        <span>開始時間</span><br>
                        <div class="d-flex mb-2">
                            <select class="form-select" id="start_yy" name="start_yy" style="width:55%;" onchange="chg_yymm(this.id);">
                                <option value="">年份</option>
                                <?php
                                $currentYear = date("Y"); // 取得今年年份
                                for ($i = $currentYear - 10; $i <= $currentYear; $i++) {
                                    if (!empty($mStartDate) && $i == intval($mStartDate[0])) {
                                        echo "<option value=\"$i\" selected>$i</option>";
                                    } else {
                                        echo "<option value=\"$i\">$i</option>";
                                    }
                                }
                                ?>
                            </select>
                            <select class="form-select" id="start_mm" name="start_mm" style="width:45%;min-width:80px;" onchange="chg_yymm(this.id);">
                                <option value="">月份</option>
                                <?php
                                for ($i = 1; $i <= 12; $i++) {
                                    // echo "<option value=\"$i\">$i</option>";
                                    if (!empty($mStartDate[1]) && $i == intval($mStartDate[1])) {
                                        echo "<option value=\"$i\" selected>$i</option>";
                                    } else {
                                        echo "<option value=\"$i\">$i</option>";
                                    }
                                } ?>
                            </select>
                        </div>
                        <span>結束時間</span><br>
                        <div class="d-flex ">
                            <select class="form-select" id="end_yy" name="end_yy" style="width:55%" onchange="chg_yymm(this.id);">
                                <option value="">年份</option>
                                <?php
                                $currentYear = date("Y"); // 取得今年年份
                                for ($i = $currentYear - 10; $i <= $currentYear; $i++) {
                                    if (!empty($mEndDate) && $i == intval($mEndDate[0])) {
                                        echo "<option value=\"$i\" selected>$i</option>";
                                    } else {
                                        echo "<option value=\"$i\" >$i</option>";
                                    }
                                }
                                ?>
                            </select>
                            <select class="form-select" id="end_mm" name="end_mm" style="width:45%;min-width:80px;" onchange="chg_yymm(this.id);">
                                <option value="">月份</option>
                                <?php
                                for ($i = 1; $i <= 12; $i++) {
                                    if (!empty($mEndDate[1]) && $i == intval($mEndDate[1])) {
                                        echo "<option value=\"$i\" selected>$i</option>";
                                    } else {
                                        echo "<option value=\"$i\">$i</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <hr style="background-color: #CFCFCF;margin-bottom: 5px; ">
                    <div class="title-type">資料格式</div>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($ary_fileFormat as $key => $value): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <input type="checkbox" id="fileFormat_<?php echo htmlspecialchars($key); ?>" name="fileFormat[]" value="<?php echo htmlspecialchars($key); ?>"
                                        <?php echo ($value == 0) ? 'disabled' : ''; ?>
                                        <?php echo (in_array($key, $fileFormats)) ? 'checked' : ''; ?> onchange="btn_Search()">
                                    &nbsp;<?php echo htmlspecialchars(strtoupper($key)); ?>
                                </div>
                                <span><?php echo htmlspecialchars($value); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>

                </div>
                <div class="col" style=" flex-grow: 1;">
                    <div class="row mb-3">
                        <div class="col-md-8 d-flex justify-content-start align-items-end">
                            <span style="margin-left:1rem;" id="totalItems">共<?php echo $totalItems; ?>筆</span>
                            <!-- 符合搜尋資料 -->
                        </div>
                        <div class="col-md-4 d-flex justify-content-end  align-right">
                            <select class="form-select-sm" id="mOrder" onchange="btn_Search()">
                                <option selected disabled>關聯</option>
                                <option value="update_date desc" <?php echo (!empty($fields['msel_order']) && 'update_date desc' == $fields['msel_order']) ? 'selected' : ''; ?>>最新更新時間</option>
                                <option value="dataTitle desc" <?php echo (!empty($fields['msel_order']) && 'dataTitle desc' == $fields['msel_order']) ? 'selected' : ''; ?>>首字筆畫多至少</option>
                                <option value="dataTitle asc" <?php echo (!empty($fields['msel_order']) && 'dataTitle asc' == $fields['msel_order']) ? 'selected' : ''; ?>>首字筆畫少至多</option>
                                <option value="viewQty desc" <?php echo (!empty($fields['msel_order']) && 'viewQty desc' == $fields['msel_order']) ? 'selected' : ''; ?>>瀏覽人數多至少</option>
                            </select>
                        </div>
                    </div>
                    <?php if (count($data_list) > 0): $rno = ($page - 1) * $itemsPerPage; ?>
                        <?php foreach ($data_list as $data): ?>
                            <div class="card card-body">
                                <a href="DataList_in.php?rid=<?php echo $data['data_id'] ?? 0; ?>" class="data-title1">
                                    <!--   <i class="bi bi-pencil-square  text-primary"></i> -->
                                    <?php echo htmlspecialchars($data['dataTitle'] ?? ''); ?></a>
                                <p class="data-info"><?php echo htmlspecialchars($data['dataSummary'] ?? ''); ?></p>
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <div class=" mb-1"><strong>資料編號：</strong><?php echo htmlspecialchars($data['dataNo'] ?? ''); ?></div>
                                        <div class=" mb-1"><strong>資料提供單位：</strong><?php echo htmlspecialchars($data['dataSource'] ?? ''); ?></div>
                                        <div class=" mb-1"><strong>資料期間：</strong><?= !empty($data['StartDate']) ? date('Y-m', strtotime($data['StartDate'])) : ''; ?>
                                            <?= (empty($data['EndDate']) || $data['EndDate'] == "1970-01-01") ? '' : "至 " . date('Y-m', strtotime($data['EndDate'])); ?></div>
                                        <div><strong>資料授權方式：</strong><?php echo htmlspecialchars($data['licenseMode'] ?? ''); ?></div>
                                    </div>
                                    <div class="col-md-6 ">
                                        <p><i class="bi bi-eye-fill "></i><span class="me-4"> <?php echo htmlspecialchars($data['viewQty'] ?? 0); ?> </span>
                                            <i class="bi bi-calendar-fill"></i> <?= !empty($data['update_date']) ? date('Y-m-d H:i', strtotime($data['update_date'])) : ''; ?>更新
                                        </p>
                                        <p>
                                            <?php
                                            $fileFormatsArray = explode(',', ($data['fileFormats'] ?? ''));
                                            foreach ($fileFormatsArray as $type) {
                                                echo '<span class="badge data-badge">' . $type . '</span>';
                                            } ?>

                                        </p>
                                        <div class="d-flex justify-content-start align-items-end">
                                            <?php
                                            $downloadTypesArray = explode(',', ($data['downloadTypes'] ?? ''));
                                            foreach ($downloadTypesArray as $type) {
                                                echo '<span class="badge data-mode">' . (isset($ary_downloadType[$type]) ? $ary_downloadType[$type] : $type) . '</span>';
                                            } ?>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center">目前沒有資料。</td>
                        </tr>
                    <?php endif; ?>

                </div>

            </div>
            <!-- 分頁導航 -->
            <div style="display: flex; justify-content: center; align-items: center; margin-top: 30px;">
                <span>共 <?php echo $totalPages; ?> 頁， 每頁 <?php echo $itemsPerPage; ?> 筆</span><!-- ，共 <?php echo $totalItems; ?> 筆資料</span>&nbsp;&nbsp; -->
                <nav aria-label="Page navigation" class="ms-4">
                    <ul class="pagination">
                        <?php if ($startPage > 1) : ?>
                            <li class="page-item"><a class="page-link" href="?page=1">1</a></li>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>

                        <?php for ($i = $startPage; $i <= $endPage; $i++) : ?>
                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php if ($endPage < $totalPages) : ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                            <li class="page-item"><a class="page-link" href="?page=<?php echo $totalPages; ?>"><?php echo $totalPages; ?></a></li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </section>

    </main>

    <?php include_once "template_footer.php"; ?>
    <script>
        showSidebar("sidebar", "DataList");
        $(document).ready(function() {
            $("#ajaxForm").submit(function(e) {
                var formData = $(this).serialize();
                console.log("formData:", formData);
            });
        });

        function btn_Search() {

            if ($("#mOrder").val() != null && $("#mOrder").val() != "") {
                $("#msel_order").val($("#mOrder").val());
                // console.log("mOrder:", $("#mOrder").val());
            }
            if ($("#start_yy").val() != null && $("#start_yy").val() != "") {
                var mStartDate = $("#start_yy").val() + ($("#start_mm").val() == "" ? '' : "-" + ($("#start_mm").val().padStart(2, '0')));
                $("#mStartDate").val(mStartDate);
            }
            if ($("#end_yy").val() != null && $("#end_yy").val() != "") {
                var mEndDate = $("#end_yy").val() + ($("#end_mm").val() == "" ? '-01' : "-" + $("#end_mm").val().padStart(2, '0'));
                $("#mEndDate").val(mEndDate);
            }

            // 資料格式
            const check_format = document.querySelectorAll('input[name="fileFormat[]"]:checked');
            const sel_format = Array.from(check_format).map(checkbox => checkbox.value);
            $("#msel_format").val(sel_format);
            // 資料類別
            const checkboxes = document.querySelectorAll('input[name="dataCategory[]"]:checked');
            const selectedCategories = Array.from(checkboxes).map(checkbox => checkbox.value);
            $("#msel_attr").val(selectedCategories);

            $("#ajaxForm").submit();

        }

        function chg_yymm(mid) {
            var mVal = $("#" + mid).val();
            console.log("chg_yymm:", mid, mVal);
            switch (mid) {
                case 'start_yy':
                    if ($("#start_yy").val() > $("#end_yy").val() && $("#end_yy").val() != "") {
                        $("#end_yy").val("");
                        console.log("開始時間>結束時間", );
                    }
                    break;
                case 'end_yy':
                    if ($("#start_yy").val() > $("#end_yy").val() && $("#end_yy").val() != "") {
                        $("#start_yy").val(mVal)
                        console.log("開始時間<結束時間", );
                    }
                    break;
                default:
                    break;
            }

        }
    </script>



</body>


</html>