<!DOCTYPE html>
<html lang="{{ current_language }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ _('cards_on_device') or 'Cards on Device' }} - {{ device_id }}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
:root { --primary-color:#667eea; --secondary-color:#764ba2; --success-color:#28a745; --warning-color:#ffc107; --danger-color:#dc3545; --info-color:#17a2b8; --dark-color:#343a40; }
body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
.navbar { background: rgba(255,255,255,0.95) !important; backdrop-filter: blur(10px); box-shadow: 0 2px 20px rgba(0,0,0,0.1); }
.main-container { margin-top: 80px; padding: 20px 0; }
.card-modern { background: rgba(255,255,255,0.95); border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); overflow: hidden; border:none; }
.card-header-modern { background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color:white; padding: 25px 30px; border:none; }
.card-header-modern h2 { margin:0; font-size:1.6rem; font-weight:700; }
.card-body-modern { padding: 24px; }
.btn-modern { border-radius: 10px; padding: 8px 16px; font-weight: 600; font-size: 0.85rem; transition: all 0.3s ease; border: none; }
.btn-modern:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); }
.btn-primary-modern { background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color: white; }
.btn-secondary-modern { background: linear-gradient(135deg, #6c757d, #495057); color: white; }
.btn-success-modern { background: linear-gradient(135deg, var(--success-color), #20c997); color: white; }
.btn-danger-modern { background: linear-gradient(135deg, var(--danger-color), #dc3545); color: white; }
.table-modern { border-radius: 15px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
.table-modern thead th { background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color:white; border:none; font-weight:600; padding: 14px; }
.table-modern tbody td { padding: 12px 14px; border:none; border-bottom: 1px solid #e9ecef; vertical-align: middle; }
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg fixed-top">
        <div class="container">
            <a class="navbar-brand" href="https://monicont.com" target="_blank">
                <img src="{{ url_for('static', filename='img/monicont_logo.png') }}" alt="Logo" style="width: 120px; height: auto;" class="me-3">
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('home') }}">
                            <i class="fas fa-home me-1"></i>{{ _('dashboard') }}
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('devices') }}">
                            <i class="fas fa-microchip me-1"></i>{{ _('devices') }}
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('users') }}">
                            <i class="fas fa-users me-1"></i>{{ _('users_title') }}
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('access_logs') }}">
                            <i class="fas fa-clipboard-list me-1"></i>{{ _('access_logs_title') }}
                        </a>
                    </li>
                </ul>
                
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            {% if user and user['profile_image'] %}
                                {% set imgsrc = user['profile_image'] %}
                                {% if imgsrc and imgsrc[0] == '@' %}
                                  {% set imgfile = imgsrc[1:] %}
                                  <img src="{{ url_for('static', filename='img/' + imgfile) }}?v={{ static_bust }}" class="rounded-circle me-2" width="32" height="32" style="object-fit:cover;">
                                {% else %}
                                  <img src="{{ url_for('static', filename='uploads/' + (imgsrc or '')) }}?v={{ static_bust }}" class="rounded-circle me-2" width="32" height="32" style="object-fit:cover;">
                                {% endif %}
                            {% else %}
                                <img src="{{ url_for('static', filename='img/default-avatar.png') }}?v={{ static_bust }}" class="rounded-circle me-2" width="32" height="32" style="object-fit:cover;">
                            {% endif %}
                            <div class="d-flex flex-column">
                                <span class="fw-bold">{{ user_name }}</span>
                                <small class="text-muted">{{ user and (user['company'] or '') }}</small>
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="{{ url_for('profile') }}"><i class="fas fa-user me-2"></i>{{ _('profile') }}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt me-2"></i>{{ _('logout') }}</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

<div class="main-container">
  <div class="container">
    <div class="card-modern">
      <div class="card-header-modern d-flex justify-content-between align-items-center">
        <h2><i class="fas fa-credit-card me-2"></i>{{ _('cards_on_device') or 'Cards on Device' }} - <code>{{ device_id }}</code></h2>
        <div class="d-flex gap-2">
          <button id="getFromDeviceBtn" class="btn btn-primary-modern btn-modern"><i class="fas fa-download me-1"></i>{{ current_language=='tr' and 'Cihazdan Al' or 'Get from Device' }}</button>
          <button id="syncBtn" class="btn btn-success-modern btn-modern"><i class="fas fa-sync-alt me-1"></i>{{ current_language=='tr' and 'Tüm NFC Kartlarını Gönder' or 'Send All NFC Cards' }}</button>
          <button id="clearBtn" class="btn btn-danger-modern btn-modern"><i class="fas fa-trash me-1"></i>{{ current_language=='tr' and 'Tüm NFC Kartlarını Sil' or 'Delete All NFC Cards' }}</button>
          <a href="{{ url_for('devices') }}" class="btn btn-secondary-modern btn-modern"><i class="fas fa-arrow-left me-1"></i>{{ _('back') }}</a>
        </div>
      </div>
      <div class="card-body-modern">
        <div class="mb-3" id="pushProgress" style="display:none;">
          <div class="d-flex justify-content-between align-items-center mb-1 small">
            <span id="pushProgressText">0%</span>
            <span id="pushProgressDetail"></span>
          </div>
          <div class="progress" style="height: 16px;">
            <div id="pushProgressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
          </div>
        </div>
        <div class="d-flex justify-content-between align-items-center mb-3">
          <span class="badge bg-primary" id="cardCount">{{ cards|length }} {{ _('cards_found') or 'cards found' }}</span>
          <div class="d-flex gap-2 align-items-center">
            <div class="input-group" style="max-width: 320px;">
              <span class="input-group-text"><i class="fas fa-filter"></i></span>
              <input type="text" class="form-control" id="cardFilter" placeholder="{{ _('card_search_placeholder') or 'Search cards...' }}">
            </div>
            <button id="deleteSelectedBtn" class="btn btn-danger-modern btn-modern"><i class="fas fa-trash me-1"></i>{{ current_language=='tr' and 'Seçili Kartları Sil' or 'Delete Selected' }}</button>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table table-modern align-middle" id="cardsTable">
            <thead>
              <tr>
                <th><input type="checkbox" id="selectAllCards"></th>
                <th>{{ _('user_name') or 'User' }}</th>
                <th>{{ _('card_uuid') or 'Card UUID' }}</th>
              </tr>
            </thead>
            <tbody>
              {% for c in cards %}
              <tr>
                <td><input type="checkbox" class="card-select" value="{{ c['card_uuid'] }}"></td>
                <td>{{ c['user_name'] or '' }}</td>
                <td><code class="text-primary">{{ c['card_uuid'] }}</code></td>
              </tr>
              {% else %}
              <tr>
                <td colspan="3" class="text-center text-muted py-4"><i class="fas fa-inbox me-2"></i>{{ _('no_cards_found') or 'No cards found on device.' }}</td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  const cardsTableBody = document.querySelector('#cardsTable tbody');
  const NO_CARDS_TEXT = {{ (_('no_cards_found') or 'No cards found on device.') | tojson | safe }};
  const CARDS_FOUND_TEXT = {{ (_('cards_found') or 'cards found') | tojson | safe }};
  const PROCESSING_TEXT = {{ (_('processing') or 'İşlem Yapılıyor...') | tojson | safe }};
  function reloadRows(cards){
    cardsTableBody.innerHTML = '';
    const countEl = document.getElementById('cardCount');
    if (countEl) { countEl.textContent = `${cards && cards.length ? cards.length : 0} ${CARDS_FOUND_TEXT}`; }
    if (!cards || cards.length === 0){
      const tr = document.createElement('tr');
      tr.innerHTML = '<td colspan="3" class="text-center text-muted py-4"><i class="fas fa-inbox me-2"></i>'+NO_CARDS_TEXT+'</td>';
      cardsTableBody.appendChild(tr);
      return;
    }
    cards.forEach((c, idx)=>{
      const tr = document.createElement('tr');
      tr.innerHTML = `<td><input type="checkbox" class="card-select" value="${(c.card_uuid||'')}"></td>
        <td>${(c.user_name||'')}</td>
        <td><code class="text-primary">${(c.card_uuid||'')}</code></td>`;
      cardsTableBody.appendChild(tr);
    });
  }
  var syncBtn = document.getElementById('syncBtn');
  var getFromDeviceBtn = document.getElementById('getFromDeviceBtn');
  if (getFromDeviceBtn){
    getFromDeviceBtn.addEventListener('click', async function(){
      const btn = this; const orig = btn.innerHTML; btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>'+PROCESSING_TEXT;
      try{
        const r = await fetch('/api/device/{{ device_id }}/cards/sync', {method:'POST'});
        const d = await r.json();
        if(!d.success){ alert(d.message||'Error'); } else { reloadRows(d.cards||[]); }
      }catch(e){ alert(String(e)); }
      finally{ btn.disabled=false; btn.innerHTML=orig; }
    });
  }
  if (syncBtn){
    syncBtn.addEventListener('click', async function(){
      const btn = this; const orig = btn.innerHTML; btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>'+PROCESSING_TEXT;
      try{
        // Send all NFC cards directly using the existing endpoint
        const barWrap = document.getElementById('pushProgress');
        const bar = document.getElementById('pushProgressBar');
        const txt = document.getElementById('pushProgressText');
        const det = document.getElementById('pushProgressDetail');
        barWrap.style.display = '';
        bar.style.width = '0%';
        txt.textContent = '0%';
        det.textContent = '{{ current_language=="tr" and "Gönderiliyor..." or "Sending..." }}';
        
        const rr = await fetch('/api/device/{{ device_id }}/cards/push', {method:'POST'});
        const dd = await rr.json();
        
        bar.style.width = '100%';
        txt.textContent = '100%';
        
        if(!dd.success){
          alert(dd.message||'Error');
        } else {
          const sent = dd.sent || 0;
          det.textContent = sent + ' {{ current_language=="tr" and "kart gönderildi" or "cards sent" }}';
          alert(sent + ' {{ current_language=="tr" and "kart gönderildi" or "cards sent" }}');
        }
      }catch(e){ alert(String(e)); }
      finally{ btn.disabled=false; btn.innerHTML=orig; }
    });
  }
  var clearBtn = document.getElementById('clearBtn');
  if (clearBtn){
    clearBtn.addEventListener('click', async function(){
      if(!confirm('{{ (_('confirm_delete_card_db_only') or 'Bu kart sadece veritabanından silinecek (terminal modu aktif). Devam etmek istiyor musunuz?') | replace("'","\\'") }}')) return;
      const btn = this; const orig = btn.innerHTML; btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>'+PROCESSING_TEXT;
      try{
        const r = await fetch('/api/device/{{ device_id }}/cards/clear', {method:'POST'});
        const d = await r.json();
        if(!d.success){ alert(d.message||'Error'); } else { reloadRows([]); }
      }catch(e){ alert(String(e)); }
      finally{ btn.disabled=false; btn.innerHTML=orig; }
    });
  }
  var filterInput = document.getElementById('cardFilter');
  if (filterInput){
    filterInput.addEventListener('input', function(){
      const term = this.value.trim().toLowerCase();
      const rows = cardsTableBody.querySelectorAll('tr');
      rows.forEach(function(row){
        const text = row.textContent.toLowerCase();
        row.style.display = text.indexOf(term) !== -1 ? '' : 'none';
      });
    });
  }
  function selectedCardUUIDs(){
    return Array.from(document.querySelectorAll('.card-select:checked')).map(cb=>cb.value).filter(Boolean);
  }
  async function deleteCards(uuids){
    try{
      if(!uuids || uuids.length===0){ alert('No cards selected'); return; }
      if(uuids.length>50){ alert('{{ current_language=="tr" and "En fazla 50 kart silebilirsiniz" or "You can delete at most 50 cards" }}'); return; }
      const r = await fetch('/api/device/{{ device_id }}/cards/delete', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({uuids})});
      const d = await r.json();
      if(!d.success){ alert(d.message||'Error'); return; }
      reloadRows(d.cards||[]);
    }catch(e){ alert(String(e)); }
  }
  const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
  if(deleteSelectedBtn){
    deleteSelectedBtn.addEventListener('click', async function(){
      const sel = selectedCardUUIDs();
      if(sel.length===0){ alert('{{ current_language=="tr" and "Seçili kart yok" or "No cards selected" }}'); return; }
      if(!confirm('{{ current_language=="tr" and "Seçili kartlar silinsin mi?" or "Delete selected cards?" }}')) return;
      await deleteCards(sel);
    });
  }
  const selectAll = document.getElementById('selectAllCards');
  if(selectAll){
    selectAll.addEventListener('change', function(){
      const checked = this.checked;
      document.querySelectorAll('.card-select').forEach(cb=>cb.checked=checked);
    });
  }
</script>
</body>
</html> 