<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Created Salary Record</title>
  <link rel="stylesheet"
    href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
    integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />
  <link href="//cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="/css/admin.css">
</head>

<body class="hold-transition sidebar-mini">
  <div class="wrapper">
    <!-- Include navigation -->
    <%- include('nav') %>
      <div class="content-wrapper">
        <section class="content-header">
          <div class="container-fluid">
            <div class="row mb-2">
              <div class="col-sm-6">
                <h1>Created Salary Record</h1>
              </div>
            </div>
          </div>
        </section>

        <!-- Main content -->
        <section class="content">
          <div class="card">
            <div class="card-body">
              <form id="salaryForm" method="POST">
                <div class="mb-3">
                  <label for="phoneNumber" class="form-label">Phone Number</label>
                  <input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" required>
                </div>

                <div class="mb-3">
                  <label for="amount" class="form-label">Amount</label>
                  <input type="number" class="form-control" id="amount" name="amount" required>
                </div>

                <div class="mb-3">
                  <label for="type" class="form-label">Type</label>
                  <select class="form-control" id="type" name="type" required>
                    <option value="" selected disabled>Select Type</option>
                    <option value="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                    <option value="monthly">Monthly</option>
                  </select>
                </div>

                <button type="submit" class="btn btn-primary" id="submit">Submit</button>
              </form>
            </div>
          </div>

          <div class="card">
            <div class="card-body">
              <h5 class="card-title">Salary Records Table</h5>
              <table class="table" id="tableget">
                <thead>
                  <tr>
                    <!-- <th>#</th> -->
                    <th class="text-center">Phone</th>
                    <th class="text-center">Amount</th>
                    <th class="text-center">Type</th>
                    <th class="text-center">Time</th>
                  </tr>
                </thead>
                <tbody>
                  <!-- Add your table rows dynamically here -->
                </tbody>
              </table>
            </div>
          </div>
        </section>
      </div>
  </div>

  <!-- Include scripts -->
  <script src="/plugins/jquery/jquery.min.js"></script>
  <script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="/dist/js/adminlte.min.js"></script>
  <script src="/js/admin/admin.js"></script>
  <script src="//cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
  <script>
    $(document).ready(function () {
      function formateT(params) {
        let result = params < 10 ? "0" + params : params;
        return result;
      }
      function timerJoin(params = "", addHours = 0) {
        let date = "";
        if (params) {
          date = new Date(Number(params));
        } else {
          date = new Date();
        }

        date.setHours(date.getHours() + addHours);

        let years = formateT(date.getFullYear());
        let months = formateT(date.getMonth() + 1);
        let days = formateT(date.getDate());

        let hours = date.getHours() % 12;
        hours = hours === 0 ? 12 : hours;
        let ampm = date.getHours() < 12 ? "AM" : "PM";

        let minutes = formateT(date.getMinutes());
        let seconds = formateT(date.getSeconds());

        return (
          years +
          "-" +
          months +
          "-" +
          days +
          " " +
          hours +
          ":" +
          minutes +
          ":" +
          seconds +
          " " +
          ampm
        );
      }

  $("#salaryForm").on("click", "#submit", function (e) {
    e.preventDefault();

    let phoneNumber = $("#phoneNumber").val().trim();
    let amount = $("#amount").val().trim();
    let type = $("#type").val().trim();

    $.ajax({
      type: "POST",
      url: "/api/webapi/admin/CreatedSalary",
      dataType: "JSON",
      data: {
        phone: phoneNumber,
        amount: amount,
        type: type,
      },
      success: function (response) {
        // Handle success, e.g., show a success message
        console.log('Response data success:', response.message);
        Swal.fire(
            'UPDATED SUCCESSFULLY',
            'success'
          )
          document.getElementById('salaryForm').reset();
        // Fetch the updated data and reload the table
        fetchAndUpdateTable();
      },
      error: function (error) {
        // Handle error, e.g., show an error message
        console.log('Response data error:', JSON.stringify(error));
        Swal.fire({
            title: "Something went wrong!",
          });
      }
    });
  });

  // Function to fetch and update the table data
  function fetchAndUpdateTable() {
    $.ajax({
      type: "GET",
      url: "/api/webapi/admin/getSalary",
      dataType: "json",
      success: function (response) {
        // Update the table with the new data
        updateTable(response);
        
      },
      error: function (xhr, status, error) {
        console.log('Error fetching data:', error);
        
      }
    });
  }

  // Function to update the table with new data
  function updateTable(data) {
    if (Array.isArray(data.rows) && data.rows.length > 0) {
      var tableBody = $('#tableget').find('tbody');
      tableBody.empty();

      data.rows.forEach(function (item) {
        var row = '<tr>' +
          '<td class="text-center">' + item.phone + '</td>' +
          '<td class="text-center">' + item.amount + '</td>' +
          '<td class="text-center">' + item.type + '</td>' +
          '<td class="text-center">' + timerJoin(item.time) + '</td>' +
          '</tr>';
        tableBody.append(row);
      });
    } else {
      console.log('No data found or invalid response format');
    }
  }

  // Initial load of table data
  fetchAndUpdateTable();
});

  </script>
</body>

</html>