<!DOCTYPE html>
<html>

<head>
  <title>Pulse Attendance System</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/dt-1.11.3/datatables.min.css" />
  <style>
    .title-bar {
      background-color: green;
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="title-bar ps-5 col-10">
        <h2>Pulse Attendance System</h2>
      </div>
      <!--<div class="title-bar text-center col-1">
        <button class="btn btn-info" id="" data-bs-toggle="modal" data-bs-target="#loginModal1Hr">Hr Login</button>
      </div>-->
        <div class="title-bar text-center col-1">
        <button class="btn btn-info" id="" data-bs-toggle="modal" data-bs-target="#loginModal1">Login</button>
      </div>
    </div>
  </div>

  <div class="container mt-5">
    <hr>
    <div class="mb-3 row">
      <div class="col-md-4">
        <div class="input-group">
          <input type="text" class="form-control" id="datetime-picker" placeholder="Select datetime">
          <button class="btn btn-primary" onclick="getDataByDatetime()">Get Records</button>
          <button class="btn btn-primary mx-2" onclick="updateRecords()">Update Records</button>
        </div>
      </div>
      <div class="col-md-8 d-flex justify-content-end">
        <button class="btn btn-primary mx-2" onclick="downloadAsPDF()">Download as PDF</button>
        <button class="btn btn-info mx-2" id="redirectLeave">Apply for Leave</button>
        <button class="btn btn-info mx-2" id="lateinEmployee">Month Wise Reports</button>
      </div>
    </div>
    <hr>
    <!-- <button class="btn btn-primary" onclick="downloadAsPDF()">Download as PDF</button>
        <button class="btn btn-primary float-end" onclick="updateRecords()">Update Records</button> -->
    <table class="table table-striped mt-3" id="data-table"></table>
  </div>
  <!-- -----------------------------LogIn Modal for Update data----------------------------------------------------- -->
  <!-- Login Modal -->
  <div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="loginModalLabel">Login</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="loginForm">
            <div class="mb-3">
              <label for="username" class="form-label">Username</label>
              <input type="text" class="form-control" id="username" placeholder="Enter username">
            </div>
            <div class="mb-3">
              <label for="password" class="form-label">Password</label>
              <input type="password" class="form-control" id="password" placeholder="Enter password">
            </div>
            <div class="d-grid gap-2">
              <button type="submit" class="btn btn-primary">Login</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  <!-- -------------------------------Login Modal for aproval-------------------------------------------------- -->
  <!-- First Login Modal -->
  <div class="modal fade" id="loginModal1" tabindex="-1" aria-labelledby="loginModalLabel1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="loginModalLabel1">Officials Login</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <!-- Login form for Modal 1 -->
          <form>
            <div class="mb-3">
              <label for="username1" class="form-label">Username</label>
              <input type="text" class="form-control" id="username1" name="username1" required>
            </div>
            <div class="mb-3">
              <label for="password1" class="form-label">Password</label>
              <input type="password" class="form-control" id="password1" name="password1" required>
            </div>
            <button class="btn btn-primary" id="loginForm1">Login</button>
          </form>
        </div>
      </div>
    </div>
  </div> <!-- -------------------------------Login Modal for aproval-------------------------------------------------- -->
  <!-- First Login Modal -->
  <div class="modal fade" id="loginModal1Hr" tabindex="-1" aria-labelledby="loginModalLabel1Hr" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="loginModalLabel1Hr">HR Login</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <!-- Login form for Modal 1 -->
          <form>
            <div class="mb-3">
              <label for="username1Hr" class="form-label">Username</label>
              <input type="text" class="form-control" id="username1Hr" name="username1Hr" required>
            </div>
            <div class="mb-3">
              <label for="password1Hr" class="form-label">Password</label>
              <input type="passwordHr" class="form-control" id="password1Hr" name="password1Hr" required>
            </div>
            <button class="btn btn-primary" id="loginForm1Hr">Login</button>
          </form>
        </div>
      </div>
    </div>
  </div>
  <!-- --------------------------------------------------------------------------------------------- -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.11.3/datatables.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

  <script>
    $(document).ready(function () {
      localStorage.removeItem('token'); // Clear the token
      // Initialize datetime picker
      $('#datetime-picker').daterangepicker({
        timePicker: true,
        singleDatePicker: true,
        showDropdowns: true,
        locale: {
          format: 'YYYY-MM-DD HH:mm:ss'
        }
      });
      // Handle login form submission
      $('#loginForm1').on('click', function (event) {
        event.preventDefault();

        const username = $('#username1').val();
        const password = $('#password1').val();

        var credentials = {
          username: username,
          password: password
        };
        // Send login data to your server for authentication
        // Assume your server returns a token upon successful login
        $.ajax({
          url: '../api/account/login',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(credentials),
          success: function (response) {
              localStorage.setItem('token', response.token); // Replace with your token key
              if (response.name == 'Faiz-ul-hassan')
            window.location.href = 'leaveapproval.html';
              else
                  window.location.href = 'leaveapprovalHead.html';

          },
          error: function () {
            alert("Invalid username or password. Please try again.");
          }
        });
      });
       // Handle login form submission
        $('#loginForm1Hr').on('click', function (event) {
        event.preventDefault();

            const username = $('#username1Hr').val();
            const password = $('#password1Hr').val();

        var credentials = {
          username: username,
          password: password
        };
        // Send login data to your server for authentication
        // Assume your server returns a token upon successful login
        $.ajax({
          url: '../api/account/login',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(credentials),
          success: function (response) {
            localStorage.setItem('token', response.token); // Replace with your token key
              window.location.href = 'hrpage.html';
          },
          error: function () {
            alert("Invalid username or password. Please try again.");
          }
        });
      });

    });
      function dataGet() {
        $.ajax({
          url: "../api/DataTransfer/TodayAttendanceData",
          method: "GET",
          dataType: "json",
          success: function (data) {
            var tableBody = $("#data-table-body");

            function formatDate(dateString) {
              const defaultDateTime = "Jan 01, 1970, 05:00:00 AM";
              const defaultDateTime1900 = "Jan 01, 1900, 12:00:00 AM";
              const date = new Date(dateString);
              const options = {
                year: "numeric",
                month: "short",
                day: "2-digit",
                hour: "2-digit",
                minute: "2-digit",
                second: "2-digit",
              };

              // Check if the date is the default value or earlier than 2023
              if (
                date.toLocaleString("en-US", options) ===
                new Date(defaultDateTime).toLocaleString("en-US", options) ||
                date.toLocaleString("en-US", options) ===
                new Date(defaultDateTime1900).toLocaleString("en-US", options) ||
                date.getFullYear() < 2023
              ) {
                return "";
              }

              return date.toLocaleString("en-US", options);
            }

            var i = 0;
            var tableBody = $("<tbody>"); // Create tbody element

            $.each(data, function (index, item) {

              // Skip the record when active is false
              if (!item.Active) {
                return; // Skip this iteration of the loop
              }
              // Check if the displayname is empty or contains only whitespace
              if (
                item.displayname === "Administrator" ||
                item.displayname === "ext-system" ||
                item.displayname === "All User" ||
                item.displayname === "All User Groups" ||
                item.displayname === "All" ||
                !item.displayname ||
                item.displayname.trim() === ""
              ) {
                return; // Skip this iteration of the loop
              }

           //   console.log(data)

              var row = $("<tr>");
              $("<td>").text(i += 1).appendTo(row);
              $("<td>").text(item.displayname).appendTo(row);
              $("<td>").text(formatDate(item.AttendanceDateIn)).appendTo(row);
              $("<td>").text(formatDate(item.AttendanceDateOut)).appendTo(row);
              $("<td>").text(item.LateIn ? "Late In" : "").appendTo(row);
              $("<td>").text(item.EarlyOut ? "Early Out" : "").appendTo(row);

              // Calculate working hours if both AttendanceDateIn and AttendanceDateOut are available
              if (item.AttendanceDateIn && item.AttendanceDateOut) {
                var dateIn = new Date(item.AttendanceDateIn);
                var dateOut = new Date(item.AttendanceDateOut);
                var diff = dateOut - dateIn;
                var hours = Math.floor(diff / 1000 / 60 / 60);
                var minutes = Math.floor((diff / 1000 / 60) % 60);
                $("<td>").text(hours + "h " + minutes + "m").appendTo(row);
              } else {
                $("<td>").text("").appendTo(row);
              }

              $("<td>").text(item.AbsentStatus ? "Absent" : "").appendTo(row);
              $("<td>").html(item.Designation + "<br>(" + item.Department + ")").appendTo(row);

              // Set row color based on late in, early out, or absent status
              if (item.LateIn) {
                row.css("background-color", "lightyellow");
              }
              if (item.AbsentStatus) {
                row.css("background-color", "#FFE18C"); // Lighter shade of red
              }
              if (item.EarlyOut) {
                row.css("background-color", "#FF9494"); // Lighter shade of red
              }
              row.appendTo(tableBody);
            });

            var table = `<thead>
                                    <tr>
                                        <th>Sr</th>
                                        <th>Name</th>
                                        <th>Date In</th>
                                        <th>Date Out</th>
                                        <th>Late In</th>
                                        <th>Early Out</th>
                                        <th>Working Hours</th>
                                        <th>Status</th>
                                        <th>Designation/Department</th>
                                    </tr>
                                    </thead>`;

            $("#data-table").empty(); // Clear the table
              $("#data-table").append(table).append(tableBody); // Append the table head and body



            // Apply DataTables plugin for sorting
            if ($.fn.DataTable.isDataTable("#data-table")) {
              $("#data-table").DataTable().destroy();
            }
            $("#data-table").DataTable({
              "pageLength": 25
            });




          },
          error: function () {
            alert("Error fetching data from the server.");
          },
        });
      }

      dataGet();

      var table = dataGet();

      //-------------------------Read Row and Fetch Data of Row----------------------

      //$('#data-table').on('click', 'tbody tr', function () {
      //    console.log('API row values : ', $('#data-table').DataTable().row(this).data());
      //})

  
      // -------------------------temp work------------------------------------------
      function getDataByDatetime() {
        var datetime = $('#datetime-picker').val();

        if (datetime) {
          $.ajax({
            url: "../api/DataTransfer/AttendanceData",
            method: "GET",
            dataType: "json",
            success: function (data) {
              var tableBody = $("#data-table-body");

              function formatDate(dateString) {
                const defaultDateTime = "Jan 01, 1970, 05:00:00 AM";
                const defaultDateTime1900 = "Jan 01, 1900, 12:00:00 AM";
                const date = new Date(dateString);
                const options = {
                  year: "numeric",
                  month: "short",
                  day: "2-digit",
                  hour: "2-digit",
                  minute: "2-digit",
                  second: "2-digit",
                };

                // Check if the date is the default value or earlier than 2023
                if (
                  date.toLocaleString("en-US", options) ===
                  new Date(defaultDateTime).toLocaleString("en-US", options) ||
                  date.toLocaleString("en-US", options) ===
                  new Date(defaultDateTime1900).toLocaleString("en-US", options) ||
                  date.getFullYear() < 2023
                ) {
                  return "";
                }

                return date.toLocaleString("en-US", options);
              }
              var i = 0;
              var tableBody = $("<tbody>"); // Create tbody element

              $.each(data, function (index, item) {

                // Skip the record when active is false
                if (!item.Active) {
                  return; // Skip this iteration of the loop
                }
                // Check if the created_date matches the input date
                var createdDate = new Date(item.CreatedDate).toLocaleDateString();
                var inputDate = new Date(datetime).toLocaleDateString();

                if (createdDate !== inputDate) {
                  return; // Skip this iteration of the loop
                }
                // Check if the displayname is empty or contains only whitespace
                if (
                  item.displayname === "Administrator" ||
                  item.displayname === "ext-system" ||
                  item.displayname === "All User" ||
                  item.displayname === "All User Groups" ||
                  item.displayname === "All" ||
                  !item.displayname ||
                  item.displayname.trim() === ""
                ) {
                  return; // Skip this iteration of the loop
                }

                var row = $("<tr>");
                $("<td>").text(i += 1).appendTo(row);
                $("<td>").text(item.displayname).appendTo(row);
                $("<td>").text(formatDate(item.AttendanceDateIn)).appendTo(row);
                $("<td>").text(formatDate(item.AttendanceDateOut)).appendTo(row);
                $("<td>").text(item.LateIn ? "Late In" : "").appendTo(row);
                $("<td>").text(item.EarlyOut ? "Early Out" : "").appendTo(row);

                // Calculate working hours if both AttendanceDateIn and AttendanceDateOut are available
                if (item.AttendanceDateIn && item.AttendanceDateOut) {
                  var dateIn = new Date(item.AttendanceDateIn);
                  var dateOut = new Date(item.AttendanceDateOut);
                  var diff = dateOut - dateIn;
                  var hours = Math.floor(diff / 1000 / 60 / 60);
                  var minutes = Math.floor((diff / 1000 / 60) % 60);
                  $("<td>").text(hours + "h " + minutes + "m").appendTo(row);
                } else {
                  $("<td>").text("").appendTo(row);
                }

                $("<td>").text(item.absent_status ? "Absent" : "").appendTo(row);
                $("<td>").html(item.Designation + "<br>(" + item.Department + ")").appendTo(row);

                // Set row color based on late in, early out, or absent status
                if (item.LateIn) {
                  row.css("background-color", "lightyellow");
                }
                if (item.AbsentStatus) {
                  row.css("background-color", "#FFE18C"); // Lighter shade of red
                }
                if (item.EarlyOut) {
                  row.css("background-color", "#FF9494"); // Lighter shade of red
                }
                row.appendTo(tableBody);
              });

              var table = `<thead>
                                        <tr>
                                            <th>Sr</th>
                                            <th>Name</th>
                                            <th>Date In</th>
                                            <th>Date Out</th>
                                            <th>Late In</th>
                                            <th>Early Out</th>
                                            <th>Working Hours</th>
                                            <th>Status</th>
                                            <th>Designation/Department</th>
                                        </tr>
                                        </thead>`;

              $("#data-table").empty(); // Clear the table
              $("#data-table").append(table).append(tableBody); // Append the table head and body

              // Apply DataTables plugin for sorting
              if ($.fn.DataTable.isDataTable("#data-table")) {
                $("#data-table").DataTable().destroy();
              }
              $("#data-table").DataTable({
                "pageLength": 25
              });

            },
            error: function () {
              alert("Error fetching data from the server.");
            },
          });
        } else {
          alert("Please select a datetime.");
        }
      }


      // ---------------------------------------------------------------------------


      function downloadAsPDF() {
        const element = document.getElementById('data-table');

        // Define custom options for PDF generation
        const options = {
          filename: 'attendance.pdf',
          orientation: 'landscape', // Set the orientation to landscape
          jsPDF: {
            format: 'a4',
            orientation: 'landscape',
          },
          html2canvas: {
            scale: 2,
            useCORS: true,
            letterRendering: true,
          },
        };

        html2pdf()
          .set(options) // Set the custom options
          .from(element)
          .save();
      }

      function updateRecords() {
        // Open the login modal
        $('#loginModal').modal('show');

        // Handle form submission
        $('#loginForm').on('submit', function (event) {
          event.preventDefault(); // Prevent form submission

          var username = $('#username').val();
          var password = $('#password').val();

          var credentials = {
            username: username,
            password: password
          };

          // Perform token validation using an API call or other method
          // Replace the following code with your own token validation logic
          // Assume tokenValidationAPI is the URL for your token validation API endpoint
          $.ajax({
            url: '../api/account/login',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(credentials),
            success: function (response) {
              // Token validation successful
              $('#loginModal').modal('hide'); // Hide the login modal
              var token = response.token; // Assuming the token is returned in the response
              console.log(token)
              // Add your code to update the records using an API call here
              $.ajax({
                url: "../api/users/UpdateRecords",
                method: "POST",
                headers: {
                  "Authorization": "Bearer " + token
                },
                success: function (response) {
                  dataGet();
                  alert("Records updated successfully!");
                  // Refresh the table data if needed
                },
                error: function () {
                  alert("Error occurred while updating records.");
                }
              });
            },
            error: function () {
              alert("Invalid username or password. Please try again.");
            }
          });
        });

      }

      $('#redirectLeave').click(function () {
        window.location.href = 'leaveform.html';
      });
      $("#lateinEmployee").click(function () {
        // Redirect to the desired page
        window.location.href = "EmployeeLatein.html";
      });
      $('#loginButton').click(function () {
        // Redirect to the specified page
        window.location.href = 'leaveapproval.html';
      });
  </script>
</body>

</html>