<?php
header('Content-Type: application/json; charset=UTF-8');
include_once '../src/inc/db/function.php';
// 檢查是否有檔案上傳
//if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    $mcsrfToken = $_POST['csrfToken'] ?? null;
    $msg = "";
    if ($_REQUEST['action'] == "dataUpload" && isset($_POST['data_id']) && $_POST['data_id'] > 0) {
        if ($mcsrfToken != $_SESSION['csrfToken']) {
            echo "<script>alert('驗證碼錯誤。');</script>";
            exit;
        }
        $detail_id = $_POST['detail_id'] ?? 0;
        $data_id = $_POST['data_id'] ?? 0;
        $downloadType = $_POST['downloadType'] ?? 'original';
        $originalfile_upload = $_POST['fileName'];
        /* $file_upload = $_POST['file_upload'];
        $file_description = $_POST['file_description'];
        $fileFormat = $_POST['fileFormat'];
        $downloadType = $_POST['downloadType'];
        $update_date = date('Y-m-d H:i:s'); */

        // 檢查檔案上傳是否成功
        if (isset($_FILES['file_upload']) && $_FILES['file_upload']['error'] == 0) {
            $file_upload = $_FILES["file_upload"]["name"];
            $fileTmpPath = $_FILES["file_upload"]["tmp_name"];
            $fileSize = $_FILES["file_upload"]["size"];

            // 獲取檔案副檔名
            $fileExtension = strtolower(pathinfo($file_upload, PATHINFO_EXTENSION));

            // 檢查檔案大小（可選，根據需要設定）
            if ($fileSize > 15 * 1024 * 1024) { // 限制最大檔案大小為 5MB
                die("檔案大小超過限制（15MB）。");
                $msg = "檔案大小超過限制（15MB）。";
            }
            $allowedExtensions = ['csv', 'grib2', 'seg-y', 'nc4', 'nc', 'wrf', 'stl', 'zip']; // 允許的檔案格式
            if (!in_array($fileExtension, $allowedExtensions)) {
                die("不允許的檔案格式。請上傳 CSV、grib2、SEG-Y、nc4、NC、WRF、STL 或 ZIP 檔案。");
                $msg = "不允許的檔案格式。請上傳 CSV、grib2、SEG-Y、nc4、NC、WRF、STL 或 ZIP 檔案。";
            }
            if ($msg == "") {
                // 定義上傳目標資料夾
                $uploadDir = '../uploads/data/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                // 取得檔案原始名稱
                //    $originalfile_upload = $downloadType . '_' . $data_id . '_' . basename($_FILES['file_upload']['name']);
                $originalfile_upload = $downloadType . '_' . $data_id . '_' . basename($_FILES['file_upload']['name']);
                // 取得檔案名稱（不包含副檔名）
              //  $file_name_without_extension = pathinfo($file_upload, PATHINFO_FILENAME);
                // 新的檔案名稱：原始名稱 + 日期時間 date('YmdHis')
                $originalfile_upload = pathinfo($file_upload, PATHINFO_FILENAME) . '_' . date('Ymd') . '.' . $fileExtension;

                // 定義上傳檔案的路徑
                $uploadFilePath = $uploadDir .  $originalfile_upload;

                // 移動上傳的檔案到指定資料夾
                if (move_uploaded_file($_FILES['file_upload']['tmp_name'], $uploadFilePath)) {


                    // 釋放資源
                    //$stmt->close();
                } else {
                    echo "檔案上傳失敗，請確認上傳目錄的權限設置。";
                    $msg = "檔案上傳失敗，請確認上傳目錄的權限設置。";
                }
            }
        } else {
            echo "未上傳任何檔案或上傳失敗。";
            $msg = "未上傳任何檔案或上傳失敗。";
        }
        $n_rid = false;
        $fieldarray = array(
            'data_id' => $_POST['data_id'],
            'fileName' => $originalfile_upload,
            'file_description' => $_POST['file_description'],
            'fileFormat' => $_POST['fileFormat'] ?? $fileExtension,
            'downloadType' => $downloadType,
            'update_date' => $now
        );
        // 上傳成功，將檔案資訊儲存到資料庫
        if ($detail_id > 0) {
            $where_claud = "detail_id = $detail_id and data_id = $data_id";
            $n_rid = update_data("data_service_detail", $fieldarray, $where_claud);
        } else {
            $n_rid = insert_data1("data_service_detail", $fieldarray);
        }
        if ($n_rid) {
            header('Location: data_edit.php?rid=' . $data_id);
            exit;
        } else {
            //  echo "儲存至資料庫失敗：" . $stmt->error;
            $msg = "儲存至資料庫失敗！";
        }
        // header('Location: data_edit.php?rid='.$data_id.'');
        // echo "<script>alert('{$msg}');</script>";
        echo "<script>alert('{$msg}');location.replace('data_edit.php?rid={$data_id}');</script>";
        exit;
    } else if ($_REQUEST['action'] == "detail_del" && isset($_REQUEST['data_id']) && $_REQUEST['data_id'] > 0) {
        // 驗證 CSRF 令牌
        if (!isset($_REQUEST['csrfToken']) || $_REQUEST['csrfToken'] != $_SESSION['csrfToken']) {
            die('CSRF 令牌驗證失敗');
            echo json_encode(['message' => '無效請求' . $_REQUEST['csrfToken']], JSON_UNESCAPED_UNICODE);
            exit;
        }
        // 如果有 data_id ，則進行更新
        try {
            $mrid = intval($_REQUEST['data_id']);  // 使用 intval() 轉換為整數，防止 SQL 注入
            $mdetail_id = intval($_REQUEST['detail_rid']);  // 使用 intval() 轉換為整數，防止 SQL 注入
            if ($mrid > 0 && $mdetail_id > 0) {
                $sql = "DELETE FROM data_service_detail WHERE detail_id = ? and  data_id  = ?; ";
                $stmt = $conn->prepare($sql);
                // $mParameter = array(':detail_id' => $mdetail_id, ':data_id' =>$mrid);
                // 執行刪除並檢查結果
                if ($stmt->execute([$mdetail_id, $mrid])) {
                    echo json_encode(['success' => true, 'message' => '刪除成功'], JSON_UNESCAPED_UNICODE);
                } else {
                    echo json_encode(['success' => false, 'message' => '刪除失敗'], JSON_UNESCAPED_UNICODE);
                }
            } else {
                echo json_encode(['success' => false, 'message' => '未提供 ID'], JSON_UNESCAPED_UNICODE);
            }
        } catch (PDOException $e) {
            $error = $e->getMessage();
            echo json_encode(['success' => false, 'message' => $error], JSON_UNESCAPED_UNICODE);
        }
    } else {
        echo json_encode(['success' => false, 'message' => '無效請求'], JSON_UNESCAPED_UNICODE);
    }
    exit;
}
//echo json_encode(['message' => $_REQUEST], JSON_UNESCAPED_UNICODE);
// 關閉資料庫連線
//$conn->close();
exit;
