<?php
include_once '../src/inc/db/function.php';
// 檢查表單是否提交
$data_id  = 0;
$mact = "新增";
$now = date("Y-m-d H:i:s"); // 獲取當前時間
$mremoveDay = date("Y-m-d", strtotime($today . " +1 years"));
$file_names = [];
$error = "";
//print_r($_REQUEST);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {

    $mcsrfToken = $_POST['csrfToken'] ?? null;
    if ($mcsrfToken != $_SESSION['csrfToken']) {
        echo "<script>alert('驗證碼錯誤。');</script>";
        exit;
    }

    if ($_REQUEST['action'] == "Delete" && isset($_POST['data_id']) && $_POST['data_id'] > 0) {

        // 如果有 data_id ，則進行更新
        $mrid = intval($_POST['data_id']);  // 使用 intval() 轉換為整數，防止 SQL 注入
        $sql = "DELETE FROM data_service WHERE data_id  = :mrid;DELETE FROM data_service_detail WHERE data_id  = :mrid; ";
        $stmt = $conn->prepare($sql);
        $stmt->bindValue(':mrid', $mrid);
        // 執行刪除並檢查結果
        if (!$stmt->execute()) {
            echo "<script>alert('刪除操作失敗，請再試一次。'); </script>";
        }
        header('Location: data_list.php');
        exit;
    }
    if ($_REQUEST['action'] == "detail_del" && isset($_POST['data_id']) && $_POST['data_id'] > 0) {
        // 如果有 data_id ，則進行更新
        $mrid = intval($_POST['data_id']);  // 使用 intval() 轉換為整數，防止 SQL 注入
        $mdetail_id = intval($_POST['detail_rid']);  // 使用 intval() 轉換為整數，防止 SQL 注入
        if ($mrid > 0 and $mdetail_id > 0) {
            $sql = "DELETE FROM data_service_detail WHERE detail_id= :detail_id and  data_id  = :data_id; ";
            $stmt = $conn->prepare($sql);
            $mParameter = array(':detail_id' => $mdetail_id, ':data_id' => $data_id);
            // 執行刪除並檢查結果
            if (!$stmt->execute($mParameter)) {
                echo json_encode(['message' => '刪除成功']);
            } else {
                echo json_encode(['message' => '刪除失敗']);
            }
        } else {
            echo json_encode(['message' => '無效請求']);
        }
        exit;
    }

    // print_r($_POST);
    $_POST['StartDate'] = (empty($_POST['StartDate'])) ? date("Y-m-01") : $_POST['StartDate'] . '-01';
    $_POST['EndDate'] = (empty($_POST['EndDate']) || $_POST['EndDate'] == '1970-01') ? null : $_POST['EndDate'] . '-01';
    // print_r($_POST);
    if (isset($_POST['data_id']) && $_POST['data_id'] > 0) {
        // 如果有 data_id ，則進行更新
        $res = Data_Update($_POST);
    } else {
        /*
        $dataCategory = mb_strtoupper(mb_substr($_POST['dataCategory'] ?? 'xx', 0, 2)); // 資料領域編號 (例如：WD, WA, WE, GE)        
        // 產生唯一資料編號 (dataNo)
        $datePrefix = date('Ymd'); // 取得當前日期 (YYYYMMDD)
        $uniqueNumber = substr(uniqid('', true), -4); // 產生 4 位數的唯一流水號
        $dataNo = $dataCategory . '-' . $datePrefix . $uniqueNumber; // 資料編號格式: WD-YYYYMMDD1234
        $_POST['dataNo'] = $dataNo;
       */
        $res = Data_Insert($_POST);
        header('Location: data_edit.php?rid=' . $res);
        exit;
    }
    if ($res) {
        header('Location: data_list.php');
    } else {
        echo "<script>alert('存檔失敗。');</script>";
    }
}

$ary_dataCategory = [
    '' => '請選擇',
    'WE' => '氣象',
    'WA' => '波浪',
    'OC' => '洋流',
    'GE' => '地(震測)'
];
$ary_licenseMode = ["依政府資料開放平臺使用規範", "書面授權", "自由文件授權"];
$ary_downloadType = ["original" => "原始資料", 'processed' => "處理後資料", 'results' => "模擬成果", 'simulation' => "資料使用 / 模擬教學"]; //檔案下載類型
$ary_fileFormat = ["CSV", "grib2", "SEG-Y", "nc4", "NC", "WRF", "STL", "ZIP"]; //檔案格式
$detail_list = [];
if (isset($_REQUEST['rid']) && $_REQUEST['rid'] > 0) {
    $mact = "修改";
    $data_id  = $_REQUEST['rid'];

    // 從資料庫中讀取詳細資料
    $sql = "SELECT * FROM data_service WHERE data_id  = :data_id Limit 1";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':data_id' => $data_id));
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$data) {
        echo "<script>alert('資料不存在！'); window.location.href = 'data_list.php';</script>";
        exit;
    }
    $mcategory = $data['dataCategory'];
    if (isset($categories[$mcategory])) {
        $categories = [$mcategory => $categories[$mcategory]];
    }

    $sql = "SELECT * FROM data_service_detail WHERE data_id  = :data_id order by downloadType,detail_id ";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':data_id' => $data_id));
    $detail_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>

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

    <!-- <title>帳號管理  </title> -->

    <?php include_once "admin_css.php"; ?>
    <!-- Change Password -->
    <script>
        window.onload = function() {
            // 检查 PHP 变量是否包含错误消息
            var errorMessage = "<?php echo $error; ?>";
            // 如果错误消息不为空，则显示警报消息
            if (errorMessage !== '') {
                alert(errorMessage);
            }
        };

        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        $(document).ready(function() {

            if ($("#rid").val() > 0) { // 如果是修改模式
                $("#saveButton").val("update");
                $("#deleteButton").css("display", "block");
            } else { // 如果是新增模式
                $("#saveButton").val("insert");
                $("#deleteButton").css("display", "none");
            }

        });
    </script>
</head>

<body>

    <!--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"><a href="data_list.php">資料服務</a></li>
                    <li class="breadcrumb-item active"><?= $mact ?></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="d-flex align-items-center">
            <div class="head-line" style="width:80px;"></div>
            <span class="head-title mx-2 ">資料服務</span>
            <div class="head-line " style="flex-grow: 1;"> </div>
        </div>

        <section class="section dashboard">
            <div class="card card-body">
                <form method="POST" action="" class="mt-2 mb-4" id="form1" enctype="multipart/form-data">
                    <input type='hidden' id="rid" name='data_id' value='<?= $data_id  ?>'>
                    <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
                    <div class="row mb-3">
                        <label for="dataCategory" class="form-label col-md-2">資料類別</label>
                        <div class="col-md-4">
                            <select class="form-select" id="dataCategory" name="dataCategory" required>
                                <?php foreach ($ary_dataCategory as $value => $label): ?>
                                    <option value="<?= htmlspecialchars($value) ?>"
                                        <?= (isset($data['dataCategory']) && $data['dataCategory'] == $value) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($label) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <!-- <select class="form-select" id="dataCategory" name="dataCategory" required>
                                <option value="" <?php echo (isset($data['dataCategory']) && $data['dataCategory'] == '') ? 'selected' : ''; ?>>請選擇</option>
                                <option value="WE" <?php echo (isset($data['dataCategory']) && $data['dataCategory'] == 'WE') ? 'selected' : ''; ?>>氣象</option>
                                <option value="WA" <?php echo (isset($data['dataCategory']) && $data['dataCategory'] == 'WA') ? 'selected' : ''; ?>>波浪</option>
                                <option value="OC" <?php echo (isset($data['dataCategory']) && $data['dataCategory'] == 'OC') ? 'selected' : ''; ?>>洋流</option>
                                <option value="GE" <?php echo (isset($data['dataCategory']) && $data['dataCategory'] == 'GE') ? 'selected' : ''; ?>>地(震測)</option>
                            </select> -->
                        </div>
                        <label for="dataNo" class="form-label col-md-2">資料編號</label>
                        <div class="col-md-4">
                            <input type="text" class="form-control" id="dataNo" name="dataNo" value="<?php echo htmlspecialchars($data['dataNo'] ?? ''); ?>" readonly>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="dataTitle" class="form-label col-md-2">資料標題</label>
                        <div class="col-md-10">
                            <input type="text" class="form-control" id="dataTitle" name="dataTitle" value="<?php echo htmlspecialchars($data['dataTitle'] ?? ''); ?>" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="dataSummary" class="form-label col-md-2">摘要說明</label>
                        <div class="col-md-10">
                            <textarea class="form-control" rows="3" id="dataSummary" name="dataSummary"><?php echo htmlspecialchars($data['dataSummary'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="StartDate" class="form-label col-md-2">資料開始年月</label>
                        <div class="col-md-4">
                            <input type="month" class="form-control" id="StartDate" name="StartDate" value="<?= date('Y-m', strtotime($data['StartDate'])) ?? '' ?>">
                        </div>
                        <label for="EndDate" class="form-label col-md-2">資料結束年月</label>
                        <div class="col-md-4">
                            <input type="month" class="form-control" id="EndDate" name="EndDate" value="<?= date('Y-m', strtotime($data['EndDate'])) ?? ''; ?>">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="dataSource" class="form-label col-md-2">資料來源單位</label>
                        <div class="col-md-4">
                            <input type="text" class="form-control" id="dataSource" name="dataSource" value="<?php echo htmlspecialchars($data['dataSource'] ?? ''); ?>">
                        </div>
                        <label for="source" class="form-label col-md-2">資料來源</label>
                        <div class="col-md-4">
                            <input type="text" class="form-control" id="source" name="source" value="<?php echo htmlspecialchars($data['source'] ?? ''); ?>" placeholder="www.abcdefg.tw">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="licenseMode" class="form-label col-md-2">授權模式</label>
                        <div class="col-md-4">
                            <select class="form-select" id="licenseMode" name="licenseMode">
                                <?php foreach ($ary_licenseMode as $value): ?>
                                    <option value="<?= htmlspecialchars($value) ?>"
                                        <?= (isset($data['licenseMode']) && $data['licenseMode'] == $value) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($value) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <!-- <input type="text" class="form-control" id="licenseMode" name="licenseMode" value="<?php echo htmlspecialchars($data['department'] ?? '依政府資料開放平臺使用規範'); ?>"> -->
                        </div>
                        <label for="source" class="form-label col-md-2">更新時間</label>
                        <div class="col-md-4">
                            <label class="form-control disabled"><?= date('Y-m-d H:i', strtotime($data['update_date'])) ?? $now ?></label>
                        </div>
                    </div>
                    <?php if($data_id>0):?>
                    <hr />
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <table class="table table-responsive table-bordered  mb-4">
                                <thead>
                                    <tr class=" table-info">
                                        <th style="width:60px;">
                                            <!-- <button type="button" onclick="modi_detail(0)" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal" title="新增">
                                                <i class="bi bi-plus-lg"></i>
                                            </button> -->
                                            <button type="button" onclick="modi_detail(0)" class="btn btn-sm btn-primary" title="新增">
                                                <i class="bi bi-plus-lg"></i>
                                            </button>
                                        </th>
                                        <th style="width:10%;">資料類型</th>
                                        <th style="width:20%;">檔案名稱</th>
                                        <th>說明</th>
                                        <th style="width:13%;">檔案格式</th>
                                        <th style="width:10%;">下載檔案</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $rno = 1;
                                    foreach ($detail_list as $detail): ?>
                                        <tr>
                                            <th>
                                                <a href="#" onclick="modi_detail(<?= $rno++ ?>)" class="btn btn-sm btn-primary" title="編輯"><i class="bi bi-pencil-square"></i></a>
                                            </th>
                                            <td class=" align-middle"><!-- <?php echo $ary_downloadType[$detail['downloadType'] ?? '']; ?> -->
                                                <?php
                                                $downloadTypeKey = $detail['downloadType'] ?? ''; // 取得 downloadType
                                                echo isset($ary_downloadType[$downloadTypeKey]) ? $ary_downloadType[$downloadTypeKey] : '未定義類型';
                                                ?>

                                            </td>
                                            <td class=" align-middle"><?php echo htmlspecialchars($detail['fileName'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($detail['file_description'] ?? ''); ?></td>
                                            <td class=" text-center"><?= strtoupper($detail['fileFormat'] ?? ''); ?></td>
                                            <td class=" text-center">
                                                <a href="../uploads/data/<?= $detail['fileName'] ?? ''; ?>" class="icon-download" target="_blank" title="資料下載, 另開視窗"><i class="bi bi-file-earmark-arrow-down"></i></a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif;?>
                    <div class="row ">
                        <div class="col-md-3">
                            <a class="btn btn-secondary w-50" id="cancelButton" href="data_list.php" role="button">取消</a>
                        </div>
                        <div class="col-md-3">
                            <button type="button" id="deleteButton" name="btn_del" class="btn btn-danger w-50" onclick="deleteData();">
                                刪除
                            </button>
                        </div>
                        <div class="col-md-6 text-center">
                            <button type="submit" id="saveButton" name="action" value="<?= $mact ?>" class="btn btn-primary w-50">
                                <?= $mact ?>存檔
                            </button>
                        </div>
                    </div>
                </form>


                <!-- Modal -->
                <div class="modal " id="uploadModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg modal-dialog-centered ">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h1 class="modal-title fs-5" id="exampleModalLabel">檔案上傳</h1>
                                <button type="button" class="btn-close bg-secondary" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <form action="data_upload.php" id="form_detail" method="POST" enctype="multipart/form-data">
                                <div class="modal-body">
                                    <input type='hidden' id="detail_id" name='detail_id' value='0'>
                                    <input type='hidden' name='data_id' value='<?= $data_id  ?>'>
                                    <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
                                    <div class="row mb-3">
                                        <label for="downloadType" class="form-label col-md-2">資料類型</label>
                                        <div class="col-md-4">
                                            <select class="form-select" id="downloadType" name="downloadType" required>
                                                <?php foreach ($ary_downloadType as $value => $label): ?>
                                                    <option value="<?= htmlspecialchars($value) ?>"
                                                        <?= (isset($data['downloadType']) && $data['downloadType'] == $value) ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($label) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <label for="dataNo" class="form-label col-md-2">資料編號</label>
                                        <div class="col-md-4">
                                            <label class="form-control"> <?= $data_id . '#' . ($data['dataNo'] ?? ''); ?></label>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <label for="fileName" class="form-label col-md-2">檔案名稱</label>
                                        <div class="col-md-10">
                                            <input type='text' id="fileName" name='fileName' class="form-control" readonly>
                                            <input type="file" class="form-control" id="file_upload" name="file_upload" accept=".csv,.grib2,.seg-y,.nc4,.nc,.wrf,.stl,.zip" onchange="upload()">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <label for="fileName" class="form-label col-md-2">檔案說明</label>
                                        <div class="col-md-10">
                                            <input type="text" class="form-control" id="file_description" name="file_description">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <label for="fileFormat" class="form-label col-md-2">檔案格式</label>
                                        <div class="col-md-4">
                                            <input type="text" class="form-control" id="fileFormat" name="fileFormat">
                                        </div>
                                        <label for="update_date" class="form-label col-md-2 update_date">更新日期</label>
                                        <div class="col-md-4">
                                            <input type="text" class="form-control" id="update_date" name="update_date" readonly>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <table class="table ">
                                        <tr>
                                            <td> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button></td>
                                            <td><button type="button" id="btn_detail_del" onclick="detail_del()" class="btn btn-danger">刪除</button></td>
                                            <td><button type="submit" class="btn btn-primary w-50" name="action" value="dataUpload">存檔</button></td>
                                        </tr>
                                    </table>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

            </div>

        </section>

    </main><!-- End #main -->

    <!--BEGIN FOOTER-->
    <?php include_once "template_footer.php"; ?>
    <!--END FOOTER-->


    <script>
        showSidebar("sidebar", "data_list");

        $(document).ready(function() {

            $('#saveButton').click(function(event) {
                if ($('#saveButton').val() != 'Delete' && !chk_required("form1")) {
                    event.preventDefault(); // 阻止表單提交
                    return;
                }
                /* if ($('#dataCategory').val() == '' || $('#dataTitle').val() == '') {
                    alert('請輸入必填欄位');
                    event.preventDefault(); // 阻止表單提交
                    return;
                } */

            });
        });

        function deleteData() {            
            if (confirm('確定要刪除此資料嗎？')) {
                var mrid = $('#rid').val();
                console.log("deleteData", mrid);
                if (!mrid || mrid == 0) {
                    alert('無效的 ID');
                    return;
                }
                // 提交表單進行刪除
                $('#saveButton').val('Delete').trigger('click');
            }
        }

        function modi_detail(rno) { // 明細資料
            console.log("detail", rno);
            if (rno == 0) {
                $("#detail_id").val(0);
                $("#downloadType").val('');
                $("#fileName").val('').hide();
                $("#file_description").val('');
                $("#fileFormat").val('');
                $("#update_date,.update_date,#btn_detail_del").hide();
            } else {
                var detailData = <?= json_encode($detail_list); ?>; // 將 PHP 陣列轉為 JSON 物件
                var data = detailData[rno - 1]; // 根據 rno 取得對應的資料，rno 從 1 開始所以 -1
                console.log("detail data=>", data);
                // 將資料填入表單
                if (data) {
                    $("#detail_id").val(data['detail_id']);
                    $("#downloadType").val(data['downloadType']);
                    $("#fileName").val(data['fileName']).show();
                    if ($("#fileName").val() == '') {
                        $("#fileName").hide();
                    }
                    $("#file_description").val(data['file_description']);
                    $("#fileFormat").val(data['fileFormat']);
                    $("#update_date").val(data['update_date']);
                    $("#update_date,.update_date,#btn_detail_del").show();
                }
            }
            // 顯示模態框
            $("#uploadModal").modal('show');
        }

        function detail_del() {
            var rno = $("#detail_id").val();
            console.log("detail", rno);
            if (confirm("確定要刪除這個項目嗎？")) {
                var mdata = {
                    csrfToken: "<?= $_SESSION['csrfToken'] ?? '' ?>",
                    action: 'detail_del',
                    data_id: '<?= $data_id  ?>',
                    detail_rid: rno
                };
                console.log("mdata", mdata);

                $.ajax({
                    url: 'data_upload.php', //'./data_upload.php', // 'data_edit.php'
                    type: 'POST',
                    // dataType: 'json',
                    data: mdata, // 傳送要刪除的項目 ID
                    success: function(response) {
                        console.log("response", response);
                        res = JSON.parse(response); // 嘗試將字串轉換為物件
                        // 處理成功的回應
                        alert(res.message); // 假設回應是一個 JSON 對象                       
                        $('#uploadModal').modal('hide');
                        if (res.success) {
                            location.reload(); // 重新載入頁面以更新資料
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log("err", xhr, status, error);
                        // 處理錯誤
                        alert("發生錯誤：" + error);
                    }
                });
            }
            //$('#uploadModal').modal('hide');
        }

        function upload() {
            // 取得 input file 元素
            var fileInput = document.getElementById('file_upload');
            const file = fileInput.files[0]; // 取得檔案
            if (file) {
                var fileName = file.name; // 取得檔案名稱
                var fileExtension = fileName.split('.').pop().toLowerCase(); // 取得檔案的副檔名並轉換為小寫

                // 允許的檔案副檔名
                var allowedExtensions = ['csv', 'grib2', 'seg-y', 'nc4', 'nc', 'wrf', 'stl', 'zip'];

                // 檢查檔案副檔名是否在允許的清單中
                if (allowedExtensions.includes(fileExtension)) {
                    // 如果副檔名符合，將副檔名設置到 fileFormat 欄位中
                    $("#fileFormat").val(fileExtension);
                } else {
                    // 如果副檔名不符合，顯示錯誤訊息並清空上傳欄位
                    alert("不支援的檔案格式，請上傳 .csv, .grib2, .seg-y, .nc4, .nc, .wrf, .stl, .zip 檔案。");
                    fileInput.value = ""; // 清空已選擇的檔案
                    $("#fileFormat").val(""); // 清空副檔名欄位
                }
                // 將副檔名設置到 fileFormat 欄位中
                // $("#fileFormat").val(fileExtension);
            }
        }
    </script>

</body>

</html>