let securityAccounts = [];
let securityRoles = [];

function roleLabel(role) {
  return String(role || '').replace(/_/g, ' ').replace(/\b\w/g, m => m.toUpperCase());
}

function statusPill(status) {
  const s = String(status || 'unknown');
  const cls = s === 'active' ? 'pill-green' : (s === 'blocked' ? 'pill-red' : 'pill-muted');
  return `<span class="pill ${cls}">${Pyrk.esc(s)}</span>`;
}

function attemptPill(success, reason) {
  return Number(success || 0) === 1
    ? '<span class="pill pill-green">Success</span>'
    : `<span class="pill pill-red">Failed</span><small>${Pyrk.esc(reason || '')}</small>`;
}

function accountSecurityHtml(a) {
  const failed = Number(a.failed_login_count || 0);
  const locked = a.locked_until && new Date(String(a.locked_until).replace(' ', 'T')).getTime() > Date.now();
  return `<div class="security-mini">
    <strong>${failed} failed</strong>
    ${locked ? `<span class="pill pill-red">Locked until ${Pyrk.esc(a.locked_until)}</span>` : '<span class="pill pill-muted">Not locked</span>'}
    ${a.last_login_ip ? `<small>Last IP: ${Pyrk.esc(a.last_login_ip)}</small>` : '<small>No IP yet</small>'}
  </div>`;
}

function filteredAccounts() {
  const q = (document.getElementById('accountSearch').value || '').toLowerCase().trim();
  const role = document.getElementById('accountRoleFilter').value;
  const status = document.getElementById('accountStatusFilter').value;
  return securityAccounts.filter(a => {
    const hay = `${a.full_name || ''} ${a.email || ''} ${a.mobile || ''} ${a.last_login_ip || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!role || a.role_name === role) && (!status || a.status === status);
  });
}

function renderAccounts() {
  const rows = filteredAccounts();
  document.getElementById('securityAccountsBody').innerHTML = rows.map(a => `
    <tr>
      <td><strong>${Pyrk.esc(a.full_name)}</strong><small>${Pyrk.esc(a.email)}${a.mobile ? ' · ' + Pyrk.esc(a.mobile) : ''}</small></td>
      <td><span class="role-badge">${roleLabel(a.role_name)}</span></td>
      <td>${statusPill(a.status)}${a.blocked_reason ? `<small>${Pyrk.esc(a.blocked_reason)}</small>` : ''}</td>
      <td>${accountSecurityHtml(a)}</td>
      <td>${Pyrk.esc(a.last_login_at || 'Never')}</td>
      <td class="table-actions">
        ${a.status === 'blocked'
          ? `<button class="btn btn-small" type="button" onclick="unblockAccount(${a.id})">Unblock</button>`
          : `<button class="btn btn-danger btn-small" type="button" onclick="blockAccount(${a.id})">Block</button>`}
        ${a.locked_until ? `<button class="btn btn-light btn-small" type="button" onclick="resetAccountLock(${a.id})">Reset lock</button>` : ''}
        <button class="btn btn-light btn-small" type="button" onclick="showAccountLogs(${a.id})">Logins</button>
      </td>
    </tr>`).join('') || '<tr><td colspan="6" class="muted">No accounts found.</td></tr>';
}

async function loadSettings() {
  const res = await Pyrk.get('security.php', {action:'settings'});
  if (!res.ok) return;
  const s = res.data.settings || {};
  document.getElementById('maxFailedAttempts').value = s.max_failed_attempts || 3;
  document.getElementById('lockoutMinutes').value = s.lockout_minutes || 60;
  document.getElementById('sessionTimeoutMinutes').value = s.session_timeout_minutes || 180;
  document.getElementById('settingFailedStat').textContent = s.max_failed_attempts || 3;
  document.getElementById('settingLockStat').textContent = s.lockout_minutes || 60;
  document.getElementById('settingSessionStat').textContent = s.session_timeout_minutes || 180;
}

async function loadAccounts() {
  const res = await Pyrk.get('security.php', {action:'accounts'});
  if (!res.ok) {
    document.getElementById('securityAccountsBody').innerHTML = `<tr><td colspan="6" class="bad">${Pyrk.esc(res.message)}</td></tr>`;
    return;
  }
  securityAccounts = res.data.accounts || [];
  securityRoles = res.data.roles || [];
  document.getElementById('accountRoleFilter').innerHTML = '<option value="">All roles</option>' + securityRoles.map(r => `<option value="${Pyrk.esc(r)}">${roleLabel(r)}</option>`).join('');
  renderAccounts();
}

async function loadLoginLogs(userId = window.PYRK_SECURITY_USER_ID || 0) {
  const params = {
    action: 'login_logs',
    q: document.getElementById('loginSearch').value || '',
    success: document.getElementById('loginSuccessFilter').value || '',
    limit: document.getElementById('loginLimit').value || 100,
  };
  if (userId) params.user_id = userId;
  const res = await Pyrk.get('security.php', params);
  if (!res.ok) {
    document.getElementById('loginLogsBody').innerHTML = `<tr><td colspan="6" class="bad">${Pyrk.esc(res.message)}</td></tr>`;
    return;
  }
  const logs = res.data.logs || [];
  document.getElementById('loginLogsBody').innerHTML = logs.map(l => `
    <tr>
      <td><strong>${Pyrk.esc(l.login_at || '—')}</strong></td>
      <td><strong>${Pyrk.esc(l.full_name || 'Unknown / failed email')}</strong><small>${Pyrk.esc(l.email || '')}${l.role_name ? ' · ' + roleLabel(l.role_name) : ''}</small></td>
      <td>${attemptPill(l.success, l.failure_reason)}</td>
      <td>${Pyrk.esc(l.ip_address || '—')}</td>
      <td><span class="device-text">${Pyrk.esc(l.user_agent || '—')}</span></td>
      <td>${l.logout_at ? `<strong>${Pyrk.esc(l.logout_at)}</strong><small>${Pyrk.esc(l.logout_reason || '')}</small>` : '<span class="muted">Open / not recorded</span>'}</td>
    </tr>`).join('') || '<tr><td colspan="6" class="muted">No login logs found yet.</td></tr>';
}

window.blockAccount = async function blockAccount(id) {
  const reason = prompt('Reason for blocking this account:', 'Blocked by super admin');
  if (reason === null) return;
  const res = await Pyrk.post('security.php', {action:'block', user_id:id, reason});
  alert(res.message || (res.ok ? 'Blocked' : 'Error'));
  await loadAccounts();
};

window.unblockAccount = async function unblockAccount(id) {
  if (!confirm('Unblock this account and set status to active?')) return;
  const res = await Pyrk.post('security.php', {action:'unblock', user_id:id});
  alert(res.message || (res.ok ? 'Unblocked' : 'Error'));
  await loadAccounts();
};

window.resetAccountLock = async function resetAccountLock(id) {
  if (!confirm('Reset failed attempts and temporary lock for this account?')) return;
  const res = await Pyrk.post('security.php', {action:'reset_lock', user_id:id});
  alert(res.message || (res.ok ? 'Reset' : 'Error'));
  await loadAccounts();
};

window.showAccountLogs = async function showAccountLogs(id) {
  window.PYRK_SECURITY_USER_ID = id;
  await loadLoginLogs(id);
  document.querySelector('.security-logs-panel').scrollIntoView({behavior:'smooth', block:'start'});
};

document.getElementById('securitySettingsForm').addEventListener('submit', async e => {
  e.preventDefault();
  const data = Object.fromEntries(new FormData(e.target));
  const res = await Pyrk.post('security.php', {action:'save_settings', ...data});
  Pyrk.toast('securitySettingsMsg', res);
  await loadSettings();
});

document.getElementById('accountSearch').addEventListener('input', renderAccounts);
document.getElementById('accountRoleFilter').addEventListener('change', renderAccounts);
document.getElementById('accountStatusFilter').addEventListener('change', renderAccounts);
document.getElementById('loginSearch').addEventListener('input', () => loadLoginLogs());
document.getElementById('loginSuccessFilter').addEventListener('change', () => loadLoginLogs());
document.getElementById('loginLimit').addEventListener('change', () => loadLoginLogs());
document.getElementById('refreshSecurityBtn').addEventListener('click', () => { loadAccounts(); loadLoginLogs(); });

Promise.all([loadSettings(), loadAccounts(), loadLoginLogs()]);
