<?php
include_once '../src/inc/db/function.php';
// 檢查表單是否提交
$news_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['news_id']) && $_POST['news_id'] > 0) {
   
    // 如果有 news_id，則進行更新
    $mrid = intval($_POST['news_id']);  // 使用 intval() 轉換為整數，防止 SQL 注入
   
    $sql = "DELETE FROM system_news WHERE news_id = :mrid";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':mrid', $mrid);

    // 執行刪除並檢查結果
    if ($stmt->execute()) {
      // 刪除成功後，跳轉到公告列表頁面
      header('Location: news_list.php');
      exit;
    } else {
      echo "<script>alert('刪除操作失敗，請再試一次。'); window.location.href = 'news_list.php';</script>";
    }
    exit;
  }
  
  // 檢查是否有檔案上傳
  if (isset($_FILES['file_url']) && !empty($_FILES['file_url']['name'][0]) && count($_FILES['file_url']['name']) > 0) {
    $total_files = count($_FILES['file_url']['name']);

    if (!empty($_POST['attachment_url'])) { // 用來存放所有檔案名稱
      $file_names = explode('，', $_POST['attachment_url']);
    }

    // 建立一個目標資料夾來儲存上傳的檔案
    $upload_dir = '../uploads/news/';
    if (!is_dir($upload_dir)) {
      mkdir($upload_dir, 0777, true);
    }

    // 處理每個上傳的檔案
    for ($i = 0; $i < $total_files; $i++) {
      // 檔案名稱
      $file_name = basename($_FILES['file_url']['name'][$i]);

      // 檢查檔案是否成功上傳並移動到指定目錄
      if ($_FILES['file_url']['error'][$i] == UPLOAD_ERR_OK) {
        $target_path = $upload_dir . $file_name;

        // 將檔案從暫存目錄移動到指定目錄
        if (move_uploaded_file($_FILES['file_url']['tmp_name'][$i], $target_path)) {
          // echo "檔案 {$file_name} 上傳成功！<br>";
          $file_names[] = $file_name;  // 將檔名加入到陣列中     
        } else {
          $error = "檔案 {$file_name} 上傳失敗！<br>";
        }
      } else {
        $error = "{$total_files}檔案 {$file_name} 上傳時發生錯誤，錯誤碼：{$_FILES['file_url']['error'][$i]}<br>";
      }
    }
    // 使用 implode 將檔案名稱以 "[,]" 分隔
    $_POST['attachment_url'] = implode('，', array_unique($file_names));
  }
  if (isset($_POST['news_id']) && $_POST['news_id'] > 0) {
    // 如果有 news_id，則進行更新
    $res = News_Update($_POST);
    if ($res) {
      header('Location: news_list.php');
     // echo "<script>alert('公告更新成功！'); window.location.href = 'news_list.php';</script>";
    } else {
      echo "<script>alert('公告更新失敗。');</script>";
    }
  } else {
    // 沒有 news_id 則執行新增操作
    $res = News_Insert($_POST);
    if ($res) {
      header('Location: news_list.php');
      //echo "<script>alert('公告新增成功！'); window.location.href = 'news_list.php';</script>";
    } else {
      echo "<script>alert('公告新增失敗。');</script>";
    }
  }
}

if (isset($_REQUEST['rid']) && $_REQUEST['rid'] > 0) {
  // $stmt = $conn->prepare("SELECT * FROM system_news WHERE news_id = ?  limit 1");

  $mact = "修改";
  $news_id = $_REQUEST['rid'];

  // 從資料庫中讀取該公告的詳細資料
  $sql = "SELECT * FROM system_news WHERE news_id = :news_id";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(':news_id', $news_id);
  $stmt->execute();
  $news = $stmt->fetch(PDO::FETCH_ASSOC);
  $file_names = explode('，', $news['attachment_url']);
  // 如果公告不存在，返回公告列表頁面
  if (!$news) {
    echo "<script>alert('公告不存在！'); window.location.href = 'news_list.php';</script>";
    exit;
  }
}

?>
<!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="news_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>
    <!-- <div class="pagetitle">
      <h1>系統公告</h1>      
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item active"><a href="index.php">系統公告</a></li>
        </ol>
      </nav>     
    </div> -->

    <section class="section">
      <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='news_id' value='<?= $news_id ?>'>         
          <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
          <div class="mb-3">
            <label for="title" class="form-label">公告標題</label>
            <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($news['title'] ?? ''); ?>" required>
          </div>
          <div class="mb-3">
            <label for="content" class="form-label">公告內容</label>
            <textarea class="form-control" id="content" name="content" rows="5" required><?php echo htmlspecialchars($news['content'] ?? ''); ?></textarea>
          </div>
          <div class="row mb-3">
            <label for="publish_date" class="form-label col-md-2">發佈日期</label>
            <div class="col-md-4">
              <input type="datetime-local" class="form-control" id="publish_date" name="publish_date" value="<?php echo date('Y-m-d\TH:i', strtotime($news['publish_date'] ?? $now)); ?>" required>
            </div>
            <label for="remove_date" class="form-label col-md-2">下架日期</label>

            <div class="col-md-4">
              <input type="datetime-local" class="form-control" id="remove_date" name="remove_date" value="<?php echo date('Y-m-d\TH:i', strtotime($news['remove_date'] ?? $mremoveDay)); ?>">
            </div>
          </div>
          <div class="row mb-3">
            <label for="publish_unit" class="form-label col-md-2">發佈單位</label>
            <div class="col-md-4">
              <input type="text" class="form-control" id="publish_unit" name="publish_unit" value="<?php echo htmlspecialchars($news['publish_unit'] ?? ''); ?>">
            </div>
            <label for="updated_by" class="form-label col-md-2">更新人員</label>
            <div class="col-md-4">
              <input type="text" class="form-control" id="updated_by" name="updated_by" value="<?php echo htmlspecialchars($news['updated_by'] ?? ''); ?>" readonly>
            </div>
          </div>
          <div class="row mb-3">
            <label for="attachment_url" class="form-label col-md-2">附件上傳</label>
            <div class="col-md-10 ">
              <input type='hidden' id='attachment_url' name='attachment_url' value='<?php echo htmlspecialchars($news['attachment_url'] ?? ''); ?>'>
              <ul id="file-list">
                <?php
                foreach ($file_names as $file_name): ?>
                  <?php if (!empty($file_name)): ?>
                    <li class="list-group-item  bi-download">
                      <a href="../uploads/news/<?php echo htmlspecialchars($file_name); ?>" title="download" target="_blank"><?php echo htmlspecialchars($file_name); ?></a>
                      <!-- <i class="bi  bi-trash-fill  remove-file"></i> -->
                      &nbsp;&nbsp;<button type="button" class="btn btn-sm btn-outline-danger remove-file" title="附件刪除" onclick="del_file(this,'<?= htmlspecialchars($file_name); ?>')">
                        <i class="bi bi-trash-fill"></i></button>
                    </li>
                  <?php endif; ?>
                <?php endforeach; ?>
              </ul>

              <input type="file" class="form-control" id="file_url" name="file_url[]" multiple>
              <small class="form-text text-muted">可選擇多個檔案進行上傳。</small>
              <!-- <a href="../uploads/news/<?php echo htmlspecialchars($file_name); ?>" title="download" download><?php echo htmlspecialchars($file_name); ?></a> -->


            </div>
          </div>



          <!-- <button type="submit" class="btn btn-primary">新增公告</button>

            <button type="submit" class="btn btn-primary">更新公告</button>
            <a href="news_list.php" class="btn btn-secondary">取消</a> -->

          <div class="row ">
            <div class="col-md-3">
              <a class="btn btn-secondary w-50" id="cancelButton" href="news_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="deleteNews();">
                刪除
              </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>
          <!--             
            <hr>
            <div class="row ">
              <div class="col-md-3">
                <a class="btn btn-secondary w-100" id="cancelButton" href="index.php" role="button">取消</a>
              </div>
              <div class="col-md-3">
                <button type="button add" id="deleteButton" name="action" value="" class="btn btn-danger" onclick="deleteDialog()">
                  刪除
                </button>
              </div>
              <div class="col-md-6 text-center">
                <button type="submit" id="saveButton" name="action" value="" class="btn btn-info">
                  儲存
                </button>
              </div>
            </div> -->

        </form>
      </div>
    </section>

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

  <!--BEGIN FOOTER-->
  <?php include_once "template_footer.php"; ?>
  <!--END FOOTER-->
  <script>
        showSidebar("sidebar", "news_list");
   
    $(document).ready(function() {
      // 綁定刪除按鈕點擊事件
      $('#file-list').on('click', '.remove-file', function() {

        var fileName = $(this).closest('li').attr('data-file-name');
        console.log(fileName);

        $(this).closest('li').remove();

        var mUrl = $('#attachment_url').val();
        mUrl = mUrl.split("，").filter(item => item !== fileName).join("，");
        $('#attachment_url').val(mUrl);
        console.log(mUrl);

      });

    });

    function del_file(mid, fileName) {
     // console.log(mid, fileName);
      $(mid).closest('li').remove();
      var mUrl = $('#attachment_url').val();
      mUrl = mUrl.split("，").filter(item => item !== fileName).join("，");
      $('#attachment_url').val(mUrl);
      //console.log(mUrl);
    }

    function deleteNews() {
      // 確認使用者是否要刪除
      if (confirm('確定要刪除此公告嗎？')) {       
        var mrid = $('#rid').val();
        if (!mrid || mrid == 0) {
          alert('無效的公告 ID');
          return;
        }
        // 提交表單進行刪除
        $('#saveButton').val('Delete').trigger('click'); // 設定操作類型為 `dele`  
        console.log("deleteNews", mrid);
       // $('#form1').submit(); // 提交表單       
      }
    }
    // 確認是否刪除
    function deleteDialog(id) {
      if (id < 0) {
        return false;
      }
      if (confirm(" 是否確定刪除?") == false) {
        return false;
      } else {
        var saveButton = document.getElementById('deleteButton');
        saveButton.value = 'delete';
        // 提交表单
        document.getElementById('form1').submit();
      }

    }
  </script>

</body>

</html>