$(document).ready(function() {
  table = $('#dataTable').DataTable({
      order: [],
      ajax: {
          url: 'discount.php',
          type: 'POST',
          data: {
              type: 'list'
          },
          dataSrc: function(json) {
              return json;
          },
      },
      columns: [
          {data: 'package_name'},
          {data: 'discount_amt'},
          {
              data: null,
              render: function (data, type, row) { 
                  return sDate(row.valid_from);
               }
          },
          {
              data: null,
              render: function (data, type, row) { 
                  return sDate(row.valid_until);
               }
          },
          {
              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="DetailDiscount(' + row.id + ')"><i class="bi bi-pencil-fill"></i></button>';
                  btn += '</div></div>';
                  return btn;
              }
          }
      ],
      createdRow: function(row, data, dataIndex) {
          var today = new Date().toISOString().split('T')[0]; // Format: YYYY-MM-DD

          if (data.valid_from < today && data.valid_until < today) {
              $(row).addClass('text-secondary');
          }else if(data.valid_from <= today && data.valid_until >= today) {
              $(row).addClass('fw-bold text-success');
          }
      }
  });
});

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

function AddDiscount() {
  var packageId = $('#packageName').val();
  var validFrom = $('#validFrom').val();
  var validUntil = $('#validUntil').val();
  var discountAmount = $('#discountAmount').val();
  var afterDiscount = $('#afterDiscount').val();

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

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

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

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

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

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

  if (new Date(validUntil) < new Date(validFrom)) {
    $("#validUntil").css("border-color", "red");
    swal('Error: "Valid Until" must be after "Valid From"', {
      icon: "error",
    });
    return;
  }

  $.ajax({
    type: "post",
    url: "modal_discount.php",
    data: {
      type: "add",
      packageId: packageId,
      validFrom: validFrom,
      validUntil: validUntil,
      discountAmount: discountAmount
    },
    success: function (response) {
      if (response.success) {
        $("#modalModal").modal("hide");
        table.ajax.reload();
        swal(response.message, {
          icon: "success",
        });
      } else {
        swal('Error: ' + response.message, {
          icon: "error",
        });
      }
    },
  });
}

function UpdateDiscount() {
  var id = $("#id").val();
  var packageId = $('#packageName').val();
  var validFrom = $('#validFrom').val();
  var validUntil = $('#validUntil').val();
  var discountAmount = $('#discountAmount').val();
  var afterDiscount = $('#afterDiscount').val();

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

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

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

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

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

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

  if (new Date(validUntil) < new Date(validFrom)) {
    $("#validUntil").css("border-color", "red");
    swal('Error: "Valid Until" must be after "Valid From"', {
      icon: "error",
    });
    return;
  }

  swal({
    title: "Are you sure?",
    text: "Update this discount!",
    icon: "warning",
    buttons: true,
    dangerMode: true,
  }).then((willDelete) => {
    if (willDelete) {
      $.ajax({
        type: "post",
        url: "modal_discount.php",
        data: {
          type: "update",
          id: id,
          packageId: packageId,
          validFrom: validFrom,
          validUntil: validUntil,
          discountAmount: discountAmount
        },
        success: function (response) {
          if (response.success) {
            $("#modalModal").modal("hide");
            table.ajax.reload();
            swal(response.message, {
              icon: "success",
            });
          } else {
            swal('Error: ' + response.message, {
              icon: "error",
            });
          }
        },
      });
    }
  });
}