<script type="text/javascript">
  /**
   * tutor index page script.
   * @script start
   */
  $(document).ready(function () {
    $(".select2").select2({
      allowClear: false,
    });

    $("#tutor-subjects").select2({
      placeholder: "Select Subject",
      allowClear: false,
    });

    dataTable();
  });

  $(".filter").click(function () {
    let tutor_name = $("#tutor-name").val();
    let tutor_subjects = $("#tutor-subjects").val();
    let status = $("#status").val();
    dataTable(tutor_name, tutor_subjects, status);
  });

  $(".reset").click(function () {
    $("#tutor-name").val(null).trigger("change");
    $("#tutor-subjects").val(null).trigger("change");
    $("#status").val(null).trigger("change");
    dataTable();
  });

  function dataTable(tutor_name = "", tutor_subjects = "", status = "") {
    $("#tutorTable").dataTable().fnDestroy();
    var userRole = "";
    var tutorTable = $("#tutorTable").DataTable({
      paging: true,
      pageLength: 10,
      language: {
        searchPlaceholder: "Search",
        processing: "<div><div></div><div></div><div></div><div></div></div>",
      },
      processing: true,
      serverSide: true,
      order: [],
      dom: "Bfltip",
      buttons: {
        buttons: [
          { extend: "excel" },
          {
            extend: "pdfHtml5",
            orientation: "landscape",
            pageSize: "A0",
            title: "Users List PDF",
            exportOptions: {
              modifier: {
                page: "current",
              },
            },
          },
        ],
      },
      buttons: [
        {
          extend: "collection",
          text: "Tutors List",
          className: "btn-default-option",
          autoClose: true,
          buttons: [
            {
              text: "Excel",
              extend: "excelHtml5",
              className: "btn-default",
              title: "Tutors List",
              exportOptions: {
                columns: [1, 2, 3],
              },
            },
            {
              extend: "pdfHtml5",
              className: "btn-default",
              title: "Tutors List",
              exportOptions: {
                columns: [1, 2, 3],
              },
              customize: function (doc) {
                doc.styles.tableHeader.alignment = "left";
                (doc.content[1].margin = [20, 0, 20, 0]),
                  (doc.styles.tableBodyOdd.padding = 20);
                doc.styles.tableBodyEven.alignment = "left";
                (doc.content[1].table.widths = ["33%", "33%", "33%"]),
                  (objLayout = {});
                // Horizontal line thickness
                objLayout["hLineWidth"] = function (i) {
                  return 0;
                };
                // Vertikal line thickness
                objLayout["vLineWidth"] = function (i) {
                  return 0;
                };
                // Horizontal line color
                objLayout["hLineColor"] = function (i) {
                  return "#aaa";
                };
                // Left padding of the cell
                objLayout["padding"] = function (i) {
                  return 5;
                };
                // Right padding of the cell
                objLayout["paddingRight"] = function (i) {
                  return 5;
                };
                // Left padding of the cell
                objLayout["paddingTop"] = function (i) {
                  return 10;
                };
                // Right padding of the cell
                objLayout["paddingBottom"] = function (i) {
                  return 10;
                };
                // Inject the object in the document
                doc.content[1].layout = objLayout;
              },
            },
          ],
          fade: true,
        },
      ],
      ajax: {
        url: "/tutors/dataTable",
        type: "POST",
        data: {
          id: tutor_name,
          tutor_subjects: tutor_subjects,
          status: status,
        },
        // success: function(data) {
        // },
      },
      drawCallback: function (settings) {
        // Here the response
        var response = settings.json;
        userRole = response.userRole;
      },
      columns: [
        {
          data: "",
          render: function (data, type, row) {
            return `<input class="select-checkbox" type="checkbox" value="${row._id}"/>`;
          },
        },
        {
          data: "first_name",
          render: function (data, type, row) {
            return `<a href="/tutor-preferences/${row._id}">${row.first_name + " " + row.last_name}</a>`;
          },
        },
        {
          data: "email",
          name: "email",
          defaultContent: "",
        },
        {
          data: "phone",
          render: function (data, type, row) {
            return row.phone ? "+" + row.dial_code + " " + row.phone : "";
          },
        },
        {
          data: "subject_ids",
          render: function (data, type, row) {
            var html = `<div class="subcat-info">`;
            for (subject of data) {
              html += `<span class="badge badge-info">${subject.name}</span>`;
            }
            html += `</div>`;
            return html;
          },
        },
        {
          data: "status",
          render: function (data, type, row) {
            return `<label class="checkbox-inline switch-btn">
                      <input type="checkbox" name="status" class="record-status" data-url="/tutors/update-status" data-uid="${
                        row._id
                      }" ${row.status ? "checked" : ""}>
                        <span class="slider-toggle"></span>  
                    </label>`;
          },
        },
        {
          data: "",
          render: function (data, type, row) {
            let html = `<div class="d-flex align-items-center table_action_btn">
                      <a class="" href="/tutors/edit/${row._id}" data-toggle="tooltip" rel="tooltip" data-placement="top"
                        title="Edit"><img src="/images/edit.svg" alt="icon"></a>`;
            html += ` <a href="javascript:void(0)"  onclick="confirmBeforeSecretLogin('/secret/${row._id}')"><img src="/images/lock2.svg"
                        alt="icon" data-toggle="tooltip" rel="tooltip" data-placement="top" title="Secret Login"></a>`;

            html += ` <a href="javascript:void(0)"
                        onclick="confirmBeforeDeletion('/tutors/destroy/${row._id}')"><img src="/images/trash.svg"
                          alt="icon" data-toggle="tooltip" rel="tooltip" data-placement="top" title="Delete"></a>
                      </div>`;

            return html;
          },
        },
      ],
        select: {
          style: "multi",
          selector: ".select-checkbox"
        },
      // Select Column
      columnDefs: [
        {
          targets: 0,
          data: "select",
          searchable: false,
          orderable: false,
          width: "3%"
        },
        {
          targets: [0, 2, 3, 4, 6] /* column index */,
          orderable: false /* true or false */,
        }
      ],
    });
    //select all checkbox
    $("#select_all").on( "click", function(e) {
      if ($(this).is( ":checked" )) {
        tutorTable.rows().select();  
        $('.select-checkbox').prop('checked',true);  
      } else {
        tutorTable.rows().deselect(); 
        $('.select-checkbox').prop('checked',false);  
      }
    });
    tutorTable.ajax.reload( function() {
      // Reinitialize tooltips after reload
      $('[data-toggle="tooltip"]').tooltip('dispose'); 
      $('[data-toggle="tooltip"]').tooltip();
    });
  }

  /**
   * tutor index page script.
   * @script end
   */
</script>