<?php
require "../../src/config.php";

page::set([
  "title" => "Mail Search",
  "nav-parent" => "mail_search"
]);

page::header();
?>


<div class="card">
  <div class="card-body">
    <div id="results"></div>
  </div>
</div>

<script id="case_result_template" type="text/template">


  {{#count}}

    <div id="search_bodytext" class="text center text-strong text-primary py-3">
      {{count}} Results
    </div>

    <div class="datalist">

      {{#data}}
        <div class="listitem">

          <a href="/<?= SUBFOLDER ?>cases/summary?id={{case_id}}" target="_blank">

            <div class="listitem-content">

              <div class="row">

                <div class="col col-w4 p-2">
                  <div class="tag-id w-100 text-md">{{case_id}}</div>
                </div>


                <div class="col ps-2">
                  <div class="text-strong">{{{case_title}}}</div>
                  <div class="text-xs progress-text-{{state}}">{{state_note}}</div>
                </div>

              </div>

            </div>

          </a>

        </div>
      {{/data}}

    </div>
  {{/count}}

  {{^count}}
    <div class="center pt-3">
      <div id="search_bodytext" class="text center text-strong text-primary">
        {{#search_term}}
          Nothing Found for "{{search_term}}"
        {{/search_term}}
        {{^search_term}}
          Start typing at least 3 characters to see results!
        {{/search_term}}
      </div>
      <img class="col-w12 m-2" src="/<?= SUBFOLDER ?>src/images/search.png" alt="">
    </div>
  {{/count}}
  </div>

</script>

<script>
  $("#search_title, #search_sender").on("input", search);
  $("#search_cs").on("change", search);

  var searchlog = [];

  function search() {

    let timestamp = Date.now();
    var search_title = $("#search_title").val();

    searchlog.push({
      "timestamp": timestamp,
      "title": search_title
    });

    if (search_title.length < 3) {
      render({
        "message": "Enter atleast 3 characters to search"
      });

      $("#search_title").removeClass("inputstate-valid").addClass("inputstate-invalid");

    } else if (search_title.length > 2) {

      $("#search_title").removeClass("inputstate-invalid").addClass("inputstate-valid");

      setTimeout(function() {

        let lastsearch = searchlog.slice(-1)[0];

        if (lastsearch.timestamp == timestamp) {

          $("#results").html(UI_loading);

          $.getJSON(API + "cases/search.php", {
            title: lastsearch.title
          }, render);

        } else {
          console.log("Obsolete Search Discarded");
          return;
        }
      }, 1500);

    }

  }

  function render(render_data) {
    var template = $("#case_result_template").html();
    content = Mustache.render(template, render_data);
    $("#results").html(content);
  }

  search();
</script>

<?php page::footer(); ?>