<?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><?= htmlspecialchars(t("add_skill")) ?> - 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">
</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 class="active"><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("add_skill")) ?></h2></div></div></div>

<div class="dashboard-list-box">
<h4><?= htmlspecialchars(t("skills")) ?></h4>
<div class="padding-20">
<div class="row">
<div class="col-md-4">
<label>English</label>
<input type="text" id="skill_en" class="form-control" placeholder="e.g. Welding">
</div>
<div class="col-md-4">
<label>Srpski</label>
<input type="text" id="skill_sr" class="form-control" placeholder="npr. Zavarivanje">
</div>
<div class="col-md-4">
<label>&nbsp;</label>
<button id="addSkillBtn" class="btn btn-block">+ Add</button>
</div>
</div>
<div id="skillMsg" style="margin-top:10px;"></div>
</div>
</div>

<div class="dashboard-list-box" style="margin-top:20px;">
<h4><?= htmlspecialchars(t("skills")) ?> list</h4>
<ul id="skillsList"></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 loadSkills() {
  const r = await fetch('../api/skills.php', { credentials: 'same-origin' });
  const j = await r.json().catch(() => ({ success: false, data: [] }));
  const ul = document.getElementById('skillsList');
  ul.innerHTML = '';

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

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

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

async function addSkill() {
  const en = document.getElementById('skill_en').value.trim();
  const sr = document.getElementById('skill_sr').value.trim();
  const msg = document.getElementById('skillMsg');

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

  const r = await fetch('../api/skills.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 r.json().catch(() => ({ success: false, error: 'invalid_response' }));
  if (j.success) {
    msg.style.color = 'green';
    msg.textContent = 'Skill added.';
    document.getElementById('skill_en').value = '';
    document.getElementById('skill_sr').value = '';
    await loadSkills();
  } else {
    msg.style.color = 'red';
    msg.textContent = j.error || 'Add failed';
  }
}

async function deleteSkill(skillId) {
  const r = await fetch('../api/skills.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    credentials: 'same-origin',
    body: JSON.stringify({
      csrf: window.APP.csrf,
      action: 'delete',
      skill_id: skillId
    })
  });
  const j = await r.json().catch(() => ({ success: false }));
  if (j.success) loadSkills();
}

document.getElementById('addSkillBtn').addEventListener('click', addSkill);
loadSkills();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
