<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/rbac.php";
require_once "../includes/lang.php";
require_once "../includes/csrf.php";
require_once "../includes/avatar.php";

requirePageAuth();
if (!hasPermission("view_admin") && !hasPermission("manage_users")) {
    http_response_code(403);
    echo "Forbidden";
    exit;
}

$user = getAuthUser();
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user['id'] ?? 0));
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars(t("admin_dashboard")) ?> - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<link rel="stylesheet" href="assets/css/dashboard.css" type="text/css">
<link rel="stylesheet" href="assets/css/owl.carousel.min.css" type="text/css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<link rel="shortcut icon" href="assets/images/favicon-icon/favicon.png">
</head>
<body>
<div class="dashboard_container">
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="dashboard.php"><img src="assets/images/logo.png" alt="logo"/></a></div>
<div id="dashboard-responsive-nav-trigger"><i class="fa fa-reorder"></i></div>
</div>
<div class="collapse navbar-collapse" id="navigation">
<div class="user_nav">
<div class="dropdown">
<span id="dLabel" type="button" data-toggle="dropdown"><img src="<?= htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="img" onerror="this.onerror=null;this.src='assets/images/100x100.jpg';"></span>
<ul class="dropdown-menu" aria-labelledby="dLabel">
<li><a href="admin.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>
</div>
<div class="submit_listing"><a href="nalog.php" class="btn outline-btn"><i class="fa fa-plus-circle"></i> <?= htmlspecialchars(t("add_account")) ?></a></div>
<div class="submit_listing" style="margin-left:10px;">
  <a href="../api/lang.php?lang=en&redirect=../public/admin.php" class="btn outline-btn">EN</a>
  <a href="../api/lang.php?lang=sr&redirect=../public/admin.php" class="btn outline-btn">SR</a>
</div>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li class="active"><a href="admin.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li><a href="dashboard.php"><i class="fa fa-th-list"></i> <?= htmlspecialchars(t("requests")) ?></a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Matched Workers</a></li>
<li><a href="agency_documents.php"><i class="fa fa-file-text-o"></i> Worker Documentation</a></li>
<li><a href="worker_documents_review.php"><i class="fa fa-folder-open-o"></i> Documentation Review</a></li>
<li>
  <a href="#adminActionsMenu" data-toggle="collapse" aria-expanded="false">
    <i class="fa fa-plus-circle"></i> Admin Actions <span class="caret"></span>
  </a>
  <ul id="adminActionsMenu" class="collapse list-unstyled" style="padding-left:15px;">
    <li><a href="nalog.php"><i class="fa fa-user-plus"></i> <?= htmlspecialchars(t("add_user")) ?></a></li>
    <li><a href="add_skills.php"><i class="fa fa-tags"></i> <?= htmlspecialchars(t("add_skill")) ?></a></li>
    <li><a href="add_positions.php"><i class="fa fa-briefcase"></i> Positions</a></li>
    <li><a href="manage_permissions.php"><i class="fa fa-lock"></i> <?= htmlspecialchars(t("manage_permissions")) ?></a></li>
    <li><a href="admin_profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("admin_profile")) ?></a></li>
  </ul>
</li>
<li><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="terms.php"><i class="fa fa-file-text-o"></i> <?= htmlspecialchars(t("terms_of_use")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>

<div class="dashboard-content">
<div id="titlebar">
<div class="row"><div class="col-md-12"><h2><?= htmlspecialchars(t("admin_dashboard")) ?></h2></div></div>
</div>


<div class="dashboard-section-card">
  <div class="section-header">
    <h4><?= htmlspecialchars(t("admin_dashboard")) ?> KPI</h4>
    <button type="button" class="btn btn-default btn-sm" id="toggleStatsBtn">Expand stats</button>
  </div>
  <div class="kpi-grid" id="kpiGrid">
    <div class="dashboard-info color-1"><h4 id="kpi-users">0</h4><span><?= htmlspecialchars(t("total_users")) ?></span></div>
    <div class="dashboard-info color-2"><h4 id="kpi-workers">0</h4><span><?= htmlspecialchars(t("total_workers")) ?></span></div>
    <div class="dashboard-info color-3"><h4 id="kpi-messages">0</h4><span><?= htmlspecialchars(t("total_messages")) ?></span></div>
    <div class="dashboard-info color-4"><h4 id="kpi-requests">0</h4><span><?= htmlspecialchars(t("total_requests")) ?></span></div>
    <div class="dashboard-info color-5"><h4 id="kpi-matches">0</h4><span><?= htmlspecialchars(t("total_matches")) ?></span></div>
  </div>
</div>

<div class="dashboard-section-card">
  <div class="section-header">
    <h4>Charts</h4>
    <button type="button" class="btn btn-default btn-sm" id="toggleChartsBtn">Expand charts</button>
  </div>
  <div class="row chart-grid" id="chartGrid">
    <div class="col-md-6 chart-wrap">
      <div class="chart-panel">
        <canvas class="chart-canvas" id="workersChart"></canvas>
      </div>
    </div>
    <div class="col-md-6 chart-wrap">
      <div class="chart-panel">
        <canvas class="chart-canvas" id="messagesChart"></canvas>
      </div>
    </div>
    <div class="col-md-12 chart-wrap chart-wrap-lg">
      <div class="chart-panel">
        <canvas class="chart-canvas" id="usersChart"></canvas>
      </div>
    </div>
  </div>
</div>


<div class="row" style="margin-top:20px;">
<div class="col-lg-12">
<div class="dashboard-list-box with-icons">
<h4><?= htmlspecialchars(t("recent_activities")) ?></h4>
<ul id="auditList"></ul>
</div>
</div>
</div>

<div class="row" style="margin-top:20px;">
<div class="col-lg-12">
<div class="dashboard-list-box">
<h4>Detailed Matches</h4>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
  <th>ID</th>
  <th>Worker</th>
  <th>Company</th>
  <th>Matched By</th>
  <th>Matched For</th>
  <th>Created At</th>
</tr>
</thead>
<tbody id="adminMatchesBody">
<tr><td colspan="6">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>

<div class="row" style="margin-top:30px;">
<div class="col-lg-12">
<div class="dashboard-list-box">
<h4><?= htmlspecialchars(t("admin_panel")) ?></h4>
<ul class="tab_group" style="border-bottom:none;">
<li class="active"><a href="nalog.php"><?= htmlspecialchars(t("add_user")) ?></a></li>
<li><a href="admin_profile.php"><?= htmlspecialchars(t("admin_profile")) ?></a></li>
<li><a href="add_skills.php"><?= htmlspecialchars(t("add_skill")) ?></a></li>
<li><a href="manage_permissions.php"><?= htmlspecialchars(t("manage_permissions")) ?></a></li>
<li><a href="#" onclick="loadPaymentApprovals(); return false;">Refresh Invoices</a></li>
<li><a href="#" onclick="loadResetRequests(); return false;">Refresh Password Requests</a></li>
</ul>
</div>
</div>
</div>

<div class="row" style="margin-top:20px;">
<div class="col-lg-12">
<div class="dashboard-list-box">
<h4>Category Management</h4>
<p style="margin-bottom:12px;">Manage worker categories (skills) with direct delete actions.</p>
<div id="admin-categories-list" class="row"></div>
</div>
</div>
</div>

<div class="tab-panel" id="invoices-panel">
  <div id="invoices-list" class="row" style="margin-top:15px;"></div>
</div>

<div class="tab-panel active" id="reset-requests-panel">
  <div id="reset-requests-list" class="row" style="margin-top:15px;"></div>
</div>

<div class="tab-panel" id="agencies-panel">
<div class="row" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
<div class="col-md-4" style="padding-left:0;">
<input type="text" id="agencies-search" placeholder="<?= htmlspecialchars(t("global_search")) ?> agencies..." class="form-control">
</div>
<button class="btn btn-primary" onclick="loadAdminTab('agencies')">Search</button>
</div>
<div id="agencies-list" class="row" style="margin-top:15px;"></div>
</div>

<div class="tab-panel" id="workers-panel">
<div class="row" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
<div class="col-md-3" style="padding-left:0;">
<input type="text" id="workers-name" placeholder="Name..." class="form-control">
</div>
<div class="col-md-2">
<input type="text" id="workers-location" placeholder="<?= htmlspecialchars(t("location")) ?>..." class="form-control">
</div>
<div class="col-md-2">
<input type="text" id="workers-country" placeholder="<?= htmlspecialchars(t("country")) ?>..." class="form-control">
</div>
<div class="col-md-2">
<input type="text" id="workers-skills" placeholder="<?= htmlspecialchars(t("skills")) ?>..." class="form-control">
</div>
<div class="col-md-2">
<input type="text" id="workers-languages" placeholder="<?= htmlspecialchars(t("languages")) ?>..." class="form-control">
</div>
<div class="col-md-2">
<input type="date" id="workers-availability" class="form-control">
</div>
<button class="btn btn-primary" onclick="loadAdminTab('workers')">Filter</button>
</div>
<div id="workers-list" class="row" style="margin-top:15px;"></div>
</div>

<div class="tab-panel" id="companies-panel">
<div class="row" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
<div class="col-md-4" style="padding-left:0;">
<input type="text" id="companies-search" placeholder="<?= htmlspecialchars(t("global_search")) ?> companies..." class="form-control">
</div>
<button class="btn btn-primary" onclick="loadAdminTab('companies')">Search</button>
</div>
<div id="companies-list" class="row" style="margin-top:15px;"></div>
</div>

</div>


</div>
</div>
</div>


<script>
window.APP = { csrf: "<?= htmlspecialchars($csrf) ?>", userId: <?= (int)$user["id"] ?> };
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script>
let workersChartInstance = null;
let messagesChartInstance = null;
let usersChartInstance = null;

function resizeCharts() {
  [workersChartInstance, messagesChartInstance, usersChartInstance].forEach(ch => {
    if (ch) ch.resize();
  });
}

function bindExpandButtons() {
  const statsBtn = document.getElementById("toggleStatsBtn");
  const chartsBtn = document.getElementById("toggleChartsBtn");
  const kpiGrid = document.getElementById("kpiGrid");
  const chartGrid = document.getElementById("chartGrid");

  if (statsBtn && kpiGrid) {
    statsBtn.addEventListener("click", function() {
      kpiGrid.classList.toggle("expanded");
      statsBtn.textContent = kpiGrid.classList.contains("expanded") ? "Collapse stats" : "Expand stats";
    });
  }

  if (chartsBtn && chartGrid) {
    chartsBtn.addEventListener("click", function() {
      chartGrid.classList.toggle("expanded");
      chartsBtn.textContent = chartGrid.classList.contains("expanded") ? "Collapse charts" : "Expand charts";
      setTimeout(resizeCharts, 200);
    });
  }
}

async function safeJsonResponse(res) {
  const text = await res.text();
  try {
    return JSON.parse(text);
  } catch (e) {
    console.error("Invalid JSON response:", text);
    return { success: false, error: "invalid_json", raw: text };
  }
}

async function loadStats() {
  const r = await fetch("../api/admin_stats.php", { credentials: "same-origin" });
  const j = await safeJsonResponse(r);
  if (!j.success) return;
  const d = j.data;

  document.getElementById("kpi-users").textContent = d.totals.users;
  document.getElementById("kpi-workers").textContent = d.totals.workers;
  document.getElementById("kpi-messages").textContent = d.totals.messages;
  document.getElementById("kpi-requests").textContent = d.totals.requests;
  document.getElementById("kpi-matches").textContent = d.totals.matches;

  workersChartInstance = new Chart(document.getElementById("workersChart"), {
    type: "doughnut",
    data: {
      labels: d.workersByStatus.map(x => x.status),
      datasets: [{ data: d.workersByStatus.map(x => x.total) }]
    }
  });

  messagesChartInstance = new Chart(document.getElementById("messagesChart"), {
    type: "line",
    data: {
      labels: d.messagesPerDay.map(x => x.day),
      datasets: [{ label: "Messages", data: d.messagesPerDay.map(x => x.total), borderColor: "#7e57c2" }]
    }
  });

  usersChartInstance = new Chart(document.getElementById("usersChart"), {
    type: "bar",
    data: {
      labels: d.newUsersPerMonth.map(x => x.month),
      datasets: [{ label: "Users", data: d.newUsersPerMonth.map(x => x.total), backgroundColor: "#5c6bc0" }]
    }
  });
}

async function loadAudit() {
  const r = await fetch("../api/audit_log.php?limit=20", { credentials: "same-origin" });
  const j = await safeJsonResponse(r);
  const ul = document.getElementById("auditList");
  ul.innerHTML = "";
  if (!j.success) {
    ul.innerHTML = "<li>Failed to load audit log.</li>";
    return;
  }
  j.data.forEach(item => {
    const li = document.createElement("li");
    li.innerHTML = '<i class="list-box-icon fa fa-list"></i> ' + (item.email || "user") + " - " + item.action;
    ul.appendChild(li);
  });
}
bindExpandButtons();
loadStats();
loadAudit();
loadDetailedMatches();
loadCategories();
(function(){
  var initialTab = "reset-requests";
  try {
    var saved = localStorage.getItem("adminActiveTab");
    if (saved) {
      initialTab = saved;
      localStorage.removeItem("adminActiveTab");
    }
  } catch (e) {}
  var tabLi = document.querySelector('[data-tab="' + initialTab + '"]');
  if (tabLi) {
    document.querySelectorAll('[data-tab]').forEach(function(l){ l.classList.remove('active'); });
    tabLi.classList.add('active');
    document.querySelectorAll('.tab-panel').forEach(function(p){ p.classList.remove('active'); });
    var panel = document.getElementById(initialTab + '-panel');
    if (panel) panel.classList.add('active');
  }
  loadAdminTab(initialTab);
})();

// Admin tabs
document.querySelectorAll('[data-tab]').forEach(li => {
  li.addEventListener('click', function() {
    document.querySelectorAll('[data-tab]').forEach(l => l.classList.remove('active'));
    this.classList.add('active');
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.getElementById(this.dataset.tab + '-panel').classList.add('active');
    try { localStorage.setItem("adminActiveTab", this.dataset.tab); } catch (e) {}
    loadAdminTab(this.dataset.tab);
  });
});

async function loadAdminTab(tab) {
  if (tab === 'payments' || tab === 'invoices') {
    loadPaymentApprovals();
    return;
  }
  if (tab === 'reset-requests') {
    loadResetRequests();
    return;
  }

  const panelId = tab + '-list';
  const listEl = document.getElementById(panelId);
  if (!listEl) return;
  listEl.innerHTML = '<div class="col-md-12"><p>Loading...</p></div>';

  let params = {};
  if (tab === 'agencies') {
    params.q = document.getElementById('agencies-search').value;
  } else if (tab === 'workers') {
    params.name = document.getElementById('workers-name').value;
    params.location = document.getElementById('workers-location').value;
    params.country = document.getElementById('workers-country').value;
    params.skills = document.getElementById('workers-skills').value;
    params.languages = document.getElementById('workers-languages').value;
    params.availability = document.getElementById('workers-availability').value;
  } else if (tab === 'companies') {
    params.q = document.getElementById('companies-search').value;
  }

  const queryStr = new URLSearchParams(params).toString();
  const api = `../api/${tab}.php?${queryStr}`;
  const r = await fetch(api, { credentials: 'same-origin' });
  const j = await safeJsonResponse(r);
  listEl.innerHTML = '';

  if (j.success && Array.isArray(j.data)) {
    j.data.slice(0,6).forEach(item => {
      const col = document.createElement('div');
      col.className = 'col-md-4';
      const title = item.email || ((item.first_name || '') + ' ' + (item.last_name || '')).trim() || 'N/A';
      const details = item.role_name || item.status || item.location || 'No details';
      const desc = item.bio || item.skills || 'No bio';
      let viewUrl = "#";
      if (tab === "workers") {
        const wid = item.id || item.worker_id || 0;
        viewUrl = "worker_view.php?worker_id=" + encodeURIComponent(wid);
      } else if (tab === "agencies") {
        const aid = item.id || item.user_id || 0;
        viewUrl = "agency_view.php?agency_id=" + encodeURIComponent(aid);
      } else if (tab === "companies") {
        const cid = item.id || item.user_id || 0;
        viewUrl = "company_view.php?company_id=" + encodeURIComponent(cid);
      }

      col.innerHTML = `
        <div class="dashboard-list-box-static">
          <div class="featured-image" style="background-image:url('assets/images/100x100.jpg')"></div>
          <div class="box-text-clear">
            <h4>${title}</h4>
            <div>${details}</div>
            <p>${desc}</p>
            <div class="buttons-to-right">
              <a href="${viewUrl}" class="button small gray" target="_blank" rel="noopener"><i class="fa fa-eye"></i> View</a>
              ${tab === "workers" ? '<a href="#" class="button small" style="background:#c0392b;margin-left:6px;" onclick="deleteWorkerByUserId(' + encodeURIComponent(item.user_id || 0) + ');return false;"><i class="fa fa-trash"></i> Delete</a>' : ''}
            </div>
          </div>
        </div>
      `;
      listEl.appendChild(col);
    });
  } else {
    listEl.innerHTML = '<div class="col-md-12"><p>No data found.</p></div>';
  }
}

async function loadPaymentApprovals() {
  const listEl = document.getElementById("payments-list");
  const listElInvoices = document.getElementById("invoices-list");
  if (!listEl && !listElInvoices) return;

  if (listEl) listEl.innerHTML = '<div class="col-md-12"><p>Loading...</p></div>';
  if (listElInvoices) listElInvoices.innerHTML = '<div class="col-md-12"><p>Loading...</p></div>';
  const r = await fetch("../api/payment_admin.php", { credentials: "same-origin" });
  const j = await safeJsonResponse(r);
  if (listEl) listEl.innerHTML = "";
  if (listElInvoices) listElInvoices.innerHTML = "";

  if (!j.success || !j.data || !Array.isArray(j.data.invoices)) {
    if (listEl) listEl.innerHTML = '<div class="col-md-12"><p>No invoices found.</p></div>';
    if (listElInvoices) listElInvoices.innerHTML = '<div class="col-md-12"><p>No invoices found.</p></div>';
    return;
  }

  const invoices = j.data.invoices;
  if (invoices.length === 0) {
    if (listEl) listEl.innerHTML = '<div class="col-md-12"><p>No invoices found.</p></div>';
    if (listElInvoices) listElInvoices.innerHTML = '<div class="col-md-12"><p>No invoices found.</p></div>';
    return;
  }

  invoices.forEach(item => {
    const col = document.createElement("div");
    col.className = "col-md-6";
    const canAct = item.status === "pending";
    const owner = item.company_email || item.agency_email || "n/a";
    col.innerHTML = `
      <div class="dashboard-list-box-static">
        <h4 style="margin-bottom:8px;">Invoice #${item.id}</h4>
        <p><strong>Type:</strong> ${item.invoice_type || "-"}</p>
        <p><strong>Owner:</strong> ${owner}</p>
        <p><strong>Plan:</strong> ${item.plan_code || "-"}</p>
        <p><strong>Amount:</strong> $${item.amount_due || "0"}</p>
        <p><strong>Status:</strong> ${item.status || "-"}</p>
        <button class="btn btn-sm btn-success" ${canAct ? "" : "disabled"} data-action="confirm_invoice" data-id="${item.id}">Accept</button>
        <button class="btn btn-sm btn-danger" ${canAct ? "" : "disabled"} data-action="reject_invoice" data-id="${item.id}" style="margin-left:8px;">Decline</button>
      </div>
    `;
    if (listEl) listEl.appendChild(col.cloneNode(true));
    if (listElInvoices) listElInvoices.appendChild(col);
  });

  const actionRoots = [listEl, listElInvoices].filter(Boolean);
  actionRoots.forEach(root => {
    root.querySelectorAll("button[data-id]").forEach(btn => {
      btn.addEventListener("click", async function() {
        const invoiceId = parseInt(this.getAttribute("data-id"), 10);
        const action = this.getAttribute("data-action");
        this.disabled = true;
        const r2 = await fetch("../api/payment_admin.php", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "same-origin",
          body: JSON.stringify({ action: action, invoice_id: invoiceId, csrf: window.APP.csrf })
        });
        const j2 = await safeJsonResponse(r2);
        if (!j2.success) {
          alert(j2.error || "Action failed");
        }
        loadPaymentApprovals();
      });
    });
  });
}

async function loadDetailedMatches() {
  const body = document.getElementById("adminMatchesBody");
  if (!body) return;
  body.innerHTML = '<tr><td colspan="6">Loading...</td></tr>';

  try {
    const r = await fetch("../api/matches.php?global=1", { credentials: "same-origin" });
    const j = await safeJsonResponse(r);
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      body.innerHTML = '<tr><td colspan="6">No matches found.</td></tr>';
      return;
    }

    body.innerHTML = "";
    j.data.forEach(m => {
      const tr = document.createElement("tr");
      const worker = m.worker_name || (((m.first_name || "") + " " + (m.last_name || "")).trim()) || ("Worker #" + (m.worker_id || ""));
      const company = m.company_name_full || m.company_name || m.company_email || ("Company #" + (m.company_id || ""));
      const matchedBy = m.matched_by_name || ("User #" + (m.matched_by || ""));
      const matchedFor = m.matched_for_name || ("User #" + (m.matched_for || ""));
      const createdAt = m.created_at || "-";

      tr.innerHTML =
        "<td>" + (m.id || "") + "</td>" +
        "<td>" + worker + "</td>" +
        "<td>" + company + "</td>" +
        "<td>" + matchedBy + "</td>" +
        "<td>" + matchedFor + "</td>" +
        "<td>" + createdAt + "</td>";
      body.appendChild(tr);
    });
  } catch (e) {
    body.innerHTML = '<tr><td colspan="6">Failed to load matches.</td></tr>';
  }
}

async function deleteWorkerByUserId(userId) {
  userId = parseInt(userId, 10);
  if (!userId || userId <= 0) {
    alert("Invalid worker user ID.");
    return;
  }
  if (!confirm("Delete this worker account? This action cannot be undone.")) return;

  const r = await fetch("../api/users.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({
      action: "delete",
      user_id: userId,
      csrf: window.APP.csrf
    })
  });
  const j = await safeJsonResponse(r);
  if (!j.success) {
    alert(j.error || "Delete failed");
    return;
  }
  alert("Worker deleted.");
  loadAdminTab("workers");
}

async function loadCategories() {
  const list = document.getElementById("admin-categories-list");
  if (!list) return;
  list.innerHTML = '<div class="col-md-12"><p>Loading categories...</p></div>';
  try {
    const r = await fetch("../api/skills.php", { credentials: "same-origin" });
    const j = await safeJsonResponse(r);
    if (!j.success || !Array.isArray(j.data)) {
      list.innerHTML = '<div class="col-md-12"><p>Failed to load categories.</p></div>';
      return;
    }
    if (j.data.length === 0) {
      list.innerHTML = '<div class="col-md-12"><p>No categories found.</p></div>';
      return;
    }
    list.innerHTML = "";
    j.data.forEach(function(skill){
      const col = document.createElement("div");
      col.className = "col-md-4";
      col.innerHTML =
        '<div class="dashboard-list-box-static">' +
          '<h4 style="margin-bottom:8px;">' + String(skill.name || ("Category #" + (skill.id || ""))) + '</h4>' +
          '<p>ID: ' + (skill.id || "-") + '</p>' +
          '<a href="#" class="button small" style="background:#c0392b;" onclick="deleteCategoryById(' + encodeURIComponent(skill.id || 0) + ');return false;"><i class="fa fa-trash"></i> Delete Category</a>' +
        '</div>';
      list.appendChild(col);
    });
  } catch (e) {
    list.innerHTML = '<div class="col-md-12"><p>Request failed.</p></div>';
  }
}

async function deleteCategoryById(skillId) {
  skillId = parseInt(skillId, 10);
  if (!skillId || skillId <= 0) {
    alert("Invalid skill ID.");
    return;
  }
  if (!confirm("Delete category (skill) #" + skillId + "?")) return;

  const r = await fetch("../api/skills.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({
      action: "delete",
      skill_id: skillId,
      csrf: window.APP.csrf
    })
  });
  const j = await safeJsonResponse(r);
  if (!j.success) {
    alert(j.error || "Delete failed");
    return;
  }
  alert("Category deleted.");
  loadCategories();
}

async function loadResetRequests() {
  const listEl = document.getElementById("reset-requests-list");
  if (!listEl) return;

  listEl.innerHTML = '<div class="col-md-12"><p>Loading...</p></div>';
  const r = await fetch("../api/password_reset_admin.php", { credentials: "same-origin" });
  const j = await safeJsonResponse(r);
  listEl.innerHTML = "";

  if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
    listEl.innerHTML = '<div class="col-md-12"><p>No reset requests.</p></div>';
    return;
  }

  j.data.forEach(item => {
    const col = document.createElement("div");
    col.className = "col-md-6";
    const canGenerate = item.status === "pending";

    col.innerHTML = `
      <div class="dashboard-list-box-static">
        <h4 style="margin-bottom:8px;">${item.email}</h4>
        <p>Status: <strong>${item.status}</strong></p>
        <p>Requested: ${item.requested_at || '-'}</p>
        <button class="btn btn-sm btn-primary" ${canGenerate ? '' : 'disabled'} data-id="${item.id}">Generate Temp Password</button>
      </div>
    `;
    listEl.appendChild(col);
  });

  listEl.querySelectorAll("button[data-id]").forEach(btn => {
    btn.addEventListener("click", async function() {
      const requestId = parseInt(this.getAttribute("data-id"), 10);
      this.disabled = true;

      const r2 = await fetch("../api/password_reset_admin.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ action: "generate", request_id: requestId, csrf: window.APP.csrf })
      });
      const j2 = await safeJsonResponse(r2);

      if (!j2.success) {
        alert(j2.error || "Failed");
        this.disabled = false;
        return;
      }

      loadResetRequests();
    });
  });
}

</script>
</body>
</html>
