$(document).ready(function () {
  var table = $('#dataTable').DataTable({
    order: [],
    ajax: {
      url: 'package.php',
      type: 'POST',
      data: {
        type: 'list'
      },
      dataSrc: function (json) {
        return json;
      },
    },
    columns: [
      {
        data: null,
        render: function (data, type, row) {
          return `<button class="btn btn-sm btn-secondary toggle-btn mx-2" data-id="${row.id}">
            <i class="toggle-arrow bi bi-chevron-down"></i>
          </button> ${row.name}`;
        }
      },
      { data: 'amt' },
      { data: 'discount_amt' },
      { data: 'after_discount' },
      {
        data: null,
        render: function (data) {
          return sStatus(data['status']);
        }
      },
      {
        data: null,
        render: function (data, type, row) {
          var btn = '<div class="text-center"><div class="btn-group">';
          btn += '<button type="button" class="btn btn-sm action-btn" onclick="DetailPackage(' + row.id + ')"><i class="bi bi-pencil-fill"></i></button>';
          btn += '</div></div>';
          return btn;
        }
      }
    ]
  });

  $('#dataTable tbody').on('click', '.toggle-btn', function () {
    var button = $(this);
    var row = table.row(button.closest('tr'));
    var packageId = button.data('id');

    if (row.child.isShown()) {
      row.child.hide();
      button.find('.toggle-arrow').removeClass('bi-chevron-up').addClass('bi-chevron-down');
    } else {
      var childContent = `
        <table class="table table-sm table-dark table-bordered" id="sub-table" style="color:var(--s-text-color-2);">
          <thead class="table-secondary">
            <tr>
              <th style="width:50px;">#</th>
              <th>Title</th>
              <th>Details</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
      `;

      $.ajax({
        url: 'package.php',
        type: 'POST',
        data: {
          type: 'detailsList',
          package_id: packageId
        },
        success: function (response) {
          if (response===null) {
            childContent += `
              <tr>
                <td class="text-center" colspan="4">No data available in table</td>
              </tr>
            `;
          }else{
          response.forEach(function (detail, index) {
            childContent += `
              <tr>
                <td class="text-center">${index + 1}</td>
                <td class="text-start">${detail.title}</td>
                <td class="text-start">${detail.details}</td>
                <td class="text-start">${sStatus(detail.status)}</td>
              </tr>
            `;
          });}
          childContent += `</tbody></table>`;

          row.child(childContent).show();
          button.find('.toggle-arrow').removeClass('bi-chevron-down').addClass('bi-chevron-up');
        }
      });
    }
  });
});

function DetailPackage(id) {
  $.ajax({
    type: "post",
    url: "modal_package.php",
    data: {
      id: id,
    },
    success: function (sData) {
      $("#modalDiv").html("");
      $("#modalDiv").append(sData);
      $("#modalModal").modal("show");
    },
  });
}

function AddPackage() {
  var name = $("#name").val();
  var amount = $("#amount").val();
  var status = document.getElementById('packageStatusActive').checked ? 1 : 0;

  if (name === "" || name === null) {
    $("#name").css("border-color", "red");
    return;
  }

  if (amount === "" || amount === null || amount < 0) {
    $("#amount").css("border-color", "red");
    return;
  }

  $.ajax({
    type: "post",
    url: "modal_package.php",
    data: {
      type: "add",
      name: name,
      amount: amount,
      status: status
    },
    success: function (response) {
      if (response.success) {
        $("#modalModal").modal("hide");
        $('#dataTable').DataTable().ajax.reload();
        swal(response.message, {
          icon: "success",
        });
      } else {
        swal('Error: ' + response.message, {
          icon: "error",
        });
      }
    },
  });
}

function UpdatePackage() {
  var id = $("#id").val();
  var name = $("#name").val();
  var amount = $("#amount").val();
  var status = document.getElementById('packageStatusActive').checked ? 1 : 0;

  if (name === "" || name === null) {
    $("#name").css("border-color", "red");
    return;
  }

  if (amount === "" || amount === null || amount < 0) {
    $("#amount").css("border-color", "red");
    return;
  }

  swal({
    title: "Are you sure?",
    text: "Update this package!",
    icon: "warning",
    buttons: true,
    dangerMode: true,
  }).then((willDelete) => {
    if (willDelete) {
      $.ajax({
        type: "post",
        url: "modal_package.php",
        data: {
          type: "update",
          id: id,
          name: name,
          amount: amount,
          status: status
        },
        success: function (response) {
          if (response.success) {
            $("#modalModal").modal("hide");
            $('#dataTable').DataTable().ajax.reload();
            swal(response.message, {
              icon: "success",
            });
          } else {
            swal('Error: ' + response.message, {
              icon: "error",
            });
          }
        },
      });
    }
  });
}