<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
  integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css"
/>
<link
  rel="stylesheet"
  href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
  integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
/>
<style>
  a {
    text-decoration: none;
  }
  .chart {
    width: 100%;
    max-height: 20rem;
    /* background-color: black; */
  }
  table {
    width: 100%;
  }
  .toast {
    width: 12rem !important;
  }
  .btn-close-toast {
    position: relative !important;
    right: 1rem !important;
  }
</style>
<html>
  <!-- BODY  -->
  <div class="container-fluid">
    <div class="row mt-3 component-leads-header">
      <div class="col">
        <h1 class="ms-5">Admin Dashboard</h1>
      </div>
      <div class="col">
        <a class="link text-danger float-end mx-1"
          ><i class="fa fa-right-from-bracket"></i> Logout</a
        >
        <a
          class="link text-danger float-end mx-1"
          target="_blank"
          href="https://github.com/berrytechnics/repair_leads/issues/new"
          ><i class="fa fa-bug"></i> Report Bug</a
        >
        <a class="link text-danger float-end mx-1" href="/admin/users"
          ><i class="fa fa-user-astronaut"></i> Manage Users</a
        >
      </div>
    </div>
    <div class="row mt-3 component-leads-charts">
      <div class="card">
        <div class="card-header">
          <h5 class="card-title">Charts</h5>
          <ul class="nav nav-tabs card-header-tabs" data-bs-tabs="tabs">
            <li class="nav-item">
              <a
                class="nav-link active"
                aria-current="true"
                data-bs-toggle="tab"
                href="#tab-total"
                >Total</a
              >
            </li>
            <li class="nav-item">
              <a class="nav-link" data-bs-toggle="tab" href="#tab-potential"
                >Potential Revenue</a
              >
            </li>
            <li class="nav-item">
              <a class="nav-link" data-bs-toggle="tab" href="#tab-captured"
                >Captured Revenue</a
              >
            </li>
          </ul>
        </div>
        <div class="card-body tab-content">
          <div class="tab-pane active" id="tab-total">
            <h5>Leads by Store (current month)</h5>
            <canvas id="leads-byStore" class="chart"></canvas>
          </div>
          <div class="tab-pane" id="tab-potential">
            <h5>Potential Revenue (current month)</h5>
            <canvas id="leads-potential" class="chart"></canvas>
          </div>
          <div class="tab-pane" id="tab-captured">
            <h5>Captured Revenue (current month)</h5>
            <canvas id="leads-captured" class="chart"></canvas>
          </div>
        </div>
      </div>
    </div>
    <div class="row mt-3 component-leads-table">
      <div class="col">
        <table id="leadsTable" class="stripe hover">
          <thead>
            <tr>
              <th>Actions</th>
              <th>Location</th>
              <th>Date</th>
              <th>Name</th>
              <th>Email</th>
              <th>Phone</th>
              <th>Make</th>
              <th>Model</th>
              <th>Issue</th>
              <th>Quote</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>
  <!-- Lead Delete Modal -->
  <div class="modal deleteModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Heads up!</h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete this lead?</p>
        </div>
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-secondary"
            data-bs-dismiss="modal"
          >
            Cancel
          </button>
          <button type="button" class="btn btn-danger" onclick="deleteLead(event)">Delete Lead</button>
        </div>
      </div>
    </div>
  </div>
  <!-- Lead Edit Modal -->
  <div class="modal editModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Update Lead</h5>
          <button
            type="button"
            class="btn-close form-cancel"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <form action="/" name="form" method="GET">
          <div class="modal-body">
            <input required type="hidden" name="id" />
            <label class="fw-bold" for="name">Name:</label>
            <input required type="text" name="name" class="form-control" />
            <label class="fw-bold" for="name">Email:</label>
            <input required type="email" name="email" class="form-control" />
            <label class="fw-bold" for="name">Phone:</label>
            <input required type="phone" name="phone" class="form-control" />
            <label class="fw-bold" for="name">Make:</label>
            <input required type="text" name="make" class="form-control" />
            <label class="fw-bold" for="name">Model:</label>
            <input required type="text" name="model" class="form-control" />
            <label class="fw-bold" for="name">Issue:</label>
            <input required type="text" name="issue" class="form-control" />
            <label class="fw-bold" for="name">Price:</label>
            <input required type="text" name="price" class="form-control" />
            <div class="form-check mt-1">
              <input class="form-check-input" type="checkbox" id="converted" />
              <label class="form-check-label" for="converted">
                Converted
              </label>
            </div>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary form-cancel"
              data-bs-dismiss="modal"
            >
              Cancel
            </button>
            <input type="submit" class="btn btn-primary" value="Update Lead" />
          </div>
        </form>
      </div>
    </div>
  </div>
  <!-- TOAST  -->
  <div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div
      id="liveToast"
      class="toast toast-sm"
      role="alert"
      aria-live="assertive"
      aria-atomic="true"
      data-bs-delay="1500"
    >
      <div class="toast-body">
        <div class="row">
          <div class="col text-center toast-body-text"></div>
          <div class="col-2">
            <button
              type="button"
              class="btn-close btn-close-toast"
              data-bs-dismiss="toast"
              aria-label="Close"
            ></button>
          </div>
        </div>
      </div>
    </div>
  </div>
</html>
<script
  src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"
></script>
<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"
  integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V"
  crossorigin="anonymous"
></script>
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"
  integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
></script>
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js"
  integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
<script>
  // Variables
  let models = JSON.parse(`<%- JSON.stringify(models) %>`);
  let chartColors;
  let datatable;
  let toast, prevToastStyle;

  // Chart setup
  function _initChart() {
    // Chart setup - Total
    const byStore_X = models
      .map((model) => model.location)
      .filter((model, i, self) => self.indexOf(model) === i);
    const byStore_Y = [];
    byStore_X.forEach((store) => {
      const leads = models.filter((model) => model.location == store);
      byStore_Y.push(leads.length);
    });

    // Chart init
    const leadsByStoreChart = new Chart("leads-byStore", {
      type: "bar",
      data: {
        labels: byStore_X,
        datasets: [
          {
            backgroundColor: chartColors,
            data: byStore_Y,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: false },
        title: {
          display: true,
        },
      },
    });

    // Chart setup - Potential
    const potential_X = models
      .map((model) => model.location)
      .filter((model, i, self) => self.indexOf(model) === i);
    const potential_Y = [];
    potential_X.forEach((store) => {
      const leads = models.filter((model) => model.location == store);
      let total = 0;
      leads.forEach((lead) => {
        let n = lead.price;
        if (isFinite(n)) total += n;
      });
      potential_Y.push(Math.floor(total));
    });

    // Chart init
    const leadsPotentialChart = new Chart("leads-potential", {
      type: "bar",
      data: {
        labels: potential_X,
        datasets: [
          {
            backgroundColor: chartColors,
            data: potential_Y,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: false },
        title: {
          display: true,
        },
      },
    });

    // Chart setup - Captured
    const captured_X = models
      .map((model) => model.location)
      .filter((model, i, self) => self.indexOf(model) === i);
    const captured_Y = [];
    captured_X.forEach((store) => {
      let leads = models.filter((model) => model.location == store);
      leads = leads.filter((lead) => lead.converted);
      let total = 0;
      leads.forEach((lead) => {
        let n = lead.price;
        if (isFinite(n)) total += n;
      });
      captured_Y.push(Math.floor(total));
    });

    // Chart init
    const leadsCapturedChart = new Chart("leads-captured", {
      type: "bar",
      data: {
        labels: captured_X,
        datasets: [
          {
            backgroundColor: chartColors,
            data: captured_Y,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: false },
        title: {
          display: true,
        },
      },
    });
  }
  function _initChartColors() {
    chartColors = [];
    const byStore_X = models
      .map((model) => model.location)
      .filter((model, i, self) => self.indexOf(model) === i);
    const byStore_Y = [];
    byStore_X.forEach((store) => {
      const color = "#" + Math.floor(Math.random() * 16777215).toString(16);
      chartColors.push(color);
      const leads = models.filter((model) => model.location == store);
      byStore_Y.push(leads.length);
    });
  }

  // Edit modal
  function editModal(e) {
    const model = models.find((model) => model._id == e.currentTarget.id);
    $("input[name=id]").val(model._id).removeClass("is-invalid");
    $("input[name=name]").val(model.name).removeClass("is-invalid");
    $("input[name=email]").val(model.email).removeClass("is-invalid");
    $("input[name=phone]").val(model.phone).removeClass("is-invalid");
    $("input[name=make]").val(model.make).removeClass("is-invalid");
    $("input[name=model]").val(model.model).removeClass("is-invalid");
    $("input[name=issue]").val(model.issue).removeClass("is-invalid");
    $("input[name=price]").val(model.price).removeClass("is-invalid");
    $("input[name=converted]").prop("checked", model.converted);
  }
  function resetModal() {
    $(".form-control").val("");
    $(".form-control").removeClass("is-valid");
    $(".editModal").modal("hide");
  }
  $("form").submit(function (e) {
    e.preventDefault();
    e.stopPropagation();
    let formData = formJson($(this));
    formData.converted = $("input[id=converted]").is(":checked");
    $.post("lead/update", formData, (res) => {
      if (res.errors) {
        res.errors.forEach((error) => {
          $(`input[name=${error}]`).addClass("is-invalid");
        });
      } else {
        $(`input.form-control`).addClass("is-valid");
        setToast('Lead Updated.','success');
        console.log(res);
        resetModal();
      }
    });
  });
  $(".form-cancel").click((e) => resetEditModal());

  // Convert form element data to JSON
  function formJson(form) {
    return $(form)
      .serializeArray()
      .reduce(function (json, { name, value }) {
        json[name] = value;
        return json;
      }, {});
  }

  // Sets toast data and displays
  function setToast(text, style, delay = 1500) {
    $(".toast")
      .removeClass(`text-bg-${prevToastStyle}`)
      .addClass(`text-bg-${style}`)
      .attr("data-bs-delay", delay);
    $(".toast-body-text").html(`${text}`);
    $("#liveToast").toast("show");
    prevToastStyle = style;

  }

  // Page Load
  $(document).ready(function () {
    // Datatable init
    $.fn.dataTable.moment("M/DD");
    $.fn.dataTable.ext.errMode = false;
    datatable = $("#leadsTable").DataTable({
      dom: "Bfrtip",
      pageLength: 1000,
      buttons: [
        {
          text: `<span id="liveToastBtn" class="p-1"><i class="fa fa-arrows-rotate"></i></span>`,
          action: async function (e, dt, node, config) {
            data = await dt.ajax.reload();
            setToast("Leads Reloaded", "secondary");
            models = data.context[0].json.data;
            _initChart();
          },
        },
        "csv",
      ],
      ajax: "lead/dataTable",
      order: [
        [2, "desc"],
        [1, "desc"],
      ],
      columnDefs: [{ orderable: false, targets: 0 }],
      columns: [
        {
          data: null,
          render: function (data, type, row) {
            return `
                <a id="${data._id}" data-bs-toggle="modal" onclick="editModal(event)" data-bs-target=".editModal" href="#" class="link link-edit"><i class="fa fa-money-check-dollar text-success me-2"></i></a>
                <a id="${data._id}" data-bs-toggle="modal" data-bs-target=".deleteModal" class="link" href="#"><i class="fa fa-trash text-danger"></i></a>
                `;
          },
        },
        { data: "location" },
        {
          data: "date",
          render: function (data, type, row) {
            var date = new Date(data);
            return moment(date).format("M/DD");
          },
        },
        { data: "name" },
        { data: "email" },
        {
          data: "phone",
          render: function (data, type, row) {
            return data.replace("-", "");
          },
        },
        { data: "make" },
        { data: "model" },
        { data: "issue" },
        {
          data: "price",
          render: function (data, type, row) {
            if (data == null || data == 0 || data == "0") return "N/A";
            else return data;
          },
        },
      ],
    });
    // Chart init
    _initChartColors();
    _initChart();
  });
</script>
