<?php
//include_once 'src/inc/db/function.php';

$error = '';
$num = 0;
if (isset($_GET['id'])) {
  $idStart =  htmlspecialchars($_GET['id'], ENT_QUOTES, 'UTF-8');

  if ($idStart) {

    $sql = "SELECT * FROM platform_description WHERE description_id = ?  ";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$idStart]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$result) {

      header("Location: platform_description.php");
      exit();

    }

  } else {

    header("Location: platform_description.php");
    exit();

  }

  $jsonData = json_encode($result); // 將結果轉換為 JSON 格式

} else {

  // $idStart = -1;
  // $sql = "SELECT * FROM platform_description LIMIT 1";
  // $stmt = $conn->prepare($sql);
  // $stmt->execute();
  // $result = $stmt->fetch(PDO::FETCH_ASSOC);
  // $jsonData = json_encode($result); // 將結果轉換為 JSON 格式
  
}

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
  $description_id = isset($_POST['description_id']) && $_POST['description_id'] !== '' ? $_POST['description_id'] : 0;

  /*** DATA ***/
  $platform_name = isset($_POST['platform_name']) && $_POST['platform_name'] !== '' ? htmlspecialchars(trim($_POST['platform_name']), ENT_QUOTES, 'UTF-8') : null;
  $description = isset($_POST['description']) && $_POST['description'] !== '' ? htmlspecialchars(trim($_POST['description']), ENT_QUOTES, 'UTF-8') : null;
  $mission = isset($_POST['mission']) && $_POST['mission'] !== '' ? htmlspecialchars(trim($_POST['mission']), ENT_QUOTES, 'UTF-8') : null;
  $vision = isset($_POST['vision']) && $_POST['vision'] !== '' ? htmlspecialchars(trim($_POST['vision']), ENT_QUOTES, 'UTF-8') : null;

  $platform_name = checkData($platform_name, "string");
  $description = checkData($description, "string");
  $mission = checkData($mission, "string");
  $vision = checkData($vision, "string");
  
  /*** INSERT/UPDATE/DELETE ***/
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 驗證 CSRF token
    if (!isset($_POST['csrfToken']) || $_POST['csrfToken'] !== $_SESSION['csrfToken']) {
      header("Location: login.php");
      exit();
    }

    try {
      if ($_POST['action'] == 'update') {       
        $fieldarray = array(
          'platform_name' => $platform_name,
          'description' => $description,
          'mission' => $mission,
          'vision' => $vision,
          'updated_by'=>$VR_UserNo,
          'update_date' =>  date("Y-m-d H:i:s")
        );
        $where_claud ="description_id= $description_id";
        $n_description_id=update_data("platform_description", $fieldarray,$where_claud );
       
        header("Location: platform_description.php");
      }
    } catch (PDOException $e) {
      $error = $e->getMessage();
    }
    if ($error === '') {
      header("Location: platform_description.php");
      exit();
    }else{
      echo $error;
    } 
  }
}

?>
<!DOCTYPE html>

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

  <title>平臺簡介表  </title>
  
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="fonts/fonts.css" rel="stylesheet">
  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <!-- Template Main CSS File -->

  <link href="assets/css/jquery-ui.css" rel="stylesheet">
  <link href="assets/css/style.css" rel="stylesheet">
  <script src="assets/js/jquery-3.7.1.js"></script>
  <script src="assets/js/jquery-ui.js"></script>

  <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() {
        $("#index-nav").addClass("show");
        $("#platform_description").addClass("active");

      /* $("#startDay,#endDay").datepicker({
        dateFormat: 'yy-mm-dd'
      }); */


      var data = <?= $jsonData ? $jsonData : 'null' ?>;
      if (data !== null && $("#description_id").val() > 0) {
        $("#form1").find("[id*='txt_']").each(function() {
          var key = $(this).attr("name");
          var value = data[key] || '';
          $(this).val(escapeHtml(value));
          // $(this).val(data[key] || '');
        });
        
      } else {

        $("#form1").find("[id*='txt_']").each(function() {
          var type = $(this).attr("type");
          var defaultValue = type === "number" ? 0 : ''; // 如果類型為 number，預設值為 0；否則為 ''
          $(this).val(defaultValue);
        });
        console.log(data, "沒有數據可顯示");
      }
    });

  </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">
      <h1>平臺簡介表</h1>
      <!--BEGIN BREADCRUMB-->
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.php">首頁</a></li>
          <li class="breadcrumb-item active">平臺簡介表</li>
        </ol>
      </nav>
      <!--END BREADCRUMB-->
    </div><!-- End Page Title -->

    <section class="section dashboard">
      <div class="card info-card sales-card">
        <div class="card-body">
          <form method="POST" action="" class="mt-4 mb-4" id="form1">
            <input type='hidden' id="description_id" name='description_id' value='<?= $idStart ?>'>            
            <input type="hidden" name="csrfToken" value="<?php echo htmlspecialchars($_SESSION['csrfToken'], ENT_QUOTES, 'UTF-8'); ?>">
            <div class="row mb-3">
              <label for="txt_platform_name" class="col-md-2 col-form-label">平台名稱</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['platform_name'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_platform_name" name='platform_name' required>
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_description" class="col-md-2 col-form-label">平台簡介</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['description'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_description" name='description' required>
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_mission" class="col-md-2 col-form-label">平台使命</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['mission'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_mission" name='mission' >
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_vision" class="col-md-2 col-form-label">平台願景</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['vision'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_vision" name='vision' >
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3 ">
              <label for="txt_create_date" class="col-md-2 col-form-label">建檔日期：</label>
              <div class="col-md-4">
                <?php echo $result['create_date']; ?>
              </div>
            </div>

            <div class="row mb-3 ">
              <label for="txt_updated_by" class="col-md-2 col-form-label">更新人員：</label>
              <div class="col-md-4">
                <?php echo $result['updated_by']; ?>
              </div>
              <label for="txt_update_date" class="col-md-2 col-form-label">更新日期：</label>
              <div class="col-md-4">
                <?php echo $result['update_date']; ?>
              </div>
            </div>
            <hr>
            <div class="row ">
              <?php if ($idStart < 0) { ?>
                <div class="col-md-3">
                  <button type="button" class="btn btn-success" onclick="changeToEdit(<?= $result['description_id'] ?>)">
                    編輯
                  </button>
                </div>
              <?php } else { ?>
                <div class="col-md-3">
                  <a class="btn btn-secondary w-100" id="cancelButton" href="platform_description.php" role="button">取消</a>
                </div>
                <div class="col-md-3 text-center">
                  <button type="submit" id="saveButton" name="action" value="update" class="btn btn-info">
                    儲存
                  </button>
                </div>
              <?php } ?>
            </div>

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

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

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

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->

  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/tinymce/tinymce.min.js"></script>

  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>

  <script>
    function changeToEdit (id) {

      window.location.href = "platform_description.php?id=" + id;

    }
  </script>

</body>

</html>