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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$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><?= $roleId === 3 ? "My Workers" : "Lista radnika" ?> - 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/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">
<style>
.navbar .logo img{max-height:42px;width:auto}
</style>
</head>
<body>
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top" data-spy="affix" data-offset-top="10">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="dashboard.php"><img src="assets/images/logo.png" alt="image"/></a></div>
<button id="menu_slide" data-target="#navigation" aria-expanded="false" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
<span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navigation">
<ul class="nav navbar-nav">
<li><a href="dashboard.php"><?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="workers.php"><?= $roleId === 3 ? "My Workers" : "Radnici" ?></a></li>
<li><a href="agencies.php">Agencije</a></li>
<li><a href="companies.php">Kompanije</a></li>
<li><a href="match_history.php">Matched workers</a></li>
</ul>
<div class="submit_listing">
<a href="profile.php" class="btn outline-btn"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a>
</div>
</div>
</div>
</nav>
</header>

<section id="listing_banner" class="parallex-bg">
<div class="container">
<div class="white-text text-center div_zindex">
<div class="search_form">
<form onsubmit="return false;">
<div class="form-group"><div class="select"><select id="f_status" class="form-control"><option value="">All status</option></select></div></div>
<div class="form-group"><div class="select"><select id="f_country" class="form-control"><option value="">All countries</option></select></div></div>
<div class="form-group"><div class="select"><select id="f_language" class="form-control"><option value="">All languages</option></select></div></div>
<div class="form-group"><div class="select"><select id="f_position" class="form-control"><option value="">All positions</option></select></div></div>
<div class="btn_group"><input type="button" value="Search" class="btn btn-block" id="btnSearch"></div>
</form>
</div>
</div>
</div>
<div class="dark-overlay"></div>
</section>

<section id="inner_pages">
<div class="container">
<div class="listing_header">
<h5><?= $roleId === 3 ? "My Workers" : "Lista radnika" ?></h5>
<div class="layout-switcher"><a href="#" class="active"><i class="fa fa-align-justify"></i></a></div>
</div>
<div class="listview show_listing" id="workersList"></div>
</div>
</section>

<script>
function escapeHtml(v){
  var s = String(v == null ? "" : v);
  s = s.replace(/&/g, "&amp;");
  s = s.replace(/</g, "&lt;");
  s = s.replace(/>/g, "&gt;");
  s = s.replace(/"/g, "&quot;");
  s = s.replace(/'/g, "&#039;");
  return s;
}

function setOptions(id, values, firstText){
  var sel = document.getElementById(id);
  sel.innerHTML = "";
  var first = document.createElement("option");
  first.value = "";
  first.textContent = firstText;
  sel.appendChild(first);
  (values || []).forEach(function(v){
    if (!v) return;
    var op = document.createElement("option");
    op.value = v;
    op.textContent = v;
    sel.appendChild(op);
  });
}

async function loadDropdowns(){
  var res = await fetch("../api/workers.php", { credentials: "same-origin" });
  var json = await res.json().catch(function(){ return { success:false, data:[] }; });
  if (!json.success || !Array.isArray(json.data)) return;

  setOptions("f_status", Array.from(new Set(json.data.map(function(x){ return x.status; }).filter(Boolean))), "All status");
  setOptions("f_country", Array.from(new Set(json.data.map(function(x){ return x.country; }).filter(Boolean))), "All countries");
  setOptions("f_language", Array.from(new Set(json.data.map(function(x){ return x.languages; }).filter(Boolean))), "All languages");
  setOptions("f_position", Array.from(new Set(json.data.map(function(x){ return x.position; }).filter(Boolean))), "All positions");
}

async function loadWorkers(){
  var list = document.getElementById("workersList");
  list.innerHTML = "";

  var qs = new URLSearchParams();
  var status = document.getElementById("f_status").value;
  var country = document.getElementById("f_country").value;
  var language = document.getElementById("f_language").value;
  var position = document.getElementById("f_position").value;
  if (status) qs.set("status", status);
  if (country) qs.set("country", country);
  if (language) qs.set("languages", language);
  if (position) qs.set("position", position);

  var res = await fetch("../api/workers.php?" + qs.toString(), { credentials: "same-origin" });
  var json = await res.json().catch(function(){ return { success:false, data:[] }; });

  if (!json.success || !Array.isArray(json.data) || json.data.length === 0){
    list.innerHTML = '<div class="listing_wrap"><div class="listing_info"><h4>No workers found</h4></div></div>';
    return;
  }

  json.data.forEach(function(w){
    var name = ((w.first_name || "") + " " + (w.last_name || "")).trim();
    if (!name) name = "Worker #" + (w.id || "");
    var html = '';
    html += '<div class="listing_wrap">';
    html +=   '<div class="listing_img">';
    html +=     '<span class="like_post"><i class="fa fa-bookmark-o"></i></span>';
    var workerImg = (w.photo_url && String(w.photo_url).trim() !== "") ? String(w.photo_url).trim() : "assets/images/800x530.jpg";
    html +=     '<a href="worker_view.php?worker_id=' + encodeURIComponent(w.id || 0) + '" target="_blank" rel="noopener"><img src="' + escapeHtml(workerImg) + '" alt="image" onerror="this.onerror=null;this.src=\'assets/images/800x530.jpg\';"></a>';
    html +=   '</div>';
    html +=   '<div class="listing_info">';
    var skillLabel = (w.skill_names && String(w.skill_names).trim() !== "") ? String(w.skill_names).trim() : "";
    if (!skillLabel) {
      var rawSkills = String(w.skills || "").trim();
      if (rawSkills && !/^\d+(?:\s*,\s*\d+)*$/.test(rawSkills)) {
        skillLabel = rawSkills;
      }
    }
    if (!skillLabel) skillLabel = "Worker";
    html +=     '<div class="post_category"><a href="#">' + escapeHtml(skillLabel) + '</a></div>';
    html +=     '<h4><a href="worker_view.php?worker_id=' + encodeURIComponent(w.id || 0) + '" target="_blank" rel="noopener">' + escapeHtml(name) + '</a></h4>';
    html +=     '<div class="listing_review_info">';
    html +=       '<p><span class="review_score">' + escapeHtml(w.status || "n/a") + '</span></p>';
    html +=       '<p class="listing_map_m"><i class="fa fa-map-marker"></i> ' + escapeHtml(w.country || "n/a") + '</p>';
    if (w.position) {
      html +=     '<p class="listing_map_m"><i class="fa fa-briefcase"></i> ' + escapeHtml(w.position) + '</p>';
    }
    html +=     '</div>';
    html +=   '</div>';
    html += '</div>';
    list.insertAdjacentHTML("beforeend", html);
  });
}

document.getElementById("btnSearch").addEventListener("click", loadWorkers);
loadDropdowns().then(loadWorkers);
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/interface.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
</body>
</html>
