<?php
include_once '../src/inc/db/function.php';
// 初始化變數
$platform_id = $itemNo = $itemName = $itemNote = "";
$flag_view = '1';
$isEditing = false;
$itemNo = "team"; // $_POST['itemNo'];
// 檢查是否有提交的資料
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $platform_id = isset($_POST['platform_id']) ? $_POST['platform_id'] : null;

  $itemName = $_POST['itemName'];
  $itemNote = $_POST['itemNote'];
  $flag_view = isset($_POST['flag_view']) ? $_POST['flag_view'] : '0';

  if ($platform_id) {
    // 更新現有記錄
    // 更新現有資料
    $platform_id = $_POST["platform_id"];
    $sql = "UPDATE platform SET itemNo=?, itemName=?, itemNote=?, flag_view=? WHERE platform_id=?";
    $stmt = $conn->prepare($sql);
    // $stmt->bind_param("ssssi", $itemNo, $itemName, $itemNote, $flag_view, $platform_id);
    $stmt->execute([$itemNo, $itemName, $itemNote, $flag_view, $platform_id]);
    // $stmt->execute();
  } else {
    // 插入新資料
    $sql = "INSERT INTO platform (itemNo, itemName, itemNote, flag_view) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$itemNo, $itemName, $itemNote, $flag_view]);
    $platform_id = $conn->lastInsertId();
    //  $stmt->bind_param("ssss", $itemNo, $itemName, $itemNote, $flag_view);
    // $stmt->execute();
  }

  $_SESSION['message'] = "資料已成功保存！";
  header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $platform_id);
  exit();
}
// 如果有 ID 參數,則載入現有資料
$platform_id = isset($_GET['id']) ? $_GET['id'] : null;
//if ($platform_id) {
$stmt = $conn->prepare("SELECT * FROM platform WHERE platform_id = ? || itemNo = ?  LIMIT 0,1");
$stmt->execute([$platform_id, $itemNo]);
if ($row = $stmt->fetch()) {
  $platform_id = $row['platform_id'];
  $itemNo = $row['itemNo'];
  $itemName = $row['itemName'];
  $itemNote = $row['itemNote'];
  $flag_view = $row['flag_view'];
  $isEditing = true;
} else {
  $itemName = "執行團隊";
  $itemNote = "執行團隊";
}
?>
<!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"; ?>

</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 active">執行團隊</li>
          <li class="breadcrumb-item"> <?php echo $isEditing ? '修改' : '新增'; ?></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">
      <!-- BRGIN SEARCHTABLE -->
      <div class="card info-card sales-card">
        <div class="card-body">
          <?php
          if (isset($_SESSION['message'])) {
            echo "<p>" . $_SESSION['message'] . "</p>";
            unset($_SESSION['message']);
          }
          ?>

          <form method="POST" action="" id="platformForm">
            <input type="hidden" name="platform_id" value="<?php echo htmlspecialchars($platform_id); ?>">

            <div class="row mb-3">
              <label for="itemName" class="form-label col-md-2">項目名稱:</label>
              <div class="col-md-4">
                <input type="text" class=" form-control" id="itemName" name="itemName" value="<?php echo htmlspecialchars($itemName); ?>" required>
              </div>
              <div class=" offset-2 col-md-4 d-flex">
                <label for="flag_view" class="form-check-label">是否顯示:</label>&nbsp;&nbsp;
                <input type="radio" class=" form-check-input" id="flag_view_1" name="flag_view" value="1" <?php if ($flag_view === '1') echo 'checked'; ?>> 是
                &nbsp;<input type="radio" class=" form-check-input" id="flag_view_0" name="flag_view" value="0" <?php if ($flag_view === '0') echo 'checked'; ?>> 否
              </div>
            </div>

            <div class="row mb-3 ">
              <ul class="nav  nav-tabs nav-justified">
                <li class="nav-item">
                  <a class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab1">內容編輯</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" data-bs-toggle="tab" data-bs-target="#tab2">原始碼</a>
                </li>
              </ul>
              <div class="tab-content" id="myTabContent">
                <div class="tab-pane fade show active" id="tab1">
                  <div id="editor" style="min-height: 350px;height:60%;"></div>
                </div>
                <div class="tab-pane fade" id="tab2">
                  <textarea name="itemNote" id="itemNote" class=" form-text" style="width: 100%;min-height: 350px;height:60%;">
                  <?php echo htmlspecialchars($itemNote); ?>
                  </textarea>
                </div>
              </div>
              <!--  <label for="itemNote" class="form-label col-md-2">內容:</label>             
              <input type="hidden" name="itemNote" id="itemNote"> -->
            </div>

            <div class="row ">
              <div class="col-md-6">
                <button type="submit" class="btn btn-success"><?php echo $isEditing ? "更新" : "新增"; ?></button>
              </div>
            </div>
          </form>
        </div>
      </div>
      <!-- END SEARCHTABLE -->


    </section>

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


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

  <link href="../assets/css/quill.snow2.2.css" rel="stylesheet" />
  <script src="../assets/js/quill-2.2.js"></script>

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

    // 初始化 Quill 編輯器
    /* const toolbarOptions = [      
          [{'header': [1, 2, 3, 4, 5, 6, false]}], //字體大小
        //  [{'size': ['small', false, 'large', 'huge']  }], //字體大小
          ['bold', 'italic', 'underline', 'strike'], // toggled buttons
         // ['blockquote', 'code-block'],
          ['link', 'image'],//, ['video', 'formula'],     
          [{'list': 'ordered'  }, { 'list': 'bullet' }],//, { 'list': 'check' }],
          [{'script': 'sub'}, {'script': 'super' }],//上標/下標superscript/subscript
          [{ 'indent': '-1'}, {  'indent': '+1'  }], // outdent/indent 減少縮排/縮排
        //  [{ 'direction': 'rtl'}],// text direction 文字方向,靠左/右     
          [{ 'color': []}, { 'background': [] },{ 'align': [] }], 
        //  [{'font': []}],//字型      ['align': [] }],// 對齊    
          [ 'table','clean'] // 添加表格按钮 ,remove formatting button
        ]; */
    const toolbarOptions = [
      [{
        'header': [1, 2, 3, 4, 5, 6, false]
      }], //字體大小
      ['bold', 'italic', 'underline', 'strike', 'link', 'image', 'table'],
      [{
        'list': 'ordered'
      }, {
        'script': 'sub'
      }, {
        'script': 'super'
      }],
      [{
        'indent': '-1'
      }, {
        'indent': '+1'
      }, {
        'align': []
      }, {
        'color': []
      }, {
        'background': []
      }, 'clean']
    ];
    var quill = new Quill('#editor', {
      theme: 'snow',
      modules: {
        toolbar: toolbarOptions,
      },
    });

    // 監聽 Quill 編輯器的變更事件
    quill.on('text-change', function() {
      // 將 Quill 的純文字內容同步到 #itemNote, console.log("text-change");
      $("#itemNote").val(quill.root.innerHTML);
    });
    $("#itemNote").on('blur', function() {
      //quill.root.innerHTML = $("#itemNote").val();
      $("#platformForm").submit();
    });

    // 設置初始內容
    quill.root.innerHTML = <?php echo json_encode($itemNote); ?>;
    // 在表單提交時將編輯器內容保存到隱藏的輸入框中
    /*  document.getElementById('platformForm').onsubmit = function() {
       document.getElementById('itemNote').value = quill.root.innerHTML;
     }; */

    /* function changeToEdit() {
      window.location.href = "teamEdit.php";
    } */
  </script>

</body>

</html>