<?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 homepage_settings WHERE setting_id = ?  ";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$idStart]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$result) {

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

    }

  } else {

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

  }

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

} else {

  // $idStart = -1;
  // $sql = "SELECT * FROM homepage_settings 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'])) {
  $setting_id = isset($_POST['setting_id']) && $_POST['setting_id'] !== '' ? $_POST['setting_id'] : 0;

  /*** DATA ***/
  $banner_image_url = isset($_POST['banner_image_url']) && $_POST['banner_image_url'] !== '' ? htmlspecialchars(trim($_POST['banner_image_url']), ENT_QUOTES, 'UTF-8') : null;
  $welcome_message = isset($_POST['welcome_message']) && $_POST['welcome_message'] !== '' ? htmlspecialchars(trim($_POST['welcome_message']), ENT_QUOTES, 'UTF-8') : null;
  $feature_section = isset($_POST['feature_section']) && $_POST['feature_section'] !== '' ? htmlspecialchars(trim($_POST['feature_section']), ENT_QUOTES, 'UTF-8') : null;

  $banner_image_url = checkData($banner_image_url, "string");
  $welcome_message = checkData($welcome_message, "string");
  $feature_section = checkData($feature_section, "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(
          'banner_image_url' => $banner_image_url,
          'welcome_message' => $welcome_message,
          'feature_section' => $feature_section,
          'updated_by'=>$VR_UserNo,
          'update_date' =>  date("Y-m-d H:i:s")
        );
        $where_claud ="setting_id= $setting_id";
        $n_setting_id=update_data("homepage_settings", $fieldarray,$where_claud );
       
        header("Location: homepage_settings.php");
      }
    } catch (PDOException $e) {
      $error = $e->getMessage();
    }
    if ($error === '') {
      header("Location: homepage_settings.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() {
        $("#SystemManage-nav").addClass("show");
        $("#homepage_settings").addClass("active");

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


      var data = <?= $jsonData ? $jsonData : 'null' ?>;
      if (data !== null && $("#setting_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="setting_id" name='setting_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_banner_image_url" class="col-md-2 col-form-label">橫幅圖片網址</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['banner_image_url'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_banner_image_url" name='banner_image_url' required>
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_welcome_message" class="col-md-2 col-form-label">歡迎訊息</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['welcome_message'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_welcome_message" name='welcome_message' required>
                <?php } ?>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_feature_section" class="col-md-2 col-form-label">特色區塊</label>
              <div class="col-md-10">
                <?php if ($idStart < 0) {
                  echo $result['feature_section'];
                 } else { ?>
                  <input type='text' class="form-control" id="txt_feature_section" name='feature_section' required>
                <?php } ?>
              </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['setting_id'] ?>)">
                    編輯
                  </button>
                </div>
              <?php } else { ?>
                <div class="col-md-3">
                  <a class="btn btn-secondary w-100" id="cancelButton" href="homepage_settings.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 = "homepage_settings.php?id=" + id;

    }
  </script>

</body>

</html>