<?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";

requirePageAuth();
if (!hasPermission("manage_users")) {
    http_response_code(403);
    exit("Forbidden");
}
$csrf = csrfToken();
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Manage Positions - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/dashboard.css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
</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="admin.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>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li><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="true">
    <i class="fa fa-plus-circle"></i> Admin Actions <span class="caret"></span>
  </a>
  <ul id="adminActionsMenu" class="collapse in 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 class="active"><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>Manage Positions</h2></div></div></div>

<div class="dashboard-list-box">
<h4>Positions</h4>
<div class="padding-20">
<div class="row">
<div class="col-md-5">
<label>Position name (English)</label>
<input type="text" id="position_en" class="form-control" placeholder="e.g. Electrician">
</div>
<div class="col-md-5">
<label>Position name (Serbian)</label>
<input type="text" id="position_sr" class="form-control" placeholder="npr. Električar">
</div>
<div class="col-md-2">
<label>&nbsp;</label>
<button id="addPositionBtn" class="btn btn-block">+ Add</button>
</div>
</div>
<div id="positionMsg" style="margin-top:10px;"></div>
</div>
</div>

<div class="dashboard-list-box" style="margin-top:20px;">
<h4>Position list</h4>
<ul id="positionsList"></ul>
</div>

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

<script>
window.APP = { csrf: "<?= htmlspecialchars($csrf) ?>" };

function escapeHtml(value) {
  return String(value || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

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

async function loadPositions() {
  const r = await fetch("../api/positions.php", { credentials: "same-origin" });
  const j = await safeJson(r);
  const ul = document.getElementById("positionsList");
  ul.innerHTML = "";

  if (!j.success || !Array.isArray(j.data)) {
    ul.innerHTML = "<li>Unable to load positions.</li>";
    return;
  }

  if (j.data.length === 0) {
    ul.innerHTML = "<li>No positions yet.</li>";
    return;
  }

  j.data.forEach(p => {
    const li = document.createElement("li");
    li.innerHTML = "<strong>" + escapeHtml(p.name || "") + "</strong> " +
      '<button class="btn btn-xs btn-danger" style="margin-left:8px;" onclick="deletePosition(' + parseInt(p.id,10) + ')">x</button>';
    ul.appendChild(li);
  });
}

async function addPosition() {
  const en = document.getElementById("position_en").value.trim();
  const sr = document.getElementById("position_sr").value.trim();
  const msg = document.getElementById("positionMsg");

  if (!en || !sr) {
    msg.style.color = "red";
    msg.textContent = "Both English and Serbian are required.";
    return;
  }

  const r = await fetch("../api/positions.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({
      csrf: window.APP.csrf,
      action: "add",
      name_en: en,
      name_sr: sr
    })
  });
  const j = await safeJson(r);

  if (!j.success) {
    msg.style.color = "red";
    msg.textContent = j.error || "Add failed";
    return;
  }

  msg.style.color = "green";
  msg.textContent = "Position added.";
  document.getElementById("position_en").value = "";
  document.getElementById("position_sr").value = "";
  loadPositions();
}

async function deletePosition(positionId) {
  if (!confirm("Delete this position?")) return;

  const r = await fetch("../api/positions.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({
      csrf: window.APP.csrf,
      action: "delete",
      position_id: positionId
    })
  });
  const j = await safeJson(r);
  if (j.success) loadPositions();
}

document.getElementById("addPositionBtn").addEventListener("click", addPosition);
loadPositions();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
