<%- include('../partials/header', { title: 'Admin Dashboard' }) %>

<div class="admin-wrap">

  <!-- Sidebar -->
  <aside class="admin-sidebar">
    <div class="admin-brand">
      <div class="admin-brand-icon">&#128196;</div>
      <div>
        <div class="admin-brand-title">CES Admin</div>
        <div class="admin-brand-sub">v0.1 Beta</div>
      </div>
    </div>
    <nav class="admin-nav">
      <a href="#" class="admin-nav-item active" data-tab="dashboard">
        <span class="nav-icon">&#128200;</span> Dashboard
      </a>
      <a href="#" class="admin-nav-item" data-tab="learners">
        <span class="nav-icon">&#128100;</span> Learners
        <span class="nav-badge"><%= learners.length %></span>
      </a>
      <a href="#" class="admin-nav-item" data-tab="agencies">
        <span class="nav-icon">&#127970;</span> Agencies
        <span class="nav-badge"><%= agencies.length %></span>
      </a>
      <a href="#" class="admin-nav-item" data-tab="settings">
        <span class="nav-icon">&#9881;</span> Settings
      </a>
    </nav>
    <div class="admin-sidebar-footer">
      <a href="/admin/logout" class="admin-logout-btn">&#128274; Logout</a>
    </div>
  </aside>

  <!-- Main Content -->
  <main class="admin-main">

    <!-- ── DASHBOARD TAB ── -->
    <div class="admin-tab active" id="tab-dashboard">
      <div class="admin-page-header">
        <div>
          <h1>Dashboard</h1>
          <p class="admin-page-sub">Connecticut Elderly Services Training Overview</p>
        </div>
        <div class="admin-page-date" id="adminDate"></div>
      </div>

      <div class="stats-grid">
        <div class="stat-card stat-blue">
          <div class="stat-icon">&#128100;</div>
          <div class="stat-info">
            <div class="stat-number"><%= stats.total %></div>
            <div class="stat-label">Total Learners</div>
          </div>
        </div>
        <div class="stat-card stat-orange">
          <div class="stat-icon">&#9989;</div>
          <div class="stat-info">
            <div class="stat-number"><%= stats.completed %></div>
            <div class="stat-label">Completed Training</div>
          </div>
        </div>
        <div class="stat-card stat-green">
          <div class="stat-icon">&#127941;</div>
          <div class="stat-info">
            <div class="stat-number"><%= stats.passed %></div>
            <div class="stat-label">Certified</div>
          </div>
        </div>
        <div class="stat-card stat-purple">
          <div class="stat-icon">&#128200;</div>
          <div class="stat-info">
            <div class="stat-number"><%= Math.round((stats.passed / Math.max(stats.total, 1)) * 100) %>%</div>
            <div class="stat-label">Pass Rate</div>
          </div>
        </div>
      </div>

      <!-- Recent activity -->
      <div class="admin-card">
        <div class="admin-card-header">
          <h2>Recent Activity</h2>
        </div>
        <% const recent = learners.slice(0, 5); %>
        <% if (recent.length === 0) { %>
          <p class="no-data">No learner activity yet.</p>
        <% } else { %>
          <table class="admin-table">
            <thead>
              <tr><th>Name</th><th>Agency</th><th>Status</th><th>Date</th></tr>
            </thead>
            <tbody>
              <% recent.forEach(l => { %>
                <tr>
                  <td><strong><%= l.name %></strong></td>
                  <td><%= l.agency_name || '—' %></td>
                  <td>
                    <% if (l.passed) { %>
                      <span class="badge badge-green">Certified</span>
                    <% } else if (l.completed_at) { %>
                      <span class="badge badge-red">Failed</span>
                    <% } else { %>
                      <span class="badge badge-yellow">In Progress</span>
                    <% } %>
                  </td>
                  <td class="text-muted"><%= new Date(l.started_at).toLocaleDateString() %></td>
                </tr>
              <% }); %>
            </tbody>
          </table>
          <% if (learners.length > 5) { %>
            <p class="card-footer-note">Showing 5 of <%= learners.length %> learners. <a href="#" data-tab="learners" class="tab-link">View all &rarr;</a></p>
          <% } %>
        <% } %>
      </div>
    </div>

    <!-- ── LEARNERS TAB ── -->
    <div class="admin-tab" id="tab-learners">
      <div class="admin-page-header">
        <div>
          <h1>Learners</h1>
          <p class="admin-page-sub"><%= learners.length %> total learner<%= learners.length !== 1 ? 's' : '' %> enrolled</p>
        </div>
        <div class="admin-search-wrap">
          <input type="text" id="learnerSearch" placeholder="&#128269; Search by name or agency..." class="admin-search-input">
          <select id="statusFilter" class="admin-select">
            <option value="">All Statuses</option>
            <option value="certified">Certified</option>
            <option value="failed">Failed</option>
            <option value="in-progress">In Progress</option>
          </select>
          <select id="agencyFilter" class="admin-select">
            <option value="">All Agencies</option>
            <% agencies.forEach(a => { %>
              <option value="<%= a.name %>"><%= a.name %></option>
            <% }); %>
          </select>
        </div>
      </div>

      <div class="admin-card">
        <% if (learners.length === 0) { %>
          <div class="empty-state">
            <div class="empty-icon">&#128100;</div>
            <p>No learners enrolled yet.</p>
            <p class="text-muted">Share your agency code with employees to get started.</p>
          </div>
        <% } else { %>
          <table class="admin-table" id="learnersTable">
            <thead>
              <tr>
                <th>Name</th>
                <th>Agency</th>
                <th>Started</th>
                <th>Completed</th>
                <th>Status</th>
                <th>Certificate</th>
              </tr>
            </thead>
            <tbody>
              <% learners.forEach(l => { %>
                <tr data-name="<%= l.name.toLowerCase() %>"
                    data-agency="<%= (l.agency_name || '').toLowerCase() %>"
                    data-status="<%= l.passed ? 'certified' : l.completed_at ? 'failed' : 'in-progress' %>">
                  <td><strong><%= l.name %></strong></td>
                  <td><%= l.agency_name || '—' %></td>
                  <td><%= new Date(l.started_at).toLocaleDateString() %></td>
                  <td><%= l.completed_at ? new Date(l.completed_at).toLocaleDateString() : '—' %></td>
                  <td>
                    <% if (l.passed) { %>
                      <span class="badge badge-green">Certified</span>
                    <% } else if (l.completed_at) { %>
                      <span class="badge badge-red">Failed</span>
                    <% } else { %>
                      <span class="badge badge-yellow">In Progress</span>
                    <% } %>
                  </td>
                  <td>
                    <% if (l.certificate_url) { %>
                      <a href="<%= l.certificate_url %>" class="link-btn" download>&#128196; Download</a>
                    <% } else { %>
                      <span class="text-muted">—</span>
                    <% } %>
                  </td>
                </tr>
              <% }); %>
            </tbody>
          </table>
          <div id="noResults" class="no-data" style="display:none">No learners match your search.</div>
        <% } %>
      </div>
    </div>

    <!-- ── AGENCIES TAB ── -->
    <div class="admin-tab" id="tab-agencies">
      <div class="admin-page-header">
        <div>
          <h1>Agencies</h1>
          <p class="admin-page-sub">Manage agency access codes</p>
        </div>
      </div>

      <div class="admin-two-col">
        <div class="admin-card">
          <div class="admin-card-header">
            <h2>Active Agencies</h2>
          </div>
          <table class="admin-table">
            <thead>
              <tr><th>Agency Name</th><th>Access Code</th><th>Added</th></tr>
            </thead>
            <tbody>
              <% agencies.forEach(a => { %>
                <tr>
                  <td><strong><%= a.name %></strong></td>
                  <td><code class="code-pill"><%= a.code %></code></td>
                  <td class="text-muted"><%= new Date(a.created_at).toLocaleDateString() %></td>
                </tr>
              <% }); %>
            </tbody>
          </table>
        </div>

        <div class="admin-card">
          <div class="admin-card-header">
            <h2>Add New Agency</h2>
          </div>
          <div id="agencyMsg" class="alert" style="display:none"></div>
          <form id="agencyForm" class="form">
            <div class="form-group">
              <label>Agency Name</label>
              <input type="text" name="name" required placeholder="e.g. Sunrise Home Care" class="form-input">
            </div>
            <div class="form-group">
              <label>Access Code</label>
              <input type="text" name="code" required placeholder="e.g. SUNRISE01"
                     class="form-input" style="text-transform:uppercase"
                     oninput="this.value=this.value.toUpperCase()">
              <p class="field-hint">Employees enter this code to start training. Use something memorable and unique.</p>
            </div>
            <button type="submit" class="btn btn-primary">Add Agency</button>
          </form>
        </div>
      </div>
    </div>

    <!-- ── SETTINGS TAB ── -->
    <div class="admin-tab" id="tab-settings">
      <div class="admin-page-header">
        <div>
          <h1>Settings</h1>
          <p class="admin-page-sub">Manage your admin account</p>
        </div>
      </div>

      <div class="admin-two-col">

        <!-- Password Change Form -->
        <div class="admin-card">
          <div class="admin-card-header">
            <h2>&#128274; Change Password</h2>
          </div>
          <div class="settings-section">
            <div id="pwAlert" class="alert" style="display:none"></div>
            <form id="changePasswordForm" class="form">
              <div class="form-group">
                <label for="currentPassword">Current Password</label>
                <input type="password" id="currentPassword" name="currentPassword"
                       required placeholder="Enter current password" class="form-input">
              </div>
              <div class="form-group">
                <label for="newPassword">New Password</label>
                <input type="password" id="newPassword" name="newPassword"
                       required placeholder="Minimum 8 characters" class="form-input" minlength="8">
              </div>
              <div class="form-group">
                <label for="confirmPassword">Confirm New Password</label>
                <input type="password" id="confirmPassword" name="confirmPassword"
                       required placeholder="Repeat new password" class="form-input" minlength="8">
              </div>
              <button type="submit" class="btn btn-primary btn-full" id="pwSubmitBtn">
                Update Password
              </button>
            </form>
          </div>
        </div>

        <!-- System Info -->
        <div class="admin-card">
          <div class="admin-card-header">
            <h2>&#128196; System Information</h2>
          </div>
          <table class="admin-table settings-table">
            <tr><td>Version</td><td><strong>v0.1 Beta</strong></td></tr>
            <tr><td>Platform</td><td>Connecticut Elderly Services Training</td></tr>
            <tr><td>Powered by</td><td><a href="https://arsenalcomputing.com" target="_blank">Arsenal Computing</a></td></tr>
            <tr><td>Total Agencies</td><td><%= agencies.length %></td></tr>
            <tr><td>Total Learners</td><td><%= learners.length %></td></tr>
            <tr><td>Certified</td><td><%= stats.passed %></td></tr>
          </table>
        </div>

      </div>
    </div>

  </main>
</div>

<script>
// CSRF token — injected server-side, sent with every state-changing request
const CSRF_TOKEN = '<%= typeof csrfToken !== "undefined" ? csrfToken : "" %>';

// ── Tab navigation ──────────────────────────────────────────────────
function switchTab(tabName) {
  document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.admin-nav-item').forEach(n => n.classList.remove('active'));
  const tab = document.getElementById('tab-' + tabName);
  if (tab) tab.classList.add('active');
  document.querySelectorAll('[data-tab="' + tabName + '"]').forEach(n => n.classList.add('active'));
}

document.querySelectorAll('[data-tab]').forEach(el => {
  el.addEventListener('click', function(e) {
    e.preventDefault();
    switchTab(this.dataset.tab);
  });
});

// ── Date display ────────────────────────────────────────────────────
document.getElementById('adminDate').textContent = new Date().toLocaleDateString('en-US', {
  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
});

// ── Learner search & filter ─────────────────────────────────────────
const searchInput = document.getElementById('learnerSearch');
const statusFilter = document.getElementById('statusFilter');
const agencyFilter = document.getElementById('agencyFilter');
const noResults = document.getElementById('noResults');

function filterLearners() {
  const search = searchInput ? searchInput.value.toLowerCase() : '';
  const status = statusFilter ? statusFilter.value : '';
  const agency = agencyFilter ? agencyFilter.value.toLowerCase() : '';
  const rows = document.querySelectorAll('#learnersTable tbody tr');
  let visible = 0;

  rows.forEach(row => {
    const name = row.dataset.name || '';
    const rowAgency = row.dataset.agency || '';
    const rowStatus = row.dataset.status || '';
    const matchSearch = !search || name.includes(search) || rowAgency.includes(search);
    const matchStatus = !status || rowStatus === status;
    const matchAgency = !agency || rowAgency === agency.toLowerCase();
    const show = matchSearch && matchStatus && matchAgency;
    row.style.display = show ? '' : 'none';
    if (show) visible++;
  });

  if (noResults) noResults.style.display = visible === 0 ? 'block' : 'none';
}

if (searchInput) searchInput.addEventListener('input', filterLearners);
if (statusFilter) statusFilter.addEventListener('change', filterLearners);
if (agencyFilter) agencyFilter.addEventListener('change', filterLearners);

// ── Add agency form ─────────────────────────────────────────────────
const agencyForm = document.getElementById('agencyForm');
const agencyMsg = document.getElementById('agencyMsg');

if (agencyForm) {
  agencyForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = agencyForm.name.value.trim();
    const code = agencyForm.code.value.trim().toUpperCase();

    agencyMsg.style.display = 'none';
    agencyMsg.className = 'alert';

    try {
      const res = await fetch('/admin/agencies/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, code, _csrf: CSRF_TOKEN })
      });
      const data = await res.json();
      if (res.ok && data.success) {
        agencyMsg.textContent = 'Agency "' + name + '" added successfully! Code: ' + code;
        agencyMsg.classList.add('alert-success');
        agencyMsg.style.display = 'block';
        agencyForm.reset();
        setTimeout(() => location.reload(), 1500);
      } else {
        agencyMsg.textContent = data.error || 'Could not add agency.';
        agencyMsg.classList.add('alert-error');
        agencyMsg.style.display = 'block';
      }
    } catch (err) {
      agencyMsg.textContent = 'Network error. Please try again.';
      agencyMsg.classList.add('alert-error');
      agencyMsg.style.display = 'block';
    }
  });
}

// ── Change password form ────────────────────────────────────────────
const pwForm = document.getElementById('changePasswordForm');
const pwAlert = document.getElementById('pwAlert');
const pwBtn = document.getElementById('pwSubmitBtn');

function showPwAlert(msg, type) {
  pwAlert.textContent = msg;
  pwAlert.className = 'alert alert-' + type;
  pwAlert.style.display = 'block';
  pwAlert.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

if (pwForm) {
  pwForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    pwAlert.style.display = 'none';

    // Client-side validation
    if (newPassword.length < 8) {
      return showPwAlert('New password must be at least 8 characters.', 'error');
    }
    if (newPassword !== confirmPassword) {
      return showPwAlert('New passwords do not match. Please try again.', 'error');
    }

    pwBtn.textContent = 'Updating...';
    pwBtn.disabled = true;

    try {
      const res = await fetch('/admin/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ currentPassword, newPassword, confirmPassword, _csrf: CSRF_TOKEN })
      });

      if (res.redirected || res.url.includes('/admin/change-password')) {
        // Route exists — parse the response
        const html = await res.text();
        if (html.includes('alert-success') || html.includes('successfully')) {
          showPwAlert('Password updated successfully! Use your new password next time you log in.', 'success');
          pwForm.reset();
        } else if (html.includes('incorrect')) {
          showPwAlert('Current password is incorrect. Please try again.', 'error');
        } else if (html.includes('do not match')) {
          showPwAlert('New passwords do not match.', 'error');
        } else {
          showPwAlert('Password updated.', 'success');
          pwForm.reset();
        }
      } else if (res.status === 404) {
        showPwAlert('Password change is not available yet. Please restart the app after uploading the latest files.', 'error');
      } else {
        showPwAlert('Unexpected response. Please try again.', 'error');
      }
    } catch (err) {
      showPwAlert('Connection error. Please try again.', 'error');
    }

    pwBtn.textContent = 'Update Password';
    pwBtn.disabled = false;
  });
}
</script>

<%- include('../partials/footer') %>
