<?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 !== '-1') {

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

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

    }

  }

  if ($idStart === '-1' || $result === null) {

    // $result = array('userName' => null, 'custName' => null, 'password' => null, 'email' => null, 'lastName' => null, 'registration_date' => $today, 'status' => null, 'custRank' => null, 'email' => null, 'phone' => null, 'gender' => null, 'age' => null, 'emailConfirm' => null);
    // $result = array('member_id' => -1, 'registration_date' => $today, 'status' => 'active');

  } else {

    $num = $stmt->rowCount();

  }

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

} else {

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

}

$add = ($num > 0) ? "update" : "insert";

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
  $user_id = isset($_POST['user_id']) && $_POST['user_id'] !== '' ? $_POST['user_id'] : 0;
  if ($_POST['action'] == 'delete') {
    if ($user_id > 0) {
      $sql = "DELETE FROM users WHERE user_id = ? ";
      $stmt = $conn->prepare($sql);
      $stmt->execute([$user_id]);
    }
    header("Location: userData.php");
    exit();
  }
  /*** DATA ***/
  $userName = isset($_POST['userName']) && $_POST['userName'] !== '' ? htmlspecialchars(trim($_POST['userName']), ENT_QUOTES, 'UTF-8') : null;
  $email = isset($_POST['email']) && $_POST['email'] !== '' ? htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8') : null;
  $phone = isset($_POST['phone']) && $_POST['phone'] !== '' ? htmlspecialchars(trim($_POST['phone']), ENT_QUOTES, 'UTF-8') : null;
  // $registration_date = !empty($_POST['registration_date']) ? htmlspecialchars(trim($_POST['registration_date']), ENT_QUOTES, 'UTF-8') : $today;
  $status = !empty($_POST['status']) ? htmlspecialchars(trim($_POST['status']), ENT_QUOTES, 'UTF-8') : 'active';
  $password = isset($_POST['password']) && $_POST['password'] !== '' ? $_POST['password'] : $email;
  $mPasswd = isset($_POST['mPasswd']) && $_POST['mPasswd'] !== '' ? $_POST['mPasswd'] : null;

  $userName = checkData($userName, "string");
  $email = checkData($email, "string");
  $phone = checkData($phone, "string");
  // $registration_date = checkData($registration_date, "date");
  $status = checkData($status, "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'] == 'insert') {
        $sql = "Select userName FROM users WHERE userName = ? ";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$userName]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
          $error = '此帳號已存在';
        } else {
          $mhsah1 = password_hash($password, PASSWORD_DEFAULT);
          $fieldarray = array(
            'userName' => $userName,            
            'userPassword' =>	$mhsah1,
            'email' => $email,
            'phone' => $phone,
            'userStatus' => $status,
            'updated_by'=>$VR_UserNo,
            'create_date' =>  date("Y-m-d H:i:s"),
            'update_date' =>  date("Y-m-d H:i:s")
          );
          $n_member_id = insert_data1("users", $fieldarray);
          header("Location: userData.php");
          exit();
        }
      } else if ($_POST['action'] == 'update') {       

        if($password != $mPasswd){
          $mhsah1 = password_hash($password, PASSWORD_DEFAULT);
        } else {
          $mhsah1 = $mPasswd;
        }
        $fieldarray = array(
          'email' => $email,
          'status' => $status,
          'phone' => $phone,
          'userPassword' =>	$mhsah1,
          'updated_by'=>$VR_UserNo,
          'update_date' =>  date("Y-m-d H:i:s")
        );
        $where_claud ="member_id= $member_id";
        $n_member_id=update_data("users", $fieldarray,$where_claud );
       
        header("Location: userData.php");
      }
    } catch (PDOException $e) {
      $error = $e->getMessage();
    }
    if ($error === '') {
      header("Location: userData.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 src="assets/js/Publicfun.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() {

      $("#UserAccount-nav").addClass("show");
      $("#userData").addClass("active");

      var data = <?= $jsonData ? $jsonData : 'null' ?>;
      // form1.registration_date.value = data.registration_date.split(' ')[0] || '';
      // form1.status.value = data.status.split(' ')[0] || '';
      if (data !== null && $("#member_id").val() > 0) {
        // form1.userName.value = data.userName || '';
        // form1.custName.value = data.custName || '';
        form1.mPasswd.value=data.password ;
        $("#form1").find("[id*='txt_']").each(function() {
          var key = $(this).attr("name");
          var value = data[key] || '';
          $(this).val(escapeHtml(value));
            // $(this).val(data[key] || '');
          // var value = chkNull(data[key]);  
          // console.log(key, $(this).val());
        });
      } 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, "沒有數據可顯示");
      }

      /* $("#startDay,#endDay").datepicker({
        dateFormat: 'yy-mm-dd'
      }); */
      if($("#member_id").val() > 0){
        $("#saveButton").val("update");
        $("#deleteButton").css("display","block");
        $("#txt_userName").attr("readonly", "readonly");
      }else{
        $("#saveButton").val("insert");
        $("#deleteButton").css("display","none");
        $("#txt_userName").removeAttr("readonly");
      }
      
    });

  </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"><a href="userData.php">會員資料</a></li>
        </ol>
      </nav>
      <!--END BREADCRUMB-->
    </div><!-- End Page Title -->

    <section class="section dashboard">
      <!--BEGIN FORM-->
      <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="act" name="act" value="<?= $add ?>" />
            <input type='hidden' id="member_id" name='member_id' value='<?=$idStart?>'>
            <input type='hidden' id="mPasswd" name='mPasswd' >
            <input type="hidden" name="csrfToken" value="<?php echo htmlspecialchars($_SESSION['csrfToken'], ENT_QUOTES, 'UTF-8'); ?>">
            <div class="row mb-3">
              <label for="txt_userName" class="col-md-2 col-form-label">帳號</label>
              <div class="col-md-4">
                <input type="text" class="form-control" id="txt_userName" name="userName"  required>
              </div>

              <label for="txt_password" class="col-md-2 col-form-label">密碼</label>
              <div class="col-md-4">
                <input id="txt_password" name="password" maxlength="250"  required placeholder="預設(電子信箱)" type="password" class="form-control lab_pwd ">
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_email" class="col-md-2 col-form-label">電子郵件</label>
              <div class="col-md-10">
                <input type="text" class="form-control" id="txt_email" name="email" required>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_phone" class="col-md-2 col-form-label">電話號碼</label>
              <div class="col-md-4">
                <input type="text" class="form-control" id="txt_phone" name="phone">
              </div>

              <?php if ($add == "update") { ?>
                <label for="txt_registration_date" class="col-md-2 col-form-label">註冊日期</label>
                <div class="col-md-4">
                  <input type="date" class="form-control" id="txt_registration_date" name="registration_date" readonly>
                </div>
              <?php } ?>
            </div>

            <div class="row mb-3">
              <?php if ($add == "update") { ?>
                <label for="txt_last_login" class="col-md-2 col-form-label">最後登入時間</label>
                <div class="col-md-4">
                  <input type="date" class="form-control" id="txt_last_login" name="last_login" readonly>
                </div>
              <?php } ?>

              <label for="txt_status" class="col-md-2 col-form-label">會員狀態</label>
              <div class="col-md-4">
                <input type="date" class="form-control" id="txt_status" name="status">
              </div>
            </div>

            <?php if ($add == "update") { ?>
              <div class="row mb-3 ">
                <label for="txt_updated_by" class="col-md-2 col-form-label">更新人員：</label>
                <div class="col-md-4">
                  <input class="form-control" type="text" id="txt_updated_by" name="updated_by" readonly />
                </div>
                <label for="txt_updated_by" class="col-md-2 col-form-label">更新日期：</label>
                <div class="col-md-4">
                  <input class="form-control" type="text" id="txt_update_date" name="update_date" readonly />
                </div>
              </div>
            <?php } ?>
            <hr>
            <div class="row ">             
              <div class="col-md-3">
                <a class="btn btn-secondary w-100" id="cancelButton" href="userData.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(<?php echo $idStart; ?>)">
                  刪除
                </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>
      </div>
      <!--END FORM-->

    </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 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>