<?php
ob_start();
session_start();
include 'check-userlogin.php';
include 'condb.php';

$strAction = isset($_GET['Action']) ? $_GET['Action'] : '';

if($strAction == "delete")
{
    $log_id = (isset($_POST['log_id']) ? $_POST['log_id'] : '');

    // สร้างคำสั่ง SQL สำหรับการลบ
    $strSQL = "DELETE FROM tbl_login WHERE log_id = '".$log_id."'";
    $objQuery = $conn->query($strSQL);

    if($objQuery){
        echo "success";  // ส่งผลลัพธ์กลับให้ JavaScript ทราบ
    } else {
        echo "error";  // ส่งผลลัพธ์กลับหากมีข้อผิดพลาด
    }
}

if($strAction == "update")
{
   $log_id  = isset($_POST['log_id']) ? trim($_POST['log_id']) : '';
   $status  = isset($_POST['status']) ? trim($_POST['status']) : '';
   $name    = isset($_POST['name']) ? trim($_POST['name']) : '';

   // ใช้ Prepared Statements
   $stmt = $conn->prepare("UPDATE tbl_login SET log_name = ?, log_status = ? WHERE log_id = ?");
   if ($stmt === false) {
       die("Error: " . $conn->error);
   }

   $stmt->bind_param("ssi", $name, $status, $log_id); // "ssi" = string, string, integer
   $result = $stmt->execute();

   if ($result) {
       echo "<script type='text/javascript'>";
       echo "window.location='dashboard';";
       echo "</script>";
   } else {
       echo "<script type='text/javascript'>";
       echo "alert('ERROR: " . htmlspecialchars($conn->error) . "');";
       echo "window.location='javascript:history.back();';";
       echo "</script>";
   }

   $stmt->close();
   $conn->close();

}

?>

<?php include 'navbar.php'; ?>

    <div class="container">
      <div class="row">
        <div class="col-sm-12 col-lg-6 col-12">

          <div class="row">
            <div class="col-sm-12 col-lg-12 col-12">

              <h1>สวัสดี</h1>
              <div class="mb-3">
                <?php echo $_SESSION['username']; ?>
              </div>
              <div class="mb-3">
                <a href="regis.php"> เพิ่มผู้ใช้งาน </a>
              </div>
              <div class="mb-3">
                <a href="logout.php"> ออกจากระบบ </a>
              </div>

            </div>
            <div class="col-sm-12 col-lg-12 col-12">

              <table id="login" class="table table-striped table-hover">
                <thead>
                  <tr>
                    <td>USERNAME</td>
                    <td>ชื่อผู้ใช้</td>
                    <td>เวลาสมัครใช้งาน</td>
                    <td>สถานะ</td>
                    <td></td>
                  </tr>
                </thead>
                <tbody>
                  <?php 
                    $sql = "SELECT * FROM tbl_login";
                    $query = $conn->query($sql);
                    $i = 0;
                    while($row = $query->fetch_assoc()){ $i++; ?>

                  <tr>
                    <td><?php echo $row['log_username']; ?></td>
                    <td><?php echo $row['log_name']; ?></td>
                    <td><?php echo $row['log_date']; ?></td>
                    <td><?php
                      if($row['log_status'] == '1'){
                        echo 'ADMIN';
                      }elseif($row['log_status'] == '2'){
                        echo 'USER';
                      }
                    ?></td>
                    <td>
                      <a href="?update_id=<?php echo $row['log_id']; ?>" class="btn btn-sm btn-outline-warning">แก้ไข</a>
                      <button type="button" id="<?php echo $row['log_id']; ?>" class="btn btn-sm btn-outline-danger delete">ลบ</button>
                    </td>
                  </tr>

                  <?php } ?>
                </tbody>
              </table>

            </div>
          </div>

        </div>
        <div class="col-sm-12 col-lg-6 col-12">
          
          <?php 
            $update_id = isset($_GET['update_id']) ? $_GET['update_id'] : '';

            $sqlUpdate = "SELECT * FROM tbl_login WHERE log_id = '$update_id'";
            $queryUpdate = $conn->query($sqlUpdate);
            $rowUpdate = $queryUpdate->fetch_assoc();

            if($update_id != ''){ ?>

              <form action="?Action=update" method="POST">
                <div class="mb-3">
                    <label for="username" class="form-label">USERNAME</label>
                    <input type="text" class="form-control" id="username" name="username" disabled
                    value="<?php echo $rowUpdate['log_username']; ?>">
                </div>
                  <div class="mb-3">
                      <label for="name" class="form-label">สถานะผู้ใช้งาน</label>
                      <select name="status" class="form-select" aria-label="Default select example" required>
                        <!-- <option selected>Open this select menu</option> -->

                        <?php 

                          if($rowUpdate['log_status'] != ""){
                            
                            if($rowUpdate['log_status'] == '1'){

                              $status = 'ADMIN';

                            }elseif($rowUpdate['log_status'] == '2'){

                              $status = 'USER';

                            }                     

                        ?>

                            <option value="<?php echo $rowUpdate["log_status"]; ?>"><?php echo $status; ?></option>
                            <option disabled>:: เลือก ::</option>

                        <?php } ?>

                        <option value="1">ADMIN</option>
                        <option value="2">USER</option>
                      </select>

                  </div>
                  <div class="mb-3">
                      <label for="name" class="form-label">ชื่อผู้ใช้</label>
                      <input type="text" class="form-control" id="name" name="name"
                      value="<?php echo $rowUpdate["log_name"]; ?>" required>
                  </div>
                <input name="log_id" type="hidden" value="<?php echo $update_id; ?>"/> 
                <button type="submit" class="btn btn-primary">อัพเดตข้อมูล</button>
              </form>

          <?php } ?>

        </div>
      </div>
    </div>

    <script>
        $(document).ready(function(){
            $(document).on('click', '.delete', function(){
                var log_id = $(this).attr("id");

                Swal.fire({
                    title: "ต้องการจะลบข้อมูลใช่ไหม ?",
                    text: "หากลบแล้ว ไม่สามารถกู้คืนได้",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "ลบ",
                    cancelButtonText: "ออก"
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: "?Action=delete", // URL สำหรับการลบข้อมูล
                            method: "POST",
                            data: { log_id: log_id },
                            success: function(response) {
                                Swal.fire({
                                    title: "ลบสำเร็จ",
                                    icon: "success",
                                    showConfirmButton: false,  // ไม่แสดงปุ่ม
                                    timer: 2000  // ตั้งเวลาให้หายไปภายใน 2 วินาที
                                });
                                /*
                                setTimeout(function() {
                                    $('#login').DataTable().ajax.reload();
                                }, 2000);
                                */
                                setTimeout(function() {
                                  location.reload();  // รีเฟรชทั้งหน้า
                                }, 2000);  // หลังจาก 2 วินาที
                            },
                            error: function() {
                                Swal.fire({
                                    title: "Error!",
                                    text: "There was an error deleting the file.",
                                    icon: "error"
                                });
                            }
                        });
                    }
                });
            });
        });
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </body>
</html>
