<?php header('Content-Type: text/html; charset=UTF-8'); ?>
<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TapTap Card Admin</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #f5f7fa;
    }
    
    .login-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      padding: 20px;
    }
    
    .login-box {
      background: white;
      padding: 40px;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
      width: 100%;
      max-width: 400px;
    }
    
    .login-box h2 { margin-bottom: 30px; color: #333; text-align: center; }
    .form-group { margin-bottom: 20px; }
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: #555;
      font-size: 14px;
    }
    
    input, textarea, select {
      width: 100%;
      padding: 12px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      font-size: 15px;
      transition: border 0.3s;
      font-family: inherit;
    }
    
    input[type="color"] {
      height: 50px;
      padding: 5px;
      cursor: pointer;
    }
    
    input:focus, textarea:focus, select:focus {
      outline: none;
      border-color: #667eea;
    }
    
    textarea { resize: vertical; min-height: 100px; }
    
    .btn {
      width: 100%;
      padding: 14px;
      background: #667eea;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.3s;
    }
    
    .btn:hover { background: #5568d3; }
    .btn-secondary { background: #6b7280; }
    .btn-secondary:hover { background: #4b5563; }
    .btn-danger { background: #ef4444; }
    .btn-danger:hover { background: #dc2626; }
    .btn-success { background: #10b981; }
    .btn-success:hover { background: #059669; }
    .btn-small { width: auto; padding: 8px 16px; font-size: 14px; }
    
    .dashboard {
      max-width: 1600px;
      margin: 0 auto;
      padding: 20px;
    }
    
    .header {
      background: white;
      padding: 20px;
      border-radius: 12px;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .header h1 { color: #333; font-size: 28px; }
    
    .header-actions {
      display: flex;
      gap: 10px;
      align-items: center;
    }
    
    .role-badge {
      background: #667eea;
      color: white;
      padding: 6px 14px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 600;
      text-transform: uppercase;
    }
    
    .tabs {
      background: white;
      padding: 0 20px;
      border-radius: 12px;
      margin-bottom: 20px;
      display: flex;
      gap: 5px;
    }
    
    .tab {
      padding: 16px 24px;
      cursor: pointer;
      border-bottom: 3px solid transparent;
      transition: all 0.3s;
      font-weight: 500;
      color: #6b7280;
    }
    
    .tab:hover { color: #667eea; }
    .tab.active { color: #667eea; border-bottom-color: #667eea; }
    
    .tab-content {
      display: none;
      background: white;
      padding: 30px;
      border-radius: 12px;
    }
    
    .tab-content.active { display: block; }
    
    .filters {
      display: flex;
      gap: 15px;
      margin-bottom: 20px;
      flex-wrap: wrap;
      align-items: flex-end;
    }
    
    .filter-item {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }
    
    .filter-item label {
      font-size: 12px;
      color: #6b7280;
      margin-bottom: 0;
    }
    
    .filter-item input,
    .filter-item select {
      min-width: 150px;
      padding: 8px 12px;
      font-size: 14px;
    }
    
    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    
    .search-box {
      position: relative;
      width: 300px;
    }
    
    .search-box input {
      width: 100%;
      padding: 10px 10px 10px 35px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
    }
    
    .search-icon {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      color: #9ca3af;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
    }
    
    th {
      background: #f9fafb;
      padding: 14px;
      text-align: left;
      font-weight: 600;
      color: #374151;
      border-bottom: 2px solid #e5e7eb;
      white-space: nowrap;
    }
    
    th.sortable {
      cursor: pointer;
      user-select: none;
    }
    
    th.sortable:hover {
      background: #f3f4f6;
    }
    
    th.sortable.asc::after {
      content: ' ?-?';
      font-size: 10px;
      color: #667eea;
    }
    
    th.sortable.desc::after {
      content: ' ?- 1/4 ';
      font-size: 10px;
      color: #667eea;
    }
    
    td {
      padding: 14px;
      border-bottom: 1px solid #f3f4f6;
      color: #374151;
    }
    
    tr:hover {
      background: #f9fafb;
    }
    
    .status-badge {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 600;
    }
    
    .status-active { background: #d1fae5; color: #065f46; }
    .status-inactive { background: #fee2e2; color: #991b1b; }
    .status-lifetime { background: #dbeafe; color: #1e40af; }
    .status-expiring { background: #fef3c7; color: #92400e; }
    
    .package-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 6px;
      font-size: 11px;
      font-weight: 700;
      text-transform: uppercase;
    }
    
    .package-basic { background: #e5e7eb; color: #374151; }
    .package-pro { background: #dbeafe; color: #1e40af; }
    .package-premium { background: #fce7f3; color: #9f1239; }
    .package-lifetime { background: #fef3c7; color: #92400e; }
    
    .action-btn {
      background: none;
      border: none;
      cursor: pointer;
      font-size: 18px;
      padding: 4px 8px;
      transition: transform 0.2s;
    }
    
    .action-btn:hover {
      transform: scale(1.2);
    }
    
    .pagination {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 2px solid #f3f4f6;
    }
    
    .pagination-info {
      color: #6b7280;
      font-size: 14px;
    }
    
    .pagination-btns {
      display: flex;
      gap: 10px;
    }
    
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      z-index: 1000;
      overflow-y: auto;
      padding: 20px;
    }
    
    .modal.show {
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding-top: 40px;
    }
    
    .modal-content {
      background: white;
      padding: 30px;
      border-radius: 12px;
      width: 100%;
      max-width: 800px;
      max-height: calc(100vh - 80px);
      overflow-y: auto;
    }
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
    }
    
    .modal-header h2 {
      color: #333;
      font-size: 24px;
    }
    
    .close-btn {
      background: none;
      border: none;
      font-size: 28px;
      cursor: pointer;
      color: #9ca3af;
      line-height: 1;
    }
    
    .close-btn:hover {
      color: #374151;
    }
    
    .section {
      margin-bottom: 25px;
      padding-bottom: 25px;
      border-bottom: 1px solid #f3f4f6;
    }
    
    .section:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #374151;
      margin-bottom: 15px;
    }
    
    .grid-2 {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
    }
    
    .link-item {
      display: flex;
      gap: 10px;
      align-items: flex-end;
      margin-bottom: 10px;
    }
    
    .link-item select {
      flex: 1;
    }
    
    .link-item input {
      flex: 2;
    }
    
    .module-item {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 10px;
      background: #f9fafb;
      border-radius: 8px;
      margin-bottom: 10px;
    }
    
    .module-item input[type="checkbox"] {
      width: auto;
      cursor: pointer;
    }
    
    .module-item label {
      flex: 1;
      margin: 0;
      cursor: pointer;
      font-weight: 500;
    }
    
    .module-config {
      display: none;
      margin-left: 30px;
      padding: 15px;
      background: white;
      border-left: 3px solid #667eea;
      border-radius: 4px;
      margin-top: 10px;
    }
    
    .module-config.show {
      display: block;
    }
    
    .error-message {
      background: #fee2e2;
      color: #991b1b;
      padding: 12px;
      border-radius: 8px;
      margin-bottom: 15px;
      border-left: 4px solid #ef4444;
    }
    
    .success-message {
      background: #d1fae5;
      color: #065f46;
      padding: 12px;
      border-radius: 8px;
      margin-bottom: 15px;
      border-left: 4px solid #10b981;
    }
    
    .role-manager {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 20px;
    }
    
    .role-card {
      border: 2px solid #e5e7eb;
      border-radius: 12px;
      padding: 20px;
    }
    
    .role-card h3 {
      margin-bottom: 15px;
      color: #374151;
      font-size: 18px;
      text-transform: uppercase;
    }
    
    .permission-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f3f4f6;
    }
    
    .permission-item:last-child {
      border-bottom: none;
    }
    
    .permission-name {
      font-size: 13px;
      color: #6b7280;
    }
    
    .toggle-switch {
      position: relative;
      width: 50px;
      height: 24px;
      background: #e5e7eb;
      border-radius: 12px;
      cursor: pointer;
      transition: background 0.3s;
    }
    
    .toggle-switch.active {
      background: #10b981;
    }
    
    .toggle-switch::after {
      content: '';
      position: absolute;
      width: 20px;
      height: 20px;
      background: white;
      border-radius: 50%;
      top: 2px;
      left: 2px;
      transition: left 0.3s;
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    
    .toggle-switch.active::after {
      left: 28px;
    }
    
    @media (max-width: 768px) {
      .grid-2 {
        grid-template-columns: 1fr;
      }
      
      .header {
        flex-direction: column;
        gap: 15px;
      }
      
      .toolbar {
        flex-direction: column;
        align-items: stretch;
      }
      
      .search-box {
        width: 100%;
      }
      
      .filters {
        flex-direction: column;
      }
      
      .filter-item input,
      .filter-item select {
        width: 100%;
      }
      
      table {
        font-size: 13px;
      }
      
      th, td {
        padding: 8px;
      }
    }
  </style>
</head>
<body>

  <div id="loginView" class="login-container">
    <div class="login-box">
      <h2> TapTap Card Admin</h2>
      <div id="loginError" class="error-message" style="display: none;"></div>
      <div class="form-group">
        <label>Username / Email</label>
        <input type="text" id="loginUsername" placeholder="admin">
      </div>
      <div class="form-group">
        <label>Lozinka</label>
        <input type="password" id="loginPassword" placeholder="?EUR??EUR??EUR??EUR??EUR??EUR??EUR??EUR?">
      </div>
      <div class="form-group">
        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
          <input type="checkbox" id="rememberMe" style="width: auto;">
          <span style="font-weight: normal;">Zapamti me</span>
        </label>
      </div>
      <button type="button" class="btn" id="loginBtn">Prijava</button>
      <div style="text-align: center; margin-top: 15px;">
        <a href="#" onclick="showPasswordReset(); return false;" style="color: #667eea; text-decoration: none; font-size: 14px;">Zaboravili ste lozinku?</a>
      </div>
    </div>
  </div>

  <div id="dashboardView" class="dashboard" style="display: none;">
    <div class="header">
      <h1> TapTap Card Admin</h1>
      <div class="header-actions">
        <span class="role-badge" id="userRoleBadge"></span>
        <button class="btn btn-secondary btn-small" onclick="handleExport()">??"? Export</button>
        <button class="btn btn-secondary btn-small" onclick="document.getElementById('importFile').click()">??"? Import</button>
        <input type="file" id="importFile" accept=".json" style="display: none;" onchange="handleImport(event)">
        <button class="btn btn-danger btn-small" onclick="handleLogout()">Odjava</button>
      </div>
    </div>

    <div class="tabs">
      <div class="tab active" onclick="showTab('users')">Korisnici</div>
      <div class="tab" id="roleManagerTab" onclick="showTab('roles')" style="display: none;">Role Manager</div>
      <div class="tab" id="accountsTab" onclick="showTab('accounts')" style="display: none;">Accounti</div>
      <div class="tab" onclick="showTab('settings')">Settings</div>
      <div class="tab" id="brandingTab" onclick="showTab('branding')" style="display: none;">Branding</div>
    </div>

    <div id="users-tab" class="tab-content active">
      <div class="filters">
        <div class="filter-item">
          <label>??"? Pretraga</label>
          <input type="text" id="searchInput" placeholder="Ime, slug, email..." onkeyup="filterUsers()">
        </div>
        <div class="filter-item">
          <label>??"... Datum od</label>
          <input type="date" id="dateFrom" onchange="filterUsers()">
        </div>
        <div class="filter-item">
          <label>??"... Datum do</label>
          <input type="date" id="dateTo" onchange="filterUsers()">
        </div>
        <div class="filter-item" id="statusFilterContainer">
          <label>Status</label>
          <select id="filterStatus" onchange="filterUsers()">
            <option value="">Svi</option>
            <option value="active">Aktivan</option>
            <option value="inactive">Neaktivan</option>
            <option value="lifetime">Lifetime</option>
            <option value="expiring">Isti??e uskoro</option>
          </select>
        </div>
        <div class="filter-item" id="packageFilterContainer">
          <label>Paket</label>
          <select id="filterPackage" onchange="filterUsers()">
            <option value="">Svi</option>
            <option value="basic">Basic</option>
            <option value="pro">Pro</option>
            <option value="premium">Premium</option>
            <option value="lifetime">Lifetime</option>
          </select>
        </div>
        <div class="filter-item" id="resellerFilterContainer" style="display: none;">
          <label>Reseller</label>
          <select id="filterReseller" onchange="filterUsers()">
            <option value="">Svi</option>
          </select>
        </div>
      </div>
      
      <div class="toolbar">
        <div style="font-size: 14px; color: #6b7280;">
          <span id="statsText"></span>
        </div>
        <button class="btn btn-success btn-small" onclick="openCreateModal()">+ Novi korisnik</button>
      </div>

      <table>
        <thead>
          <tr>
            <th class="sortable" onclick="sortTable('id')">ID</th>
            <th class="sortable" onclick="sortTable('name')">Ime i prezime</th>
            <th class="sortable" onclick="sortTable('slug')">Slug</th>
            <th class="sortable" onclick="sortTable('email')">Email</th>
            <th>Status</th>
            <th>Paket</th>
            <th>Analitika</th>
            <th>Login</th>
            <th id="createdByColumn" style="display: none;">Kreirao</th>
            <th class="sortable" onclick="sortTable('created')">Kreirano</th>
            <th>Akcije</th>
          </tr>
        </thead>
        <tbody id="usersTableBody"></tbody>
      </table>

      <div class="pagination">
        <div class="pagination-info" id="paginationInfo"></div>
        <div class="pagination-btns">
          <button class="btn btn-small btn-secondary" id="prevBtn" onclick="prevPage()">?EUR? Prethodna</button>
          <button class="btn btn-small btn-secondary" id="nextBtn" onclick="nextPage()">Sljede??a ?EUR?</button>
        </div>
      </div>
    </div>

    <div id="roles-tab" class="tab-content">
      <h2 style="margin-bottom: 20px;">Role & Permissions Manager</h2>
      <div id="roleManagerGrid" class="role-manager">
        <p>U??itavam...</p>
      </div>
    </div>

    <div id="accounts-tab" class="tab-content">
      <div class="toolbar">
        <h2>Admin Accounti</h2>
        <div style="display: flex; gap: 10px;">
          <button class="btn btn-success btn-small" onclick="openCreateResellerModal()">+ Novi Reseller</button>
          <button class="btn btn-success btn-small" onclick="openCreateAdminModal()">+ Novi Admin</button>
        </div>
      </div>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Role</th>
            <th>Kreirano</th>
            <th>Akcije</th>
          </tr>
        </thead>
        <tbody id="accountsTableBody">
          <tr><td colspan="5" style="text-align: center;">U??itavam...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="settings-tab" class="tab-content">
      <div class="section">
        <div class="section-title">??"-- Analitika Login Link</div>
        <div class="form-group">
          <label>Slug za analitiku</label>
          <input type="text" id="settingAnalyticsSlug" placeholder="analitika">
          <p style="color: #6b7280; font-size: 13px; margin-top: 8px;">
            Link: /<strong id="previewSlug">analitika</strong><br>
            URL: <a href="/analitika" target="_blank" style="color: #667eea;">card.taptap.ba/<span id="previewSlug2">analitika</span></a>
          </p>
        </div>
        <button class="btn btn-small" onclick="saveSettings()">??' 3/4  Spremi postavke</button>
      </div>
    </div>

    <div id="branding-tab" class="tab-content">
      <div class="section">
        <div class="section-title">Branding Postavke</div>
        <p style="color: #6b7280; margin-bottom: 20px;">Prilagodi izgled sustava</p>
        
        <div style="max-width: 600px;">
          <form id="brandingForm">
            <div class="form-group">
              <label>Logo</label>
              <input type="file" id="brandLogo" accept="image/*">
              <div id="logoPreview" style="margin-top: 15px;"></div>
            </div>
            
            <div class="form-group">
              <label>Ime branda</label>
              <input type="text" id="brandName" placeholder="TapTap Card">
            </div>
            
            <div class="grid-2">
              <div class="form-group">
                <label>Glavna boja</label>
                <input type="color" id="primaryColor" value="#667eea">
                <input type="text" id="primaryColorText" readonly style="margin-top: 8px; font-family: monospace; font-size: 13px; background: #f9fafb;">
              </div>
              <div class="form-group">
                <label>Sekundarna boja</label>
                <input type="color" id="secondaryColor" value="#764ba2">
                <input type="text" id="secondaryColorText" readonly style="margin-top: 8px; font-family: monospace; font-size: 13px; background: #f9fafb;">
              </div>
            </div>
            
            <div class="form-group">
              <div style="padding: 20px; background: linear-gradient(135deg, var(--primary, #667eea) 0%, var(--secondary, #764ba2) 100%); border-radius: 12px; color: white; text-align: center; font-weight: 600;" id="brandPreview">
                Preview
              </div>
            </div>
            
            <button type="submit" class="btn">Spremi branding</button>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- USER MODAL -->
  <div id="userModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="modalTitle">Novi korisnik</h2>
        <button class="close-btn" onclick="closeModal()">&times;</button>
      </div>
      <div id="modalError" class="error-message" style="display: none;"></div>
      
      <form id="userForm" onsubmit="handleSubmit(event)">
        <input type="hidden" id="userId">
        
        <div class="section">
          <div class="section-title">??'? Osnovni podaci</div>
          <div class="grid-2">
            <div class="form-group">
              <label>Ime *</label>
              <input type="text" id="ime" required>
            </div>
            <div class="form-group">
              <label>Prezime *</label>
              <input type="text" id="prezime" required>
            </div>
          </div>
          <div class="form-group">
            <label>Slug (URL) *</label>
            <input type="text" id="slug" required placeholder="npr. zmadzar">
            <p style="color: #9ca3af; font-size: 13px; margin-top: 5px;">
              URL: card.taptap.ba/<strong id="slugPreview">slug</strong>
            </p>
          </div>
          <div class="form-group">
            <label>Opis</label>
            <textarea id="opis"></textarea>
          </div>
        </div>

        <div class="section">
          <div class="section-title">??"? Kontakt</div>
          <div class="grid-2">
            <div class="form-group">
              <label>Email</label>
              <input type="email" id="email">
            </div>
            <div class="form-group">
              <label>Telefon</label>
              <input type="tel" id="telefon">
            </div>
          </div>
          <div class="grid-2">
            <div class="form-group">
              <label>WhatsApp</label>
              <input type="tel" id="whatsapp">
            </div>
            <div class="form-group">
              <label>Viber</label>
              <input type="tel" id="viber">
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">???? Dizajn</div>
          <div class="form-group">
            <label>Profilna slika</label>
            <input type="file" id="slika" accept="image/*">
          </div>
          <div class="form-group">
            <label>Background slika</label>
            <input type="file" id="background_image" accept="image/*">
          </div>
          <div class="form-group">
            <label>Accent boja</label>
            <input type="color" id="accent_color" value="#3b82f6">
          </div>
        </div>

        <div class="section">
          <div class="section-title">??"-- Dru??tveni linkovi</div>
          <div id="socialLinksContainer"></div>
          <button type="button" class="btn btn-secondary btn-small" onclick="addSocialLink()">+ Dodaj link</button>
        </div>

        <div class="section">
          <div class="section-title">???(C) Moduli</div>
          
          <div class="module-item">
            <input type="checkbox" id="module_vcard" onchange="toggleModuleConfig('vcard')">
            <label for="module_vcard">vCard Download</label>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_qr_code" onchange="toggleModuleConfig('qr_code')">
            <label for="module_qr_code">QR Code</label>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_mapa" onchange="toggleModuleConfig('mapa')">
            <label for="module_mapa">Google Maps</label>
          </div>
          <div class="module-config" id="config_mapa">
            <div class="form-group">
              <label>Google Maps Link ili Adresa</label>
              <input type="text" id="mapa_link" placeholder="https://maps.app.goo.gl/... ili 'Ljubu??ki, BiH'">
            </div>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_instagram_feed" onchange="toggleModuleConfig('instagram_feed')">
            <label for="module_instagram_feed">Instagram Feed</label>
          </div>
          <div class="module-config" id="config_instagram_feed">
            <div class="form-group">
              <label>Instagram Username</label>
              <input type="text" id="instagram_username" placeholder="Bez @, npr: zvonimirmadzar">
            </div>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_text_block" onchange="toggleModuleConfig('text_block')">
            <label for="module_text_block">Tekstualni Blok</label>
          </div>
          <div class="module-config" id="config_text_block">
            <div class="form-group">
              <label>Sadr? 3/4 aj</label>
              <textarea id="text_block_content" placeholder="Unesi tekst koji ? 3/4 eli?? prikazati..."></textarea>
            </div>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_google_reviews" onchange="toggleModuleConfig('google_reviews')">
            <label for="module_google_reviews">Google Reviews</label>
          </div>
          <div class="module-config" id="config_google_reviews">
            <div class="form-group">
              <label>Google Reviews Link</label>
              <input type="url" id="google_reviews_link" placeholder="https://g.page/...">
            </div>
          </div>

          <div class="module-item">
            <input type="checkbox" id="module_working_hours" onchange="toggleModuleConfig('working_hours')">
            <label for="module_working_hours">Radno Vrijeme</label>
          </div>
          <div class="module-config" id="config_working_hours">
            <div class="form-group">
              <label>Tip</label>
              <select id="working_hours_type" onchange="toggleWorkingHoursFields()">
                <option value="">Odaberi...</option>
                <option value="all">Svi dani isto</option>
                <option value="individual">Pojedina??no</option>
              </select>
            </div>
            <div id="wh_all_days" style="display: none;">
              <div class="form-group">
                <label>Radno vrijeme</label>
                <input type="text" id="working_hours_all" placeholder="npr. 08:00 - 20:00">
              </div>
            </div>
            <div id="wh_individual" style="display: none;">
              <div class="form-group">
                <label>Radni dani (Pon-Pet)</label>
                <input type="text" id="working_hours_weekday" placeholder="npr. 08:00 - 20:00">
              </div>
              <div class="form-group">
                <label>Subota</label>
                <input type="text" id="working_hours_saturday" placeholder="npr. 09:00 - 15:00">
              </div>
              <div class="form-group">
                <label>Nedjelja</label>
                <input type="text" id="working_hours_sunday" placeholder="Zatvoreno ili 10:00 - 14:00">
              </div>
            </div>
          </div>
        </div>

        <div class="section" id="packageSection">
          <div class="section-title">??"? Paket i Status</div>
          <div class="form-group">
            <label>Paket</label>
            <select id="package">
              <option value="basic">Basic</option>
              <option value="pro">Pro</option>
              <option value="premium">Premium</option>
              <option value="lifetime">Lifetime</option>
            </select>
          </div>
          <div class="form-group">
            <label style="display: flex; align-items: center; gap: 8px;">
              <input type="checkbox" id="active" checked>
              <span>Aktivan</span>
            </label>
          </div>
          <div class="grid-2">
            <div class="form-group">
              <label>Datum aktivacije (opciono)</label>
              <input type="date" id="active_from">
            </div>
            <div class="form-group">
              <label>Aktivan do (prazno = lifetime)</label>
              <input type="date" id="active_until">
              <button type="button" onclick="document.getElementById('active_until').value='';" class="btn btn-secondary btn-small" style="margin-top: 8px;">
                Ukloni datum
              </button>
            </div>
          </div>
        </div>
        
        <div style="display: flex; gap: 10px; margin-top: 30px;">
          <button type="submit" class="btn">??' 3/4  Spremi</button>
          <button type="button" class="btn btn-secondary" onclick="closeModal()">Odustani</button>
        </div>
      </form>
    </div>
  </div>

  <!-- RESELLER MODAL -->
  <div id="resellerModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
      <div class="modal-header">
        <h2>Novi Reseller</h2>
        <button class="close-btn" onclick="closeResellerModal()">&times;</button>
      </div>
      <form id="resellerForm" onsubmit="handleResellerSubmit(event)">
        <div class="form-group">
          <label>Username *</label>
          <input type="text" name="username" required minlength="3">
        </div>
        <div class="form-group">
          <label>Lozinka *</label>
          <input type="password" name="password" required minlength="6">
        </div>
        <div style="display: flex; gap: 10px;">
          <button type="submit" class="btn">Kreiraj</button>
          <button type="button" class="btn btn-secondary" onclick="closeResellerModal()">Odustani</button>
        </div>
      </form>
    </div>
  </div>

  <!-- ADMIN MODAL -->
  <div id="adminModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
      <div class="modal-header">
        <h2>Novi Admin</h2>
        <button class="close-btn" onclick="closeAdminModal()">&times;</button>
      </div>
      <form id="adminForm" onsubmit="handleAdminSubmit(event)">
        <div class="form-group">
          <label>Username *</label>
          <input type="text" name="username" required minlength="3">
        </div>
        <div class="form-group">
          <label>Lozinka *</label>
          <input type="password" name="password" required minlength="6">
        </div>
        <div style="display: flex; gap: 10px;">
          <button type="submit" class="btn">Kreiraj</button>
          <button type="button" class="btn btn-secondary" onclick="closeAdminModal()">Odustani</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    let currentToken = null;
    let currentUserRole = null;
    let editingUserId = null;
    let linkCounter = 0;
    let allUsers = [];
    let filteredUsers = [];
    let currentPage = 1;
    const perPage = 50;
    let sortColumn = null;
    let sortDirection = 'asc';

    checkAuth();
    
    function checkAuth() {
      currentToken = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      if (currentToken) {
        // Decode token to get role
        try {
          const payload = JSON.parse(atob(currentToken.split('.')[1]));
          const accountInfo = payload.id.split(':');
          currentUserRole = localStorage.getItem('userRole') || sessionStorage.getItem('userRole') || 'admin';
          
          document.getElementById('loginView').style.display = 'none';
          document.getElementById('dashboardView').style.display = 'block';
          document.getElementById('userRoleBadge').textContent = currentUserRole.toUpperCase();
          
          // Show/hide tabs based on role
          if (currentUserRole === 'super_admin') {
            document.getElementById('roleManagerTab').style.display = 'block';
            document.getElementById('brandingTab').style.display = 'block';
            document.getElementById('accountsTab').style.display = 'block';
            document.getElementById('resellerFilterContainer').style.display = 'block';
            document.getElementById('createdByColumn').style.display = 'table-cell';
          } else if (currentUserRole === 'admin') {
            document.getElementById('accountsTab').style.display = 'block';
            document.getElementById('createdByColumn').style.display = 'table-cell';
          } else if (currentUserRole === 'reseller') {
            // Reseller samo vidi svoje
          } else if (currentUserRole === 'user') {
            // Redirect to user panel
            window.location.href = 'user-panel.php';
            return;
          }
          
          loadUsers();
        } catch(e) {
          handleLogout();
        }
      } else {
        document.getElementById('loginView').style.display = 'flex';
        document.getElementById('dashboardView').style.display = 'none';
      }
    }

    function showTab(tabName) {
      document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
      event.target.classList.add('active');
      
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
      document.getElementById(`${tabName}-tab`).classList.add('active');
      
      if (tabName === 'settings') {
        loadSettings();
      } else if (tabName === 'roles') {
        loadRoles();
      } else if (tabName === 'accounts') {
        loadAccounts();
      } else if (tabName === 'branding') {
        loadBrandingSettings();
      }
    }

    async function handleLogin() {
      const username = document.getElementById('loginUsername').value;
      const password = document.getElementById('loginPassword').value;
      const rememberMe = document.getElementById('rememberMe').checked;
      
      try {
        const response = await fetch('/api.php/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password, remember: rememberMe })
        });
        
        const data = await response.json();
        
        if (response.ok) {
          if (rememberMe) {
            localStorage.setItem('token', data.token);
            localStorage.setItem('userRole', data.role);
          } else {
            sessionStorage.setItem('token', data.token);
            sessionStorage.setItem('userRole', data.role);
          }
          checkAuth();
        } else {
          document.getElementById('loginError').textContent = data.error || 'Pogre??ni podaci';
          document.getElementById('loginError').style.display = 'block';
        }
      } catch (error) {
        document.getElementById('loginError').textContent = 'Gre??ka pri povezivanju';
        document.getElementById('loginError').style.display = 'block';
      }
    }
    
    function showPasswordReset() {
      const email = prompt('Unesite va?? email:');
      
      if (!email || !email.includes('@')) {
        alert('Neva? 3/4 e??i email');
        return;
      }
      
      fetch('/api.php/auth/request-reset', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email })
      })
      .then(r => r.json())
      .then(data => {
        alert('?oe... ' + data.message + '\n\nProvjerite email za reset link.');
      })
      .catch(() => {
        alert('??OE Gre??ka pri slanju');
      });
    }

    // Check za reset token u URL-u
    window.addEventListener('DOMContentLoaded', () => {
      const urlParams = new URLSearchParams(window.location.search);
      const resetToken = urlParams.get('reset');
      
      if (resetToken) {
        const newPass = prompt('Unesite novu lozinku (minimalno 6 znakova):');
        
        if (!newPass || newPass.length < 6) {
          alert('??OE Lozinka mora imati minimalno 6 znakova');
          return;
        }
        
        fetch('/api.php/auth/reset-password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token: resetToken, password: newPass })
        })
        .then(r => r.json())
        .then(data => {
          if (data.message) {
            alert('?oe... ' + data.message);
            window.location.href = '/admin.php';
          } else {
            alert('??OE ' + (data.error || 'Gre??ka'));
          }
        });
      }
      
      // Slug preview update
      document.getElementById('slug')?.addEventListener('input', (e) => {
        document.getElementById('slugPreview').textContent = e.target.value || 'slug';
      });
    });

    function handleLogout() {
      localStorage.removeItem('token');
      localStorage.removeItem('userRole');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('userRole');
      currentToken = null;
      currentUserRole = null;
      checkAuth();
    }

    async function loadUsers() {
      try {
        const response = await fetch('/api.php/users', {
          headers: { 'Authorization': 'Bearer ' + currentToken }
        });
        
        if (response.status === 401) {
          handleLogout();
          return;
        }
        
        allUsers = await response.json();
        filteredUsers = [...allUsers];
        currentPage = 1;
        renderUsers();
        updateStats();
      } catch (error) {
        console.error('Gre??ka:', error);
      }
    }

    function updateStats() {
      const active = filteredUsers.filter(u => u.active).length;
      const total = filteredUsers.length;
      document.getElementById('statsText').textContent = 
        `Prikazano ${filteredUsers.length} od ${allUsers.length} korisnika ?EUR? ${active} aktivnih`;
    }

    function sortTable(column) {
      if (sortColumn === column) {
        sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        sortColumn = column;
        sortDirection = 'asc';
      }
      
      // Remove previous sort indicators
      document.querySelectorAll('th.sortable').forEach(th => {
        th.classList.remove('asc', 'desc');
      });
      
      // Add current sort indicator
      event.target.classList.add(sortDirection);
      
      filteredUsers.sort((a, b) => {
        let valA, valB;
        
        switch(column) {
          case 'id':
            valA = a.id;
            valB = b.id;
            break;
          case 'name':
            valA = (a.ime + ' ' + a.prezime).toLowerCase();
            valB = (b.ime + ' ' + b.prezime).toLowerCase();
            break;
          case 'slug':
            valA = a.slug.toLowerCase();
            valB = b.slug.toLowerCase();
            break;
          case 'email':
            valA = (a.email || '').toLowerCase();
            valB = (b.email || '').toLowerCase();
            break;
          case 'created':
            valA = new Date(a.created_at);
            valB = new Date(b.created_at);
            break;
          default:
            return 0;
        }
        
        if (valA < valB) return sortDirection === 'asc' ? -1 : 1;
        if (valA > valB) return sortDirection === 'asc' ? 1 : -1;
        return 0;
      });
      
      renderUsers();
    }

    function renderUsers() {
      const tbody = document.getElementById('usersTableBody');
      tbody.innerHTML = '';
      const start = (currentPage - 1) * perPage;
      const end = start + perPage;
      const pageUsers = filteredUsers.slice(start, end);
      
      if (pageUsers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="11" style="text-align: center; padding: 40px; color: #9ca3af;">Nema korisnika</td></tr>';
        return;
      }
      
      pageUsers.forEach(user => {
        const status = getStatusBadge(user);
        const packageBadge = user.package ? 
          `<span class="package-badge package-${user.package}">${user.package.toUpperCase()}</span>` :
          '<span class="package-badge package-basic">BASIC</span>';
        const hasLogin = user.has_login ? '?oe...' : '??OE';
        const createdBy = currentUserRole !== 'reseller' ? 
          `<td>${user.created_by_name || '-'}</td>` : '';
        
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${user.id}</td>
          <td>${user.ime} ${user.prezime}</td>
          <td><a href="/${user.slug}" target="_blank" style="color: #667eea;">${user.slug}</a></td>
          <td>${user.email || '-'}</td>
          <td>${status}</td>
          <td>${packageBadge}</td>
          <td><a href="/analytics-view.php?user=${user.id}" target="_blank">??"?</a></td>
          <td>${hasLogin}</td>
          ${createdBy}
          <td>${formatDate(user.created_at)}</td>
          <td>
            <button class="action-btn" onclick="editUser(${user.id})" title="Uredi">?oe??,?</button>
            <button class="action-btn" onclick="deleteUser(${user.id})" title="Obri??i">??--'?,?</button>
          </td>
        `;
        tbody.appendChild(row);
      });
      
      updatePagination();
    }

    function getStatusBadge(user) {
      if (!user.active) return '<span class="status-badge status-inactive">Neaktivan</span>';
      if (!user.active_until) return '<span class="status-badge status-lifetime">Lifetime</span>';
      
      const until = new Date(user.active_until);
      const now = new Date();
      const daysLeft = Math.floor((until - now) / (1000 * 60 * 60 * 24));
      
      if (daysLeft < 0) return '<span class="status-badge status-inactive">Istekao</span>';
      if (daysLeft < 30) return `<span class="status-badge status-expiring">Isti??e (${daysLeft}d)</span>`;
      return '<span class="status-badge status-active">Aktivan</span>';
    }

    function updatePagination() {
      const total = filteredUsers.length;
      const showing = Math.min(currentPage * perPage, total);
      const from = total > 0 ? (currentPage - 1) * perPage + 1 : 0;
      
      document.getElementById('paginationInfo').textContent = 
        `${from}-${showing} od ${total}`;
      
      document.getElementById('prevBtn').disabled = currentPage === 1;
      document.getElementById('nextBtn').disabled = showing >= total;
    }

    function prevPage() {
      if (currentPage > 1) {
        currentPage--;
        renderUsers();
      }
    }

    function nextPage() {
      const total = filteredUsers.length;
      const maxPage = Math.ceil(total / perPage);
      if (currentPage < maxPage) {
        currentPage++;
        renderUsers();
      }
    }

    function formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleDateString('hr-HR');
    }

    function filterUsers() {
      const search = document.getElementById('searchInput').value.toLowerCase();
      const dateFrom = document.getElementById('dateFrom').value;
      const dateTo = document.getElementById('dateTo').value;
      const status = document.getElementById('filterStatus').value;
      const packageFilter = document.getElementById('filterPackage').value;
      const resellerFilter = document.getElementById('filterReseller')?.value || '';
      
      filteredUsers = allUsers.filter(user => {
        const matchesSearch = !search || 
          (user.ime + ' ' + user.prezime).toLowerCase().includes(search) ||
          user.slug.toLowerCase().includes(search) ||
          (user.email && user.email.toLowerCase().includes(search));
        
        const userDate = new Date(user.created_at).toISOString().split('T')[0];
        const matchesDateFrom = !dateFrom || userDate >= dateFrom;
        const matchesDateTo = !dateTo || userDate <= dateTo;
        
        let matchesStatus = true;
        if (status === 'active') matchesStatus = user.active && user.active_until;
        if (status === 'inactive') matchesStatus = !user.active;
        if (status === 'lifetime') matchesStatus = user.active && !user.active_until;
        if (status === 'expiring') {
          if (user.active_until) {
            const daysLeft = Math.floor((new Date(user.active_until) - new Date()) / (1000 * 60 * 60 * 24));
            matchesStatus = daysLeft >= 0 && daysLeft < 30;
          } else {
            matchesStatus = false;
          }
        }
        
        const matchesPackage = !packageFilter || user.package === packageFilter;
        const matchesReseller = !resellerFilter || user.created_by == resellerFilter;
        
        return matchesSearch && matchesDateFrom && matchesDateTo && matchesStatus && matchesPackage && matchesReseller;
      });
      
      currentPage = 1;
      renderUsers();
      updateStats();
    }

    // MODALS
    function openCreateModal() {
      editingUserId = null;
      document.getElementById('modalTitle').textContent = 'Novi korisnik';
      document.getElementById('userForm').reset();
      document.getElementById('userId').value = '';
      linkCounter = 0;
      document.getElementById('socialLinksContainer').innerHTML = '';
      
      // Show package section for admin/super_admin
      if (currentUserRole === 'super_admin' || currentUserRole === 'admin') {
        document.getElementById('packageSection').style.display = 'block';
      } else {
        document.getElementById('packageSection').style.display = 'none';
      }
      
      addSocialLink();
      document.getElementById('userModal').classList.add('show');
    }

    function closeModal() {
      document.getElementById('userModal').classList.remove('show');
    }

    function addSocialLink() {
      const container = document.getElementById('socialLinksContainer');
      const linkId = 'link_' + linkCounter++;
      
      const div = document.createElement('div');
      div.className = 'link-item';
      div.id = linkId;
      div.innerHTML = `
        <select>
          <option value="">Tip...</option>
          <option value="website">??OE? Website</option>
          <option value="facebook">??"~ Facebook</option>
          <option value="instagram">??", Instagram</option>
          <option value="linkedin">??' 1/4  LinkedIn</option>
          <option value="twitter">???? Twitter</option>
          <option value="youtube">??"? YouTube</option>
          <option value="tiktok">???u TikTok</option>
          <option value="custom">??"-- Custom</option>
        </select>
        <input type="url" placeholder="URL...">
        <button type="button" class="btn btn-danger btn-small" onclick="removeSocialLink('${linkId}')">?oe-</button>
      `;
      
      container.appendChild(div);
    }

    function removeSocialLink(linkId) {
      document.getElementById(linkId).remove();
    }

    function toggleModuleConfig(moduleName) {
      const checkbox = document.getElementById('module_' + moduleName);
      const config = document.getElementById('config_' + moduleName);
      
      if (config) {
        config.classList.toggle('show', checkbox.checked);
      }
    }

    function toggleWorkingHoursFields() {
      const type = document.getElementById('working_hours_type').value;
      document.getElementById('wh_all_days').style.display = type === 'all' ? 'block' : 'none';
      document.getElementById('wh_individual').style.display = type === 'individual' ? 'block' : 'none';
    }

    async function handleSubmit(e) {
      e.preventDefault();
      
      const formData = new FormData();
      
      if (editingUserId) {
        formData.append('_method', 'PUT');
        formData.append('user_id', editingUserId);
      }
      
      formData.append('slug', document.getElementById('slug').value);
      formData.append('ime', document.getElementById('ime').value);
      formData.append('prezime', document.getElementById('prezime').value);
      formData.append('opis', document.getElementById('opis').value);
      formData.append('email', document.getElementById('email').value);
      formData.append('telefon', document.getElementById('telefon').value);
      formData.append('whatsapp', document.getElementById('whatsapp').value);
      formData.append('viber', document.getElementById('viber').value);
      formData.append('accent_color', document.getElementById('accent_color').value);
      formData.append('package', document.getElementById('package').value);
      formData.append('active', document.getElementById('active').checked ? 1 : 0);
      formData.append('active_from', document.getElementById('active_from').value);
      formData.append('active_until', document.getElementById('active_until').value);
      
      // Files
      const slikaFile = document.getElementById('slika').files[0];
      if (slikaFile) formData.append('slika', slikaFile);
      
      const bgFile = document.getElementById('background_image').files[0];
      if (bgFile) formData.append('background_image', bgFile);
      
      // Social links
      const linkItems = document.querySelectorAll('.link-item');
      linkItems.forEach((item, index) => {
        const select = item.querySelector('select');
        const input = item.querySelector('input');
        if (select.value && input.value) {
          formData.append(`links[${index}][tip]`, select.value);
          formData.append(`links[${index}][url]`, input.value);
        }
      });
      
      // Modules
      const modules = ['vcard', 'qr_code', 'mapa', 'instagram_feed', 'text_block', 'google_reviews', 'working_hours'];
      modules.forEach(mod => {
        const checkbox = document.getElementById('module_' + mod);
        formData.append('module_' + mod, checkbox.checked ? 1 : 0);
        
        // Module configs
        if (mod === 'mapa' && checkbox.checked) {
          formData.append('mapa_link', document.getElementById('mapa_link').value);
        }
        if (mod === 'instagram_feed' && checkbox.checked) {
          formData.append('instagram_username', document.getElementById('instagram_username').value);
        }
        if (mod === 'text_block' && checkbox.checked) {
          formData.append('text_block_content', document.getElementById('text_block_content').value);
        }
        if (mod === 'google_reviews' && checkbox.checked) {
          formData.append('google_reviews_link', document.getElementById('google_reviews_link').value);
        }
        if (mod === 'working_hours' && checkbox.checked) {
          const type = document.getElementById('working_hours_type').value;
          if (type === 'all') {
            formData.append('working_hours_all', document.getElementById('working_hours_all').value);
          } else if (type === 'individual') {
            formData.append('working_hours_weekday', document.getElementById('working_hours_weekday').value);
            formData.append('working_hours_saturday', document.getElementById('working_hours_saturday').value);
            formData.append('working_hours_sunday', document.getElementById('working_hours_sunday').value);
          }
        }
      });
      
      try {
        const response = await fetch('/api.php/users' + (editingUserId ? '/' + editingUserId : ''), {
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + currentToken },
          body: formData
        });
        
        const data = await response.json();
        
        if (response.ok) {
          closeModal();
          loadUsers();
          alert(editingUserId ? '?oe... Korisnik a? 3/4 uriran' : '?oe... Korisnik kreiran');
        } else {
          document.getElementById('modalError').textContent = data.error || 'Gre??ka';
          document.getElementById('modalError').style.display = 'block';
        }
      } catch (error) {
        document.getElementById('modalError').textContent = 'Gre??ka pri spremanju';
        document.getElementById('modalError').style.display = 'block';
      }
    }

    async function editUser(userId) {
      try {
        const response = await fetch('/api.php/users/' + userId, {
          headers: { 'Authorization': 'Bearer ' + currentToken }
        });
        
        const user = await response.json();
        
        editingUserId = userId;
        document.getElementById('modalTitle').textContent = 'Uredi korisnika';
        document.getElementById('userId').value = userId;
        
        // Fill form
        document.getElementById('slug').value = user.slug || '';
        document.getElementById('ime').value = user.ime || '';
        document.getElementById('prezime').value = user.prezime || '';
        document.getElementById('opis').value = user.opis || '';
        document.getElementById('email').value = user.email || '';
        document.getElementById('telefon').value = user.telefon || '';
        document.getElementById('whatsapp').value = user.whatsapp || '';
        document.getElementById('viber').value = user.viber || '';
        document.getElementById('accent_color').value = user.accent_color || '#3b82f6';
        document.getElementById('package').value = user.package || 'basic';
        document.getElementById('active').checked = user.active === 1;
        document.getElementById('active_from').value = user.active_from || '';
        document.getElementById('active_until').value = user.active_until || '';
        
        // Social links
        document.getElementById('socialLinksContainer').innerHTML = '';
        if (user.links && user.links.length > 0) {
          user.links.forEach(link => {
            addSocialLink();
            const lastLink = document.getElementById('socialLinksContainer').lastElementChild;
            lastLink.querySelector('select').value = link.tip;
            lastLink.querySelector('input').value = link.url;
          });
        } else {
          addSocialLink();
        }
        
        // Modules
        if (user.modules) {
          user.modules.forEach(mod => {
            const checkbox = document.getElementById('module_' + mod.modul_name);
            if (checkbox) {
              checkbox.checked = mod.aktivan === 1;
              toggleModuleConfig(mod.modul_name);
              
              // Fill config
              if (mod.config) {
                const config = typeof mod.config === 'string' ? JSON.parse(mod.config) : mod.config;
                
                if (mod.modul_name === 'mapa' && config.link) {
                  document.getElementById('mapa_link').value = config.link;
                }
                if (mod.modul_name === 'instagram_feed' && config.username) {
                  document.getElementById('instagram_username').value = config.username;
                }
                if (mod.modul_name === 'text_block' && config.content) {
                  document.getElementById('text_block_content').value = config.content;
                }
                if (mod.modul_name === 'google_reviews' && config.link) {
                  document.getElementById('google_reviews_link').value = config.link;
                }
                if (mod.modul_name === 'working_hours') {
                  if (config.all) {
                    document.getElementById('working_hours_type').value = 'all';
                    document.getElementById('working_hours_all').value = config.all;
                    toggleWorkingHoursFields();
                  } else if (config.weekday) {
                    document.getElementById('working_hours_type').value = 'individual';
                    document.getElementById('working_hours_weekday').value = config.weekday || '';
                    document.getElementById('working_hours_saturday').value = config.saturday || '';
                    document.getElementById('working_hours_sunday').value = config.sunday || '';
                    toggleWorkingHoursFields();
                  }
                }
              }
            }
          });
        }
        
        // Show package section for admin/super_admin
        if (currentUserRole === 'super_admin' || currentUserRole === 'admin') {
          document.getElementById('packageSection').style.display = 'block';
        } else {
          document.getElementById('packageSection').style.display = 'none';
        }
        
        document.getElementById('userModal').classList.add('show');
      } catch (error) {
        alert('Gre??ka pri u??itavanju korisnika');
      }
    }

    async function deleteUser(userId) {
      if (!confirm('Jeste li sigurni da ? 3/4 elite obrisati ovog korisnika?')) {
        return;
      }
      
      try {
        const response = await fetch('/api.php/users/' + userId, {
          method: 'DELETE',
          headers: { 'Authorization': 'Bearer ' + currentToken }
        });
        
        if (response.ok) {
          loadUsers();
          alert('?oe... Korisnik obrisan');
        } else {
          const data = await response.json();
          alert('??OE ' + (data.error || 'Gre??ka pri brisanju'));
        }
      } catch (error) {
        alert('Gre??ka pri brisanju');
      }
    }

    // ROLE MANAGER
    async function loadRoles() {
      try {
        const response = await fetch('/api.php/roles/permissions', {
          headers: { 'Authorization': 'Bearer ' + currentToken }
        });
        
        const roles = await response.json();
        const grid = document.getElementById('roleManagerGrid');
        grid.innerHTML = '';
        
        for (const [role, permissions] of Object.entries(roles)) {
          if (role === 'super_admin') continue;
          
          const card = document.createElement('div');
          card.className = 'role-card';
          card.innerHTML = `<h3>${role}</h3>`;
          
          permissions.forEach(perm => {
            const item = document.createElement('div');
            item.className = 'permission-item';
            item.innerHTML = `
              <span class="permission-name">${perm.permission}</span>
              <div class="toggle-switch ${perm.allowed ? 'active' : ''}" 
                   onclick="togglePermission('${role}', '${perm.permission}', this)"></div>
            `;
            card.appendChild(item);
          });
          
          grid.appendChild(card);
        }
      } catch (error) {
        console.error(error);
      }
    }

    async function togglePermission(role, permission, element) {
      const allowed = !element.classList.contains('active');
      
      try {
        const response = await fetch('/api.php/roles/permissions', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + currentToken,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ role, permission, allowed })
        });
        
        if (response.ok) {
          element.classList.toggle('active');
        } else {
          alert('Gre??ka pri a? 3/4 uriranju');
        }
      } catch (error) {
        alert('Gre??ka');
      }
    }

    // ACCOUNTS
    async function loadAccounts() {
      // Placeholder - ovdje bi i??ao poziv za listanje admin accounta
      // Trenutno API nema taj endpoint, ali struktura tablice je spremna
      document.getElementById('accountsTableBody').innerHTML = 
        '<tr><td colspan="5" style="text-align: center; padding: 20px;">Placeholder - API endpoint za listanje accounta dolazi uskoro</td></tr>';
    }

    function openCreateResellerModal() {
      document.getElementById('resellerForm').reset();
      document.getElementById('resellerModal').classList.add('show');
    }

    function closeResellerModal() {
      document.getElementById('resellerModal').classList.remove('show');
    }

    async function handleResellerSubmit(e) {
      e.preventDefault();
      
      const form = e.target;
      const data = {
        username: form.username.value,
        password: form.password.value
      };
      
      try {
        const response = await fetch('/api.php/admin/create-reseller', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + currentToken,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
          closeResellerModal();
          alert('?oe... Reseller kreiran!');
          loadAccounts();
        } else {
          alert('??OE ' + (result.error || 'Gre??ka'));
        }
      } catch (error) {
        alert('Gre??ka pri kreiranju');
      }
    }

    function openCreateAdminModal() {
      document.getElementById('adminForm').reset();
      document.getElementById('adminModal').classList.add('show');
    }

    function closeAdminModal() {
      document.getElementById('adminModal').classList.remove('show');
    }

    async function handleAdminSubmit(e) {
      e.preventDefault();
      
      const form = e.target;
      const data = {
        username: form.username.value,
        password: form.password.value
      };
      
      try {
        const response = await fetch('/api.php/admin/create-admin', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + currentToken,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
          closeAdminModal();
          alert('?oe... Admin kreiran!');
          loadAccounts();
        } else {
          alert('??OE ' + (result.error || 'Gre??ka'));
        }
      } catch (error) {
        alert('Gre??ka pri kreiranju');
      }
    }

    // SETTINGS
    async function loadSettings() {
      // Placeholder
    }

    async function saveSettings() {
      alert('Settings ??e biti implementirani uskoro');
    }

    // EXPORT/IMPORT
    function handleExport() {
      const dataStr = JSON.stringify(allUsers, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'taptap-export-' + new Date().toISOString().split('T')[0] + '.json';
      link.click();
    }

    function handleImport(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result);
          console.log('Import data:', data);
          alert('Import funkcionalnost dolazi uskoro');
        } catch (error) {
          alert('Gre??ka pri ??itanju JSON filea');
        }
      };
      reader.readAsText(file);
    }


    // ============================================
    // BRANDING FUNCTIONS
    // ============================================
    
    async function loadBrandingSettings() {
      try {
        const response = await fetch('/api.php/branding');
        const branding = await response.json();
        
        document.getElementById('brandName').value = branding.brand_name || 'TapTap Card';
        document.getElementById('primaryColor').value = branding.primary_color || '#667eea';
        document.getElementById('secondaryColor').value = branding.secondary_color || '#764ba2';
        
        document.getElementById('primaryColorText').value = branding.primary_color || '#667eea';
        document.getElementById('secondaryColorText').value = branding.secondary_color || '#764ba2';
        
        updateBrandPreview();
        
        if (branding.logo_url) {
          document.getElementById('logoPreview').innerHTML = 
            '<img src="' + branding.logo_url + '" style="max-height: 100px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
        }
      } catch (error) {
        console.error('Error loading branding:', error);
      }
    }
    
    function updateBrandPreview() {
      const primary = document.getElementById('primaryColor').value;
      const secondary = document.getElementById('secondaryColor').value;
      const name = document.getElementById('brandName').value || 'Preview';
      
      const preview = document.getElementById('brandPreview');
      preview.style.background = 'linear-gradient(135deg, ' + primary + ' 0%, ' + secondary + ' 100%)';
      preview.textContent = name;
      
      document.documentElement.style.setProperty('--primary', primary);
      document.documentElement.style.setProperty('--secondary', secondary);
    }
    
    // Color picker event listeners
    if (document.getElementById('primaryColor')) {
      document.getElementById('primaryColor').addEventListener('input', function() {
        document.getElementById('primaryColorText').value = this.value;
        updateBrandPreview();
      });
    }
    
    if (document.getElementById('secondaryColor')) {
      document.getElementById('secondaryColor').addEventListener('input', function() {
        document.getElementById('secondaryColorText').value = this.value;
        updateBrandPreview();
      });
    }
    
    if (document.getElementById('brandName')) {
      document.getElementById('brandName').addEventListener('input', updateBrandPreview);
    }
    
    // Branding form submit
    if (document.getElementById('brandingForm')) {
      document.getElementById('brandingForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const brandName = document.getElementById('brandName').value;
        const primaryColor = document.getElementById('primaryColor').value;
        const secondaryColor = document.getElementById('secondaryColor').value;
        const logoFile = document.getElementById('brandLogo').files[0];
        
        let logoUrl = null;
        
        // Upload logo ako je odabran
        if (logoFile) {
          const formData = new FormData();
          formData.append('file', logoFile);
          
          try {
            const uploadResponse = await fetch('/api.php/upload-branding-logo', {
              method: 'POST',
              headers: { 'Authorization': 'Bearer ' + currentToken },
              body: formData
            });
            
            const uploadData = await uploadResponse.json();
            
            if (uploadResponse.ok && uploadData.url) {
              logoUrl = uploadData.url;
            } else {
              alert(uploadData.error || 'Greska pri uploadu loga');
              return;
            }
          } catch (error) {
            alert('Greska pri uploadu loga');
            return;
          }
        }
        
        // Dohvati trenutni logo ako nije uploadan novi
        if (!logoUrl) {
          try {
            const currentResponse = await fetch('/api.php/branding');
            const currentBranding = await currentResponse.json();
            logoUrl = currentBranding.logo_url;
          } catch (error) {
            // Ignore
          }
        }
        
        // Spremi branding
        try {
          const response = await fetch('/api.php/branding', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + currentToken
            },
            body: JSON.stringify({
              brand_name: brandName,
              primary_color: primaryColor,
              secondary_color: secondaryColor,
              logo_url: logoUrl
            })
          });
          
          const data = await response.json();
          
          if (response.ok) {
            alert('Branding uspjesno azuriran!');
            loadBrandingSettings();
          } else {
            alert(data.error || 'Greska pri spremanju');
          }
        } catch (error) {
          alert('Greska pri povezivanju');
        }
      });
    }
    // Login button event listeners (FIX za encoding bug)
    document.getElementById('loginBtn')?.addEventListener('click', handleLogin);
    
    document.getElementById('loginPassword')?.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') handleLogin();
    });
    
    document.getElementById('loginUsername')?.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') handleLogin();
    });
  </script>

</body>
</html>