$(function () {
  // manage datatable
  $("#customer_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  //delete Customer
  $(document).on("click", ".deleteCustomer", function () {
    var id = $(this).data("id");
    var url = $(".deleteCustomerForm").data("url") + id;
    $(".deleteCustomerForm").attr("action", url);
  });

  //Block Customer
  $(document).on("click", ".blockCustomer", function () {
    var id = $(this).data("id");
    var url = $(".blockCustomerForm").data("url") + id;
    $(".blockCustomerForm").attr("action", url);
  });
  //Unblock Customer
  $(document).on("click", ".unblockCustomer", function () {
    var id = $(this).data("id");
    var url = $(".unblockCustomerForm").data("url") + id;
    $(".unblockCustomerForm").attr("action", url);
  });

  // withdraw datatable
  $("#withdraw_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  //Accept withdraw
  $(document).on("click", ".acceptWithdraw", function () {
    var id = $(this).data("id");
    var url = $(".acceptWithdrawForm").data("url") + id;
    $(".acceptWithdrawForm").attr("action", url);
  });

  //cancel withdraw
  $(document).on("click", ".cancelWithdraw", function () {
    var id = $(this).data("id");
    var url = $(".cancelWithdrawForm").data("url") + id;
    $(".cancelWithdrawForm").attr("action", url);
  });

  //ajax subcategory
  $("#category_filter").on("change", function () {
    var value = $(this).val();
    if (value !== "") {
      $.ajax({
        url: "/admin/ajax/subcategories",
        type: "get",
        data: { category_id: value },
        success: function (res) {
          var table = `
                            <table id="table_datatable" class="table table-bordered table-hover float-left">
                                <thead>
                                    <tr>
                                    <th>Index</th>
                                    <th>Category</th>
                                    <th>Name</th>
                                    <th>Description</th>
                                    <th>Updated At</th>
                                    <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>`;
          res.length > 0 &&
            res.forEach((subcat, i) => {
              var date = new Date(subcat.updatedAt);
              var update = date.toDateString();
              var time = date.getHours();
              var minutes = date.getMinutes();
              time = time % 12;
              time = time ? time : 12; // the hour '0' should be '12'
              minutes = minutes < 10 ? "0" + minutes : minutes;
              table +=
                `
                    <tr key="` +
                i +
                `">
                        <td> ` +
                (i + 1) +
                ` </td>
                        <td> ` +
                subcat.Category.name +
                ` </td>
                        <td> ` +
                subcat.name +
                ` </td>
                        <td class="col-md-3"> ` +
                subcat.description +
                ` </td>
                        <td> ` +
                update +
                ` ` +
                time +
                `:` +
                minutes +
                ` </td>
                        <td class="project-actions">
                            <a class="btn btn-primary btn-sm" title="View" href="/admin/subcategory/view/` +
                subcat.id +
                `"> 
                                <i class="fas fa-eye"> </i> 
                            </a>
                            <a class="btn btn-info btn-sm" title="Edit" href="/admin/subcategory/` +
                subcat.id +
                `"> 
                                <i class="fas fa-pencil-alt"> </i> 
                            </a>
                            <button class="btn btn-danger btn-sm deleteSubcategory" data-id="` +
                subcat.id +
                `" 
                                title="Delete" href="#" data-toggle="modal" data-target="#modal-danger"> 
                                <i class="fas fa-trash"> </i> 
                            </button>
                        </td>
                    </tr> `;
            });
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="6" class="dataTables_empty">No data available in table</td></tr>`;
          }
          table += `</tbody>
                    <tfoot>
                        <tr>
                        <th>Index</th>
                        <th>Category</th>
                        <th>Name</th>
                        <th>Description</th>
                        <th>Updated At</th>
                        <th>Actions</th>
                        </tr>
                    </tfoot>
                </table>`;
          $("#ajax_table").html(table);
          $("#table_datatable").DataTable({
            paging: true,
            ordering: true,
            autoWidth: true,
            responsive: true,
          });
        },
        error: function (err) {
          console.error("subcategories error", err);
        },
      });
    }
  });
  setTimeout(() => {
    $("#category_filter").change();
  }, 500);

  // state datatable
  $("#state_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  //delete State
  $(document).on("click", ".deleteState", function () {
    var id = $(this).data("id");
    var url = $(".deleteStateForm").data("url") + id;
    $(".deleteStateForm").attr("action", url);
  });

  // Location datatable
  $("#location_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  //delete Location

  $(document).on("click", ".deleteLocation", function () {
    var id = $(this).data("id");
    var url = $(".deleteLocationForm").data("url") + id;
    $(".deleteLocationForm").attr("action", url);
  });

  // category datatable
  $("#products_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });
  // add more variants to product
  $(".addMoreVariants").on("click", function () {
    var dynamicClass = "variant" + Date.now();
    var html =
      `<div class="m-0 col-md-12 p-0 row ` +
      dynamicClass +
      `"><div class="col-md-1"><button type="button" data-class="` +
      dynamicClass +
      `"
                            class="btn btn-danger deleteVariant"><i
                                class="fas fa-minus"></i></button>
                                <input type="hidden" name="item_id" value="new"/>
                    </div>
                    <div class="form-group col-md-3">
                        <input type="text" class="form-control" name="packing[]">
                    </div>
                    <div class="form-group col-md-3">
                        <input type="text" class="form-control" name="in_stock[]">
                    </div>
                    <div class="form-group col-md-3">
                        <input type="text" class="form-control"
                            name="warning_level[]">
                    </div>
                    <div class="form-group col-md-2">
                        <input type="text" class="form-control" name="price[]">
                    </div></div>`;
    $(".productVariants").append(html);
    $(".deleteVariant").unbind("click");
    $(".deleteVariant").on("click", function () {
      var variantClass = $(this).data("class");
      // console.log("variant", variantClass);
      $("." + variantClass).remove();
    });
  });

  // remove variant from product
  $(".deleteVariant").unbind("click");
  $(".deleteVariant").on("click", function () {
    var variantClass = $(this).data("class");
    // console.log("variant", variantClass);
    $("." + variantClass).remove();
  });

  // fetch subcategories by categoty id
  $("#product_category").on("change", function () {
    var cat = $(this).val();
    var selected = $("#product_subcategory").data("selected");
    // console.log('selected', selected)
    if (cat !== "") {
      $.ajax({
        url: "/admin/ajax/subcategories",
        type: "get",
        data: { category_id: cat },
        success: function (res) {
          var optionHtml = "";
          if (selected == undefined) {
            optionHtml += `<option value="">Select Subcategory</option>`;
          }
          res.length > 0 &&
            res.forEach((itm, i) => {
              var selectedText = "";
              if (itm.id == selected) {
                selectedText = "selected";
              }
              optionHtml +=
                `<option key="` +
                i +
                `" value="` +
                itm.id +
                `" ` +
                selectedText +
                `>` +
                itm.name +
                `</option>`;
            });
          $("#product_subcategory").html(optionHtml);
        },
        error: function (err) {
          console.error("subcategories error", err);
        },
      });
    }
  });
  setTimeout(() => {
    $("#product_category").change();
  }, 500);

  // delete product
  // $('.deleteproduct').on('click', function () {
  //     var id = $(this).data('id');
  //     var url = $('.deleteProductForm').data('url') + id
  //     $('.deleteProductForm').attr('action', url);
  //     console.log("here");
  // });

  $(document).on("click", ".deleteproduct", function () {
    var id = $(this).data("id");
    // console.log('id--', id);
    var url = $(".deleteProductForm").data("url") + id;
    $(".deleteProductForm").attr("action", url);
  });

  // fetch subcategories by categoty id
  $("#product_category").on("change", function () {
    var cat = $(this).val();
    var selected = $("#product_subcategory").data("selected");
    if (cat !== "") {
      $.ajax({
        url: "/admin/ajax/subcategories",
        type: "get",
        data: { category_id: cat },
        success: function (res) {
          var optionHtml = "";
          if (selected == undefined) {
            optionHtml += `<option value="">Select Subcategory</option>`;
          }
          res.length > 0 &&
            res.forEach((itm, i) => {
              var selectedText = "";
              if (itm.id == selected) {
                selectedText = "selected";
              }
              optionHtml +=
                `<option key="` +
                i +
                `" value="` +
                itm.id +
                `" ` +
                selectedText +
                `>` +
                itm.name +
                `</option>`;
            });
          $("#product_subcategory").html(optionHtml);
        },
        error: function (err) {
          console.error("subcategories error", err);
        },
      });
    }
  });
  setTimeout(() => {
    $("#product_category").change();
  }, 500);

  //ajax product Subcategory
  $("#filterSubcategory").on("click", function (e) {
    e.preventDefault();
    var value = $("#product_subcategory").val();
    var name = $("#product_subcategory").find("option:selected").attr("name");
    if (value !== "") {
      $.ajax({
        url: "/admin/ajax/product",
        type: "get",
        data: { name: name, value: value },
        success: function (res) {
          var table = `
                        <table id="product_datatable" class="table table-bordered table-hover float-left">
                            <thead>
                                <tr>
                                <th>Index</th>
                                <th>Name</th>
                                <th>Packing</th>
                                <th>In Stock</th>
                                <th>Warning Level</th>
                                <th>Price</th>
                                <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>`;
          res.length > 0 &&
            res.forEach((prod, i) => {
              prod.ProductItems.forEach((itm, index) => {
                table +=
                  `
                                        <tr key="` +
                  i +
                  `">
                                            <td>
                                                ` +
                  (i + 1) +
                  `
                                            </td>
                                            <td>
                                            ` +
                  prod.name +
                  `
                                            </td>
                                            <td>
                                            ` +
                  itm.packing_text +
                  `
                                            </td>
                                            <td>
                                            ` +
                  itm.in_stock +
                  `
                                            </td>
                                            <td>
                                            ` +
                  itm.warning_level +
                  `
                                            </td>
                                            <td>
                                            ` +
                  itm.price +
                  `
                                            </td>
                                            <td class="project-actions">
                                            <a class="btn btn-primary btn-sm" title="View" href="/admin/product/view/` +
                  prod.id +
                  `">
                                            <i class="fas fa-eye">
                                            </i>
                                            </a>
                                            <a class="btn btn-info btn-sm" title="Edit" href="/admin/product/` +
                  prod.id +
                  `">
                                            <i class="fas fa-pencil-alt">
                                            </i>
                                            </a>
                                            <button class="btn btn-danger btn-sm deleteproduct" data-id="` +
                  prod.id +
                  `"
                                            title="Delete" href="#" data-toggle="modal" data-target="#modal-danger">
                                            <i class="fas fa-trash">
                                            </i>
                                            </button>
                                        </td>
                                        </tr>
                                        `;
              });
            });
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="7" class="dataTables_empty">No data available in table</td></tr>`;
          }
          table += `</tbody>
                            <tfoot>
                                <tr>
                                <th>Index</th>
                                <th>Name</th>
                                <th>Packing</th>
                                <th>In Stock</th>
                                <th>Warning Level</th>
                                <th>Price</th>
                                <th>Actions</th>
                                </tr>
                            </tfoot>
                        </table>`;
          $("#ajax_product_table").html(table);
          $("#product_datatable").DataTable({
            paging: true,
            ordering: true,
            autoWidth: true,
            responsive: true,
          });
        },
        error: function (err) {
          console.error("Producer error", err);
        },
      });
    }
  });

  //edit staff products datatable
  $("#edit_products_datatable").DataTable({
    paging: true,
    ordering: true,
    order: [[2, "asc"]],
    autoWidth: true,
    responsive: true,
  });
  // preview driver image
  $("#driver_image").on("change", function (e) {
    const [file] = e.target.files;
    if (file) {
      $("#previewDriverImage").attr("src", URL.createObjectURL(file));
      var reader = new FileReader();
      reader.onloadend = function () {
        $("#driver_image_base64").val(reader.result);
      };
      reader.readAsDataURL(file);
    }
  });
  // preview Licence image
  $("#driver_licence_image").on("change", function (e) {
    const [file] = e.target.files;
    if (file) {
      $("#previewLicenceImage").attr("src", URL.createObjectURL(file));
      var reader = new FileReader();
      reader.onloadend = function () {
        $("#driver_licence_base64").val(reader.result);
      };
      reader.readAsDataURL(file);
    }
  });
  // preview RC image
  $("#drive_rc_image").on("change", function (e) {
    const [file] = e.target.files;
    if (file) {
      $("#previewRCImage").attr("src", URL.createObjectURL(file));
      var reader = new FileReader();
      reader.onloadend = function () {
        $("#driver_rc_base64").val(reader.result);
      };
      reader.readAsDataURL(file);
    }
  });

  //Block Driver
  $(document).on("click", ".blockDriver", function () {
    var id = $(this).data("id");
    var url = $(".blockDriverForm").data("url") + id;
    $(".blockDriverForm").attr("action", url);
  });
  //Unblock Driver
  $(document).on("click", ".unblockDriver", function () {
    var id = $(this).data("id");
    var url = $(".unblockDriverForm").data("url") + id;
    $(".unblockDriverForm").attr("action", url);
  });

  // Producer datatable
  $("#producer_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  //delete Producer

  $(document).on("click", ".deleteProducer", function () {
    var id = $(this).data("id");
    var url = $(".deleteProducerForm").data("url") + id;
    $(".deleteProducerForm").attr("action", url);
  });

  var $modal = $("#modal");

  var image = document.getElementById("sample_image");

  var cropper;

  // preview cover image
  $("#edit_cover_image").on("change", function (e) {
    // const [file] = e.target.files;
    // if (file) {
    //   $("#previewCoverImage").attr("src", URL.createObjectURL(file));
    //   var reader = new FileReader();
    //   reader.onloadend = function () {
    //     $("#coverbaseImage").val(reader.result);
    //   };
    //   reader.readAsDataURL(file);
    // }
    var files = e.target.files;
    var done = function (url) {
      image.src = url;
      $modal.modal("show");
    };

    if (files && files.length > 0) {
      reader = new FileReader();
      reader.onload = function (event) {
        done(reader.result);
      };
      reader.readAsDataURL(files[0]);
    }
  });
  $modal
    .on("shown.bs.modal", function () {
      cropper = new Cropper(image, {
        aspectRatio: 16 / 9,
        viewMode: 1,
        preview: ".preview",
      });
    })
    .on("hidden.bs.modal", function () {
      cropper.destroy();
      cropper = null;
    });

  $("#crop").click(function () {
    canvas = cropper.getCroppedCanvas({
      width: 400,
      height: 400,
    });

    canvas.toBlob(function (blob) {
      // url = URL.createObjectURL(blob);
      $("#previewCoverImage").attr("src", URL.createObjectURL(blob));
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function () {
        $("#coverbaseImage").val(reader.result);
        $modal.modal("hide");
        // var base64data = reader.result;
        // $.ajax({
        //     url:'upload.php',
        //     method:'POST',
        //     data:{image:base64data},
        //     success:function(data)
        //     {
        //         $modal.modal('hide');
        //         $('#uploaded_image').attr('src', data);
        //     }
        // });
      };
    });
  });

  // Admin datatable
  $("#admin_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  // delete Admin
  $(document).on("click", ".deleteAdmin", function () {
    var id = $(this).data("id");
    var url = $(".deleteAdminForm").data("url") + id;
    $(".deleteAdminForm").attr("action", url);
  });

  //Block Admin
  $(document).on("click", ".blockAdmin", function () {
    var id = $(this).data("id");
    var url = $(".blockAdminForm").data("url") + id;
    $(".blockAdminForm").attr("action", url);
  });
  //Unblock Admin
  $(document).on("click", ".unblockAdmin", function () {
    var id = $(this).data("id");
    var url = $(".unblockAdminForm").data("url") + id;
    $(".unblockAdminForm").attr("action", url);
  });

  // preview admin image
  $("#edit_admin_image").on("change", function (e) {
    const [file] = e.target.files;
    if (file) {
      $("#previewAdminImage").attr("src", URL.createObjectURL(file));
      var reader = new FileReader();
      reader.onloadend = function () {
        $("#baseImage").val(reader.result);
      };
      reader.readAsDataURL(file);
    }
  });

  // CMS datatable
  $("#cms_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  // delete CMS
  // $('.deleteCMS').on('click', function () {
  //     var id = $(this).data('id');
  //     var url = $('.deleteCMSForm').data('url') + id
  //     $('.deleteCMSForm').attr('action', url);
  // })

  $(document).on("click", ".deleteCMS", function () {
    var id = $(this).data("id");
    var url = $(".deleteCMSForm").data("url") + id;
    $(".deleteCMSForm").attr("action", url);
  });

  // $('#editor').summernote({
  //     height: 250,
  // })

  // $('#editoredit').summernote()

  // Order datatable
  $("#order_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  // view Order

  $(document).on("click", ".viewOrder", function (e) {
    e.preventDefault();
    var id = $(this).data("id");
    $.ajax({
      url: "/admin/ajax/order",
      type: "get",
      data: { order_id: id },
      success: function (res) {
        var notes = "";
        var table = `
                <div class="form-group ">
                    <div class="custName float-left">
                        <label class="px-2 ">Order Id: </label>
                        <span >`;
        res.forEach((itm) => {
          table += `<b> ` + itm.Order.id + `</b>`;
        });
        table += `       </span>
                    </div>
                    <div class="custName float-right">
                        <label class="px-2 ">Date: </label>
                        <span >`;
        res.forEach((itm) => {
          var date = new Date(itm.Order.updatedAt);
          var update = date.toDateString();
          var time = date.getHours();
          var minutes = date.getMinutes();
          time = time % 12;
          time = time ? time : 12; // the hour '0' should be '12'
          minutes = minutes < 10 ? "0" + minutes : minutes;
          table += update + ` ` + time + `:` + minutes;
        });
        table += `       </span>
                    </div>
                </div>
                <br><br>
                <table id="ajaxOrder_datatable" class="table table-border float-left">
                    <thead>
                        <tr>
                        <th>#</th>
                        <th>Product</th>
                        <th>Packing</th>
                        <th class="text-right">Qty</th>
                        <th class="text-right">Price Per</th>
                        <th class="text-right">Total</th>
                        </tr>
                    </thead>
                    <tbody>`;

        res.length > 0 &&
          res.forEach((itm, i) => {
            table +=
              ` <tr key="` +
              i +
              `">
                    <td> ` +
              (i + 1) +
              ` </td>
                    <td> ` +
              itm.product_name +
              ` </td>
                    <td> ` +
              itm.packing_name +
              ` </td>
                    <td class="text-right"> ` +
              itm.qty +
              ` </td>
                    <td class="text-right"> ` +
              itm.rate +
              ` </td>
                    <td class="text-right"> ` +
              itm.rate * itm.qty +
              ` </td>
                </tr>`;
          });
        if (res.length == 0) {
          table += `<tr class="odd"><td valign="top" colspan="6" class="dataTables_empty">No data available in table</td></tr>`;
        }
        table += `</tbody>
                </table>`;
        res.length > 0 &&
          res.forEach((itm, i) => {
            if (i == 0 && itm.Order.notes) {
              notes +=
                `<aside class="aside">
                            <h5 class="text-center"><span>Delivery Note:</span></h5>
                            <div>
                                <p class="text-center">` +
                itm.Order.notes +
                `</p>
                            </div>
                        </aside>`;
            }
          });
        res.length > 0 &&
          res.forEach((itm, i) => {
            if (i == 0) {
              table +=
                `
                <table class="balance">
                    <tr>
                        <th colspan="5"><span>Subtotal</span></th>
                        <td><span data-prefix>$</span><span>` +
                itm.Order.subtotal +
                `</span></td>
                    </tr>
                    <tr>
                        <th colspan="5"><span>Discount</span></th>
                        <td><span data-prefix>$</span><span>` +
                itm.Order.discount +
                `</span></td>
                    </tr>
                    <tr>
                        <th colspan="5"><span>Tax</span></th>
                        <td><span data-prefix>$</span><span>` +
                itm.Order.tax +
                `</span></td>
                    </tr>
                    <tr>
                        <th colspan="5"><span>Delivery Charge</span></th>
                        <td><span data-prefix>$</span><span>` +
                itm.Order.delivery +
                `</span></td>
                    </tr>
                    <tr>
                        <th colspan="5"><span>Grand Total</span></th>
                        <td><span data-prefix>$</span><span>` +
                itm.Order.grandtotal +
                `</span></td>
                    </tr>
                </table>`;
            }
          });
        table += notes;
        $("#order-data").html(table);

        $("#modal-view").modal("show");
      },
      error: function (err) {
        console.error("subcategories error", err);
      },
    });
  });

  // Contact Information datatable
  $("#info_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });
  // Contact Information Delete
  $(document).on("click", ".deleteContactInfo", function () {
    var id = $(this).data("id");
    var url = $(".deleteContactInfoForm").data("url") + id;
    $(".deleteContactInfoForm").attr("action", url);
  });

  // Inventory datatable
  $("#inventory_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  // fetch subcategories by categoty id
  $("#inventory_category").on("change", function () {
    var cat = $(this).val();
    var selected = $("#inventory_subcategory").data("selected");
    if (cat !== "") {
      $.ajax({
        url: "/admin/ajax/subcategories",
        type: "get",
        data: { category_id: cat },
        success: function (res) {
          var optionHtml = "";
          if (selected == undefined) {
            optionHtml += `<option value="">Select Subcategory</option>`;
          }
          res.length > 0 &&
            res.forEach((itm, i) => {
              var selectedText = "";
              if (itm.id == selected) {
                selectedText = "selected";
              }
              optionHtml +=
                `<option key="` +
                i +
                `" value="` +
                itm.id +
                `" ` +
                selectedText +
                `>` +
                itm.name +
                `</option>`;
            });
          $("#inventory_subcategory").html(optionHtml);
        },
        error: function (err) {
          console.error("subcategories error", err);
        },
      });
    }
  });
  setTimeout(() => {
    $("#inventory_category").change();
  }, 500);

  //ajax inventory Subcategory
  $("#filterSubcategory").on("click", function (e) {
    e.preventDefault();
    var value = $("#inventory_subcategory").val();
    var name = $("#inventory_subcategory").find("option:selected").attr("name");
    if (value !== "") {
      $.ajax({
        url: "/admin/ajax/inventory",
        type: "get",
        data: { name: name, value: value },
        success: function (res) {
          var table = `
                <table id="producer_datatable" class="table table-bordered table-hover float-left">
                    <thead>
                        <tr>
                            <th>Index</th>
                            <th>Producer</th>
                            <th>Product</th>
                            <th>Packing</th>
                            <th>In Stock</th>
                            <th>Warning Level</th>
                            <th>Price</th>
                        </tr>
                    </thead>
                    <tbody>`;
          res.length > 0 &&
            res.forEach((prod, i) => {
              var className = "";
              if (prod.in_stock <= prod.warning_level) {
                className += `bg-danger`;
              } else {
                className += "";
              }
              table +=
                `<tr class="` +
                className +
                `" key="` +
                i +
                `">
                    <td> ` +
                (i + 1) +
                ` </td>
                    <td> ` +
                prod.Product.Producer.name +
                ` </td>
                    <td> ` +
                prod.Product.name +
                ` </td>
                    <td> ` +
                prod.packing_text +
                ` </td>
                    <td>`;
              if (prod.in_stock == 0) {
                table += `<b class="danger">Out Of Stock</b>`;
              } else {
                table += prod.in_stock;
              }
              table +=
                `   </td>
                    <td> ` +
                prod.warning_level +
                ` </td>
                    <td> ` +
                prod.price +
                ` </td>
                </tr> `;
            });
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="7" class="dataTables_empty">No data available in table</td></tr>`;
          }
          table += `</tbody>
                    <tfoot>
                        <tr>
                            <th>Index</th>
                            <th>Producer</th>
                            <th>Product</th>
                            <th>Packing</th>
                            <th>In Stock</th>
                            <th>Warning Level</th>
                            <th>Price</th>
                        </tr>
                    </tfoot>
                </table>`;
          $("#ajax_table").html(table);
          $("#producer_datatable").DataTable({
            paging: true,
            ordering: true,
            autoWidth: true,
            responsive: true,
          });
        },
        error: function (err) {
          console.error("Producer error", err);
        },
      });
    }
  });

  //ajax inventory Producer
  $("#filterProducer").on("click", function (e) {
    e.preventDefault();
    var value = $("#inventory_producer").val();
    var name = $("#inventory_producer").find("option:selected").attr("name");

    if (value !== "") {
      $.ajax({
        url: "/admin/ajax/inventory",
        type: "get",
        data: { name: name, value: value },
        success: function (res) {
          var table = `
                            <table id="producer_datatable" class="table table-bordered table-hover float-left">
                                <thead>
                                    <tr>
                                        <th>Index</th>
                                        <th>Producer</th>
                                        <th>Product</th>
                                        <th>Packing</th>
                                        <th>In Stock</th>
                                        <th>Warning Level</th>
                                        <th>Price</th>
                                    </tr>
                                </thead>
                                <tbody>`;
          res.length > 0 &&
            res.forEach((prod, i) => {
              var className = "";
              if (prod.in_stock <= prod.warning_level) {
                className += `bg-danger`;
              } else {
                className += "";
              }
              table +=
                `   <tr class="` +
                className +
                `" key="` +
                i +
                `">
                        <td> ` +
                (i + 1) +
                ` </td>
                        <td> ` +
                prod.Product.Producer.name +
                ` </td>
                        <td> ` +
                prod.Product.name +
                ` </td>
                        <td> ` +
                prod.packing_text +
                ` </td>
                    <td>`;
              if (prod.in_stock == 0) {
                table += `<b class="danger">Out Of Stock</b>`;
              } else {
                table += prod.in_stock;
              }
              table +=
                `   </td>
                    <td> ` +
                prod.warning_level +
                ` </td>
                    <td> ` +
                prod.price +
                ` </td>
                </tr>`;
            });
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="7" class="dataTables_empty">No data available in table</td></tr>`;
          }
          table += `</tbody>
                                <tfoot>
                                    <tr>
                                        <th>Index</th>
                                        <th>Producer</th>
                                        <th>Product</th>
                                        <th>Packing</th>
                                        <th>In Stock</th>
                                        <th>Warning Level</th>
                                        <th>Price</th>
                                    </tr>
                                </tfoot>
                            </table>`;
          $("#ajax_table").html(table);
          $("#producer_datatable").DataTable({
            paging: true,
            ordering: true,
            autoWidth: true,
            responsive: true,
          });
        },
        error: function (err) {
          console.error("Producer error", err);
        },
      });
    }
  });
  // var editor;
  // editor = new $.fn.dataTable.Editor( {
  //     table: "#inventory_datatable",
  // })
  // // Activate an inline edit on click of a table cell
  // $('#inventory_datatable').on( 'click', 'tbody td:not(:first-child)', function (e) {
  //     alert(this);
  // } );

  $(".drop-toggle").click(function (e) {
    $(this).next("#drop").toggle(400);

    //   $(document).click(function(e) {

    var id = $.map($("#drop > a"), (a) => a.id);
    $.ajax({
      url: "/admin/ajax/allNotification",
      type: "post",
      data: { id: id },
      error: function (err) {
        console.error("error", err);
      },
    });
  });
  $("#notification_datatable").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
  });

  $(document).on("click", ".viewNotification", function (e) {
    e.preventDefault();
    var noti_id = $(this).data("id");
    var type = $(this).data("type");
    console.log(noti_id);
    $.ajax({
      url: "/admin/ajax/notification/",
      type: "get",
      data: { id: noti_id, type: type },
      success: function (res) {
        if (res.type == "product_update") {
          var table = "";
          table += `
                <table id="ajaxNotification_datatable" class="table table-bordered table-hover float-left">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Packing</th>
                            <th>stock</th>
                        </tr>
                    </thead>
                    <tbody>`;
          table +=
            `   <tr>
                            <td> ` +
            res.ProductItem.Product.name +
            ` </td>
                            <td> ` +
            res.ProductItem.packing_text +
            ` </td>
                            <td> ` +
            res.ProductItem.in_stock +
            ` </td>
                        </tr>`;
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="4" class="dataTables_empty">No data available in table</td></tr>`;
          }

          table += `   </tbody>
                    <tfoot>
                        <tr>    
                            <th>Product</th>
                            <th>Packing</th>
                            <th>stock</th>
                        </tr>
                    </tfoot>
                </table>`;
          $("#notification-data").html(table);
          $("#modal-view-notification").modal("show");
        } else if (res.type == "new_order") {
          var date = new Date(res.Order.updatedAt);
          var update = date.toDateString();
          var time = date.getHours();
          var minutes = date.getMinutes();
          time = time % 12;
          time = time ? time : 12; // the hour '0' should be '12'
          minutes = minutes < 10 ? "0" + minutes : minutes;
          var table = "";
          table += `
                <table id="ajaxNotification_datatable" class="table table-bordered table-hover float-left">
                    <thead>
                        <tr>
                            <th>Order Date</th>
                            <th>Customer</th>
                            <th>Status</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>`;
          table +=
            `   <tr>
                        <td> ` +
            update +
            ` ` +
            time +
            `:` +
            minutes +
            ` </td>
                        <td> ` +
            res.Customer.User.first_name +
            " " +
            res.Customer.User.last_name +
            ` </td>
                        <td> `;
          if (res.Order.order_status == 0) {
            table += `<b class="text-danger">Cancel</b>`;
          }
          if (res.Order.order_status == 1) {
            table += `<b class="text-warning">New</b>`;
          }
          if (res.Order.order_status == 2) {
            table += `<b class="text-info">Ready To Delivery</b>`;
          }
          if (res.Order.order_status == 3) {
            table += `<b class="text-brimary">On Delivery</b>`;
          }
          if (res.Order.order_status == 4) {
            table += `<b class="text-success">Delivered</b>`;
          }
          table +=
            `   </td>
                        <td class="text-right">` +
            res.Order.grandtotal +
            `</td>   
                    </tr>`;

          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="5" class="dataTables_empty">No data available in table</td></tr>`;
          }

          table += `</tbody>
                            <tfoot>
                                <tr>    
                                    <th>Order Date</th>
                                    <th>Customer</th>
                                    <th>Status</th>
                                    <th>Amount</th>
                                </tr>
                            </tfoot>
                        </table>`;
          $("#notification-data").html(table);
          $("#modal-view-notification").modal("show");
        } else if (res.type == "new_customer") {
          var table = "";
          table += `
                <table id="ajaxNotification_datatable" class="table table-bordered table-hover float-left">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th >Image</th>
                            <th class="col-2">Email</th>
                            <th class="col-2">Address</th>
                            <th>Zip</th>
                            <th>Phone No.</th>
                        </tr>
                    </thead>
                    <tbody>`;
          table +=
            `   <tr>
                            <td> ` +
            res.Customer.User.first_name +
            " " +
            res.Customer.User.last_name +
            ` </td>
                            <td> <img class="tableImage" src="/images/` +
            res.Customer.image +
            `"/> </td>
                            <td> ` +
            res.Customer.User.email +
            ` </td>
                            <td> ` +
            res.Customer.CustomerDeliveryAddresses.forEach(
              (delivery, index) => {
                index == 0 ? delivery.address1 + "," + delivery.address2 : "";
              }
            ) +
            ` </td>
                            <td> ` +
            res.Customer.CustomerDeliveryAddresses.forEach(
              (delivery, index) => {
                index == 0 ? delivery.zip : "";
              }
            ) +
            ` </td>
                            <td> ` +
            res.Customer.phone +
            ` </td>
                        </tr>`;
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="7" class="dataTables_empty">No data available in table</td></tr>`;
          }

          table += `</tbody>
                            <tfoot>
                                <tr>    
                                    <th >Name</th>
                                    <th >Image</th>
                                    <th class="col-2">Email</th>
                                    <th class="col-2">Address</th>
                                    <th>Zip</th>
                                    <th>Phone No.</th>
                                </tr>
                            </tfoot>
                        </table>`;
          $("#notification-data").html(table);
          $("#modal-view-notification").modal("show");
        }

        $("#ajaxNotification_datatable").DataTable({
          paging: false,
          lengthChange: false,
          ordering: true,
          autoWidth: false,
          responsive: true,
        });
      },
      error: function (err) {
        console.error("error", err);
      },
    });
  });
  //ajax notification
  $("#filterType").on("click", function (e) {
    e.preventDefault();
    var value = $("#type_notificaiton").val();
    if (value !== "") {
      $.ajax({
        url: "/admin/ajax/filter/notification",
        type: "get",
        data: { value: value },
        success: function (res) {
          var table = `
                        <table id="type_datatable" class="table table-bordered table-hover float-left">
                            <thead>
                                <tr>
                                    <th>Index</th>
                                    <th>Type</th>
                                    <th>Message</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>`;
          res.length > 0 &&
            res.forEach((itm, i) => {
              table +=
                ` <tr key="` +
                i +
                `">
                    <td>
                        ` +
                (i + 1) +
                `
                    </td>
                    <td style="text-transform: capitalize">
                    ` +
                itm.item.type +
                `
                    </td>
                    <td>
                        ` +
                itm.item.message +
                `
                    </td>
                    <td>
                        ` +
                itm.diff +
                `
                    </td>
                    <td class="project-actions">
                        <button class="btn btn-danger btn-sm viewNotification" data-id="` +
                itm.item.id +
                `" data-type="` +
                itm.item.type +
                `" title="View" href="#"
                            data-toggle="modal" data-target="#modal-view-notification">
                            <i class="fas fa-eye">
                            </i>
                        </button>
                    </td>
                </tr>`;
            });
          if (res.length == 0) {
            table += `<tr class="odd"><td valign="top" colspan="5" class="dataTables_empty">No data available in table</td></tr>`;
          }
          table += `</tbody>
                    <tfoot>
                        <tr>
                            <th>Index</th>
                            <th>Type</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </tfoot>
                </table>`;
          $("#ajax_table").html(table);
          $("#type_datatable").DataTable({
            paging: true,
            ordering: true,
            autoWidth: true,
            responsive: true,
          });
        },
        error: function (err) {
          console.error("type error", err);
        },
      });
    }
  });

  //Date picker
  $("#datepicker").datepicker({ dateFormat: "yy/mm/dd" });
  //delete notification
  $("#deleteNotification").on("click", function (e) {
    e.preventDefault();
    var date = $("#datepicker").val();
    date = date.replaceAll("/", "-");
    var url = $(".deleteNotificationForm").data("url") + date;
    $(".deleteNotificationForm").attr("action", url);
  });

  // new_order_table datatable
  $("#new_order_table").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
    searching: false,
    bInfo: false,
    iDisplayLength: 5,
    lengthChange: false,
    pagingType: "numbers",
  });

  $(document).ready(function () {
    //Initialize your table
    var table = $("#new_order_table").dataTable();
    //Get the total rows
    var total = table.fnGetData().length;
    if (total > 0) {
      $("#countNewOrder").html(
        `<p> Total Entries: ` + table.fnGetData().length + `</p>`
      );
    }
  });

  // readyDelivery_table datatable
  $("#readyDelivery_table").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
    searching: false,
    bInfo: false,
    iDisplayLength: 5,
    lengthChange: false,
    pagingType: "numbers",
  });

  $(document).ready(function () {
    //Initialize your table
    var table = $("#readyDelivery_table").dataTable();
    //Get the total rows
    var total = table.fnGetData().length;
    if (total > 0) {
      $("#countReadyDelivery span").html(
        `<p> Total Entries: ` + total + `</p>`
      );
    }
  });

  // availabe datatable
  $("#available_table").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
    searching: false,
    bInfo: false,
    // aLengthMenu: [[5, 10, 15, 20], [5, 10, 15, 20 ]],
    iDisplayLength: 5,
    lengthChange: false,
    pagingType: "numbers",
  });

  $(document).ready(function () {
    //Initialize your table
    var table = $("#available_table").dataTable();
    //Get the total rows
    var total = table.fnGetData().length;
    if (total > 0) {
      $("#countAvailable").html(
        `<p> Total Entries: ` + table.fnGetData().length + `</p>`
      );
    }
  });

  // delivery datatable
  $("#delivery_table").DataTable({
    paging: true,
    ordering: true,
    autoWidth: true,
    responsive: true,
    searching: false,
    bInfo: false,
    iDisplayLength: 5,
    lengthChange: false,
    pagingType: "numbers",
  });

  $(document).ready(function () {
    //Initialize your table
    var table = $("#delivery_table").dataTable();
    //Get the total rows
    var total = table.fnGetData().length;
    if (total > 0) {
      $("#countDelivery").html(
        `<p> Total Entries: ` + table.fnGetData().length + `</p>`
      );
    }
  });
  $(document).on("click", "#new_order_table tbody tr  td", function (e) {
    $("#modal-view").modal("show");
    var id = $(e.target).closest("tr").data("id");
    var custId = $(e.target).closest("tr").data("cust");
    $.ajax({
      url: "/admin/ajax/order/verify",
      type: "get",
      data: { id: id, customer_id: custId },
      success: function (res) {
        res.forEach((itm, i) => {
          if (itm.customer_id) {
            var notes = "";
            var table = `
                                <div class="form-group row">
                                    <div class="custName col-5">
                                        <label class="px-2 ">Name: </label>
                                        <span >`;
            res.forEach((itm) => {
              table +=
                itm.Customer.User.first_name +
                " " +
                itm.Customer.User.last_name;
            });
            table += `       </span>
                                    </div>
                                    <div class="custName col-2 text-center">
                                        <label class="px-2 ">Order Id: </label>
                                        <span >`;
            res.forEach((itm) => {
              table += `<b> ` + itm.id + `</b>`;
            });
            table += `   </span>
                                </div>
                                    <div class="custName col-5 text-right">
                                        <label class="px-2 ">Date: </label>
                                        <span >`;
            res.forEach((itm) => {
              var date = new Date(itm.updatedAt);
              var update = date.toDateString();
              var time = date.getHours();
              var minutes = date.getMinutes();
              time = time % 12;
              time = time ? time : 12; // the hour '0' should be '12'
              minutes = minutes < 10 ? "0" + minutes : minutes;
              table += update + ` ` + time + `:` + minutes;
            });
            table += `       </span>
                                    </div>
                                </div>
                                <table id="order_view_details" class="table table-border ">
                                    <thead>
                                        <tr>
                                        <th>#</th>
                                        <th>Product</th>
                                        <th>Packing</th>
                                        <th class="text-right">Qty</th>
                                        <th class="text-right">Price Per</th>
                                        <th class="text-right">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;
            res.length > 0 &&
              res.forEach((itm) => {
                itm.OrderItems.forEach((ordItm, i) => {
                  table +=
                    `   <tr key="` +
                    i +
                    `">
                                        <td> ` +
                    (i + 1) +
                    ` </td>
                                        <td> ` +
                    ordItm.product_name +
                    ` </td>
                                        <td> ` +
                    ordItm.packing_name +
                    ` </td>
                                        <td class="text-right"> ` +
                    ordItm.qty +
                    ` </td>
                                        <td class="text-right"> ` +
                    ordItm.rate +
                    ` </td>
                                        <td class="text-right"> ` +
                    ordItm.rate * ordItm.qty +
                    ` </td>
                                    </tr>`;
                });
              });
            if (res.length == 0) {
              table += `<tr class="odd"><td valign="top" colspan="6" class="dataTables_empty">No data available in table</td></tr>`;
            }
            table += `</tbody>
                                </table>`;
            res.length > 0 &&
              res.forEach((itm, i) => {
                if (i == 0 && itm.notes) {
                  notes +=
                    `
                                <aside class="aside">
                                    <h5 class="text-center"><span>Delivery Note:</span></h5>
                                    <div>
                                        <p class="text-center">` +
                    itm.notes +
                    `</p>
                                    </div>
                                </aside>`;
                }
              });

            res.length > 0 &&
              res.forEach((itm, i) => {
                if (i == 0) {
                  table +=
                    `
                                <table class="balance">
                                    <tr>
                                        <th colspan="5"><span>Subtotal</span></th>
                                        <td><span data-prefix>$</span><span>` +
                    itm.subtotal +
                    `</span></td>
                                    </tr>
                                    <tr>
                                        <th colspan="5"><span>Discount</span></th>
                                        <td><span data-prefix>$</span><span>` +
                    itm.discount +
                    `</span></td>
                                    </tr>
                                    <tr>
                                        <th colspan="5"><span>Tax</span></th>
                                        <td><span data-prefix>$</span><span>` +
                    itm.tax +
                    `</span></td>
                                    </tr>
                                    <tr>
                                        <th colspan="5"><span>Delivery Charge</span></th>
                                        <td><span data-prefix>$</span><span>` +
                    itm.delivery +
                    `</span></td>
                                    </tr>
                                    <tr>
                                        <th colspan="5"><span>Grand Total</span></th>
                                        <td><span data-prefix>$</span><span>` +
                    itm.grandtotal +
                    `</span></td>
                                    </tr>
                                </table>`;
                }
              });
            table += notes;
            res.forEach((itm) => {
              table +=
                `<br>
                                <div class="row">
                                    <div class="mx-auto">
                                        <button data-dismiss="modal" class="py-2 px-3 btn btn-danger float-left">
                                            Cancel &nbsp;<i class="fa fa-times"></i>
                                        </button>
                                        <form class="updateStatusForm pl-1 float-left" action="" data-url="/admin/order/update/" method="POST">
                                            <button class="updateStatus py-2 px-3 btn btn-success" data-id="` +
                id +
                `" data-status="readyfordelivery" >
                                                Ready For Delivery &nbsp;<i class="fa fa-check"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div> `;
            });
            $("#orderDetails").html(table);
            $("#modal-view").modal("show");
          } else {
            var table = `  <div class="container">
                                <div class="mySlides activeSlide">`;
            res.length > 0 &&
              res.forEach((itm) => {
                if (itm.front_id) {
                  table +=
                    `
                                                <img 
                                                    src="/images/` +
                    itm.front_id +
                    `" 
                                                    alt="Frontside Id"
                                                />`;
                }
              });
            table += `</div>
                                <div class="mySlides">`;
            res.length > 0 &&
              res.forEach((itm) => {
                if (itm.back_id) {
                  table +=
                    `
                                                <img 
                                                    src="/images/` +
                    itm.back_id +
                    `" 
                                                    alt="Backside Id"
                                                />`;
                }
              });
            table += `</div>
                                <div class="mySlides">`;
            res.length > 0 &&
              res.forEach((itm) => {
                if (itm.user_with_id) {
                  table +=
                    `
                                                <img 
                                                    src="/images/` +
                    itm.user_with_id +
                    `" 
                                                    alt="User with Id"
                                                />`;
                }
              });
            table += `</div>
                                  
                                <a class="prevBtn" onclick="plusSlides(-1)">❮</a>
                                <a class="nextBtn" onclick="plusSlides(1)">❯</a>
                              
                                <div class="row">
                                <div class="col-10 mx-auto">
                                  <div class="column col-4 float-left ">`;
            res.length > 0 &&
              res.forEach((itm, i) => {
                if (itm.front_id) {
                  table +=
                    `
                                                <img 
                                                    class="activeColumn demo cursor "
                                                    src="/images/` +
                    itm.front_id +
                    `" 
                                                    alt="Frontside Id"
                                                    onclick="currentSlide(1)"
                                                />`;
                }
              });
            table += `  </div>
                                  <div class="column col-4 float-left">`;
            res.length > 0 &&
              res.forEach((itm, i) => {
                if (itm.back_id) {
                  table +=
                    `
                                                <img 
                                                    class="demo cursor"
                                                    src="/images/` +
                    itm.back_id +
                    `" 
                                                    alt="Backside Id"
                                                    onclick="currentSlide(2)"
                                                />`;
                }
              });
            table += `  </div>
                                  <div class="column col-4 float-left">`;
            res.length > 0 &&
              res.forEach((itm, i) => {
                if (itm.user_with_id) {
                  table +=
                    `
                                                <img 
                                                    class="demo cursor"
                                                    src="/images/` +
                    itm.user_with_id +
                    `" 
                                                    alt="User with Id"
                                                    onclick="currentSlide(3)"
                                                />`;
                }
              });
            table += `  </div>
                                </div>
                                </div>
                              </div>`;

            table +=
              `<br>
                            <div class="row">
                                <div class="mx-auto">
                                    <form class="updateStatusForm pr-1 float-left" action="" data-url="/admin/order/update/" method="POST">
                                        <button type="submit" class="updateStatus py-2 px-3 btn btn-danger" data-id="` +
              id +
              `" data-status="cancel">
                                            Reject &nbsp;<i class="fa fa-times"></i>
                                        </button>
                                    </form>
                                        <button class="py-2 px-3 btn btn-success approveOrder" data-id="` +
              id +
              `" >
                                            Approve &nbsp;<i class="fa fa-check"></i>
                                        </button>
                                </div>
                            </div>`;
            $("#orderDetails").html(table);
            $("#ordertitle").text("Age Verification");
            $("#modal-view").modal("show");
          }
        });

        $("#order_details").DataTable({
          paging: false,
          lengthChange: false,
          ordering: true,
          autoWidth: false,
          responsive: true,
        });
      },
      error: function (err) {
        console.error("type error", err);
      },
    });
  });
  //update status  order
  $(document).on("click", ".updateStatus", function () {
    var status = $(this).data("status");
    var id = $(this).data("id");

    var url = $(".updateStatusForm").data("url") + id + "/" + status;
    $(".updateStatusForm").attr("action", url);
  });

  $(document).on("click", ".approveOrder", function (e) {
    $("#modal-view").modal("hide");
    $("#order-view").modal("show");
    var id = $(this).data("id");
    $.ajax({
      url: "/admin/ajax/full-order",
      type: "get",
      data: { id: id },
      success: function (res) {
        var notes = "";
        var table = `
                        <div class="form-group row">
                            <div class="custName col-5">
                                <label class="px-2 ">Name: </label>
                                <span >`;
        res.forEach((itm) => {
          table +=
            itm.Customer.User.first_name + " " + itm.Customer.User.last_name;
        });
        table += `       </span>
                            </div>
                            <div class="custName col-2 text-center">
                                <label class="px-2 ">Order Id: </label>
                                <span >`;
        res.forEach((itm) => {
          table += `<b> ` + itm.id + `</b>`;
        });
        table += `   </span>
                        </div>
                            <div class="custName col-5 text-right">
                                <label class="px-2 ">Date: </label>
                                <span >`;
        res.forEach((itm) => {
          var date = new Date(itm.updatedAt);
          var update = date.toDateString();
          var time = date.getHours();
          var minutes = date.getMinutes();
          time = time % 12;
          time = time ? time : 12; // the hour '0' should be '12'
          minutes = minutes < 10 ? "0" + minutes : minutes;
          table += update + ` ` + time + `:` + minutes;
        });
        table += `       </span>
                            </div>
                        </div>
                        <table id="order_view_details" class="table table-border ">
                            <thead>
                                <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th>Packing</th>
                                <th class="text-right">Qty</th>
                                <th class="text-right">Price Per</th>
                                <th class="text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody>`;
        res.length > 0 &&
          res.forEach((itm) => {
            itm.OrderItems.forEach((ordItm, i) => {
              table +=
                `   <tr key="` +
                i +
                `">
                                <td> ` +
                (i + 1) +
                ` </td>
                                <td> ` +
                ordItm.product_name +
                ` </td>
                                <td> ` +
                ordItm.packing_name +
                ` </td>
                                <td class="text-right"> ` +
                ordItm.qty +
                ` </td>
                                <td class="text-right"> ` +
                ordItm.rate +
                ` </td>
                                <td class="text-right"> ` +
                ordItm.rate * ordItm.qty +
                ` </td>
                            </tr>`;
            });
          });
        if (res.length == 0) {
          table += `<tr class="odd"><td valign="top" colspan="6" class="dataTables_empty">No data available in table</td></tr>`;
        }
        table += `</tbody>
                        </table>`;
        res.length > 0 &&
          res.forEach((itm, i) => {
            if (i == 0 && itm.notes) {
              notes +=
                `
                        <aside class="aside">
                            <h5 class="text-center"><span>Delivery Note:</span></h5>
                            <div>
                                <p class="text-center">` +
                itm.notes +
                `</p>
                            </div>
                        </aside>`;
            }
          });

        res.length > 0 &&
          res.forEach((itm, i) => {
            if (i == 0) {
              table +=
                `
                        <table class="balance">
                            <tr>
                                <th colspan="5"><span>Subtotal</span></th>
                                <td><span data-prefix>$</span><span>` +
                itm.subtotal +
                `</span></td>
                            </tr>
                            <tr>
                                <th colspan="5"><span>Discount</span></th>
                                <td><span data-prefix>$</span><span>` +
                itm.discount +
                `</span></td>
                            </tr>
                            <tr>
                                <th colspan="5"><span>Tax</span></th>
                                <td><span data-prefix>$</span><span>` +
                itm.tax +
                `</span></td>
                            </tr>
                            <tr>
                                <th colspan="5"><span>Delivery Charge</span></th>
                                <td><span data-prefix>$</span><span>` +
                itm.delivery +
                `</span></td>
                            </tr>
                            <tr>
                                <th colspan="5"><span>Grand Total</span></th>
                                <td><span data-prefix>$</span><span>` +
                itm.grandtotal +
                `</span></td>
                            </tr>
                        </table>`;
            }
          });
        table += notes;
        res.forEach((itm) => {
          table +=
            `<br>
                        <div class="row">
                            <div class="mx-auto">
                                <button data-dismiss="modal" class="py-2 px-3 btn btn-danger float-left">
                                    Cancel &nbsp;<i class="fa fa-times"></i>
                                </button>
                                <form class="updateStatusForm pl-1 float-left" action="" data-url="/admin/order/update/" method="POST">
                                    <button class="updateStatus py-2 px-3 btn btn-success" data-id="` +
            id +
            `" data-status="readyfordelivery" >
                                        Ready For Delivery &nbsp;<i class="fa fa-check"></i>
                                    </button>
                                </form>
                            </div>
                        </div> `;
        });
        $("#details").html(table);
        $("#order-view").modal("show");
      },
      error: function (err) {
        console.error("type error", err);
      },
    });
  });
  $(document).on("click", ".readyForDeliveryCheck", function (e) {
    if ($(this).prop("checked") == true) {
      var assign = document.getElementById("assign");
      assign.style.display = "block";
    }
  });
  $(document).on("click", "#assign", function (e) {
    $("#available-view").modal("show");
    let arr = [];
    $("input:checkbox[name=readyForDeliveryCheck]:checked").each(function () {
      arr.push($(this).val());
    });

    $.ajax({
      url: "/admin/ajax/available",
      type: "get",
      data: { idArr: arr },
      success: function (res) {
        console.log("res", res);
      },
      error: function (err) {
        console.error("type error---", err);
      },
    });
  });
  // dashboard graph data
  $(document).on("click", ".graphData", function () {
    var type = $(this).data("id");
    $(".graphData a").removeClass("active");
    $(this).find('a').addClass("active");
    $.ajax({
      url: "/admin/ajax/dashboard",
      type: "get",
      data: { type },
      success: function (res) {
        $("#graphData").html(`<canvas id="myChart" width="300" height="300"></canvas>`);
        
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
              labels: res,
              datasets: [{
                label: 'Minted Token',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1,
                data: res
              }]
            },
            options: {
              plugins: {
                legend: {
                  display: false,
                },
                datalabels: {
                  display: false
                },
                title: {
                  display: true,
                }
              },
              responsive: true,
              scales: {
                x: {
                  grid: {
                    display: true,
                    drawBorder: true,
                  },
                  beginAtZero: true
                },
                y: {
                  grid: {
                    display: true,
                    drawBorder: true,
                  },
                  beginAtZero: true
                }
              }
            }
        });
      },
      error: function (err) {
        console.error("type error---", err);
      },
    });
  });
});
