<div class="message_delete_equipment"></div>

<table id="equipmentTypes" class="table table-striped table-bordered mt-3" style="width:100%">
  <thead>
    <tr>
      <?php if ($login_user['role'] == "Super Admin"): ?>
        <th>Client ID</th>
      <?php endif; ?>

      <th>Equipment Type</th>
      <th>Create Time <?php echo '<sup> (UTC ' . htmlspecialchars((string)$login_user['TimeZone'], ENT_QUOTES, 'UTF-8') . ')</sup>'; ?></th>

      <?php if ($login_user['Devices'] == 'Edit' || $login_user['Operators'] == 'Edit'): ?>
        <th>Actions</th>
      <?php endif; ?>
    </tr>
  </thead>

  <tbody>
    <?php if (!$equipmentTypes): ?>
      <tr>
        <td colspan="<?= ($login_user['role'] == 'Super Admin') ? 4 : 3 ?>" style="text-align:center;">
          There are no equipment types
        </td>
      </tr>
    <?php endif; ?>

    <?php foreach ($equipmentTypes as $eq): ?>
      <?php
        $eqId = (int)($eq['Id'] ?? 0);
        $eqClientId = (string)($eq['ClientId'] ?? '');
        $eqType = (string)($eq['Type'] ?? '');
      ?>

      <tr>
        <?php if ($login_user['role'] == "Super Admin"): ?>
          <td><?= htmlspecialchars($eqClientId, ENT_QUOTES, 'UTF-8') ?></td>
        <?php endif; ?>

        <td>
          <input type="text"
                 class="updateEquipmentType<?= $eqId ?>"
                 style="background-color: transparent; border: 0px; padding: 0px;"
                 value="<?= htmlspecialchars($eqType, ENT_QUOTES, 'UTF-8') ?>">

          <input type="hidden"
                 class="EqId<?= $eqId ?>"
                 value="<?= $eqId ?>">
        </td>

        <td>
          <?php
            $start = $eq['CreationTime'] ?? null;

            echo $start
              ? htmlspecialchars(date('Y-m-d H:i:s', strtotime((string)$login_user['TimeZone'] . 'hour', strtotime($start))), ENT_QUOTES, 'UTF-8')
              : '-';
          ?>
        </td>

        <?php if ($login_user['Devices'] == 'Edit' || $login_user['Operators'] == 'Edit'): ?>
          <td>
            <div class="table-actions d-flex align-items-center gap-3 fs-6">
              <a href="#"
                 class="text-warning js-save-eq"
                 data-id="<?= $eqId ?>"
                 data-bs-toggle="tooltip"
                 title="Save">
                <i class="lni lni-save"></i>
              </a>

              <a href="#"
                 class="text-danger js-del-eq"
                 data-id="<?= $eqId ?>"
                 data-bs-toggle="tooltip"
                 title="Delete">
                <i class="bi bi-trash-fill"></i>
              </a>

              <span class="message_eq_edit<?= $eqId ?>"></span>
            </div>
          </td>
        <?php endif; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<script>
$(function () {
  var delay = 150;

  $(document).off('click', '.AddEquipmentType').on('click', '.AddEquipmentType', function(e) {
    e.preventDefault();

    var typeName = $.trim($('.EquipmentTypeName').val());

    if (!typeName) {
      alert('Please enter equipment type.');
      return;
    }

    var clientId = '';

    <?php if ($_SESSION['role'] == "Super Admin"): ?>
      clientId = $('.EquipmentClientId').val();
    <?php else: ?>
      clientId = <?= json_encode((string)($_SESSION['ClientId'] ?? '')) ?>;
    <?php endif; ?>

    if (!clientId) {
      alert('Client ID is missing.');
      return;
    }

    $.ajax({
      type: "POST",
      url: "/admin/devices",
      data: {
        EquipmentTypeAddAjax: 1,
        addEquipmentType: typeName,
        EquipmentClientId: clientId
      },
      beforeSend: function() {
        $('.equipment_type_table').html('<div class="spinner-border"></div>');
      },
      success: function(html) {
        setTimeout(function() {
          $('.equipment_type_table').html(html);
          $('.EquipmentTypeName').val('').focus();
        }, delay);
      },
      error: function(xhr) {
        console.log(xhr.responseText || xhr.statusText);
        alert('Error adding equipment type.');
      }
    });
  });

  $(document).off('click', '.js-save-eq').on('click', '.js-save-eq', function(e) {
    e.preventDefault();

    var id = $(this).data('id');
    var val = $.trim($('.updateEquipmentType' + id).val());

    if (!val) {
      $('.message_eq_edit' + id).html('<span class="text-danger">Required</span>');
      return;
    }

    $.ajax({
      type: "POST",
      url: "/admin/devices",
      data: {
        EquipmentTypeUpdateAjax: 1,
        Id: id,
        Type: val
      },
      beforeSend: function() {
        $('.message_eq_edit' + id).html('<span class="spinner-border spinner-border-sm"></span>');
      },
      success: function(html) {
        setTimeout(function() {
          $('.equipment_type_table').html(html);
        }, delay);
      },
      error: function(xhr) {
        console.log(xhr.responseText || xhr.statusText);
        $('.message_eq_edit' + id).html('<span class="text-danger">Error</span>');
      }
    });
  });

  $(document).off('click', '.js-del-eq').on('click', '.js-del-eq', function(e) {
    e.preventDefault();

    var id = $(this).data('id');

    if (!confirm('Delete this equipment type?')) {
      return;
    }

    $.ajax({
      type: "POST",
      url: "/admin/devices",
      data: {
        EquipmentTypeDeleteAjax: 1,
        Id: id
      },
      beforeSend: function() {
        $('.equipment_type_table').html('<div class="spinner-border"></div>');
      },
      success: function(html) {
        setTimeout(function() {
          $('.equipment_type_table').html(html);
        }, delay);
      },
      error: function(xhr) {
        console.log(xhr.responseText || xhr.statusText);
        alert('Error deleting equipment type.');
      }
    });
  });
});
</script>