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

if ($roleId === 3) {
    header("Location: agency_dashboard.php");
    exit;
}
if ($roleId === 4) {
    header("Location: company_dashboard.php");
    exit;
}

$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user['id'] ?? 0));

$termsAcceptedAt = trim((string)($user["terms_accepted_at"] ?? ""));
$mustAcceptTerms = ($termsAcceptedAt === "");
?>
<!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("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">
<li><a href="dashboard.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="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="agencies.php"><i class="fa fa-building"></i> Agencies</a></li>
<li><a href="companies.php"><i class="fa fa-briefcase"></i> Companies</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Matched Workers</a></li>
<?php if ($roleId === 1 || $roleId === 5): ?>
<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>
<?php endif; ?>
<li><a href="terms.php"><i class="fa fa-file-text-o"></i> <?= htmlspecialchars(t("terms_of_use")) ?></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/dashboard.php" class="btn outline-btn">EN</a>
  <a href="../api/lang.php?lang=sr&redirect=../public/dashboard.php" class="btn outline-btn">SR</a>
</div>
<?php if (((int)($user["role_id"] ?? 0)) === 1 || ((int)($user["role_id"] ?? 0)) === 5): ?>
<div class="submit_listing" style="margin-left:10px;">
  <a href="requests_review.php" class="btn outline-btn">Review Requests</a>
</div>
<?php endif; ?>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li class="active"><a href="dashboard.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="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="agencies.php"><i class="fa fa-building"></i> Agencies</a></li>
<li><a href="companies.php"><i class="fa fa-briefcase"></i> Companies</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Matched Workers</a></li>
<?php if ($roleId === 1 || $roleId === 5): ?>
<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>
<?php endif; ?>
<li><a href="terms.php"><i class="fa fa-file-text-o"></i> <?= htmlspecialchars(t("terms_of_use")) ?></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 class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2><?= htmlspecialchars(t("my_listings")) ?></h2></div></div></div>

<div class="row">
<div class="col-lg-12 col-md-12">
<div class="dashboard-list-box">
<h4><?= htmlspecialchars(t("worker_search")) ?></h4>
<div class="padding-20">
<input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
<div class="row">
<div class="col-md-3"><input type="text" id="q" class="form-control" placeholder="<?= htmlspecialchars(t("keywords")) ?>"></div>
<div class="col-md-2"><input type="text" id="skills" class="form-control" placeholder="<?= htmlspecialchars(t("skills")) ?>"></div>
<div class="col-md-2"><input type="text" id="location" class="form-control" placeholder="<?= htmlspecialchars(t("location")) ?>"></div>
<div class="col-md-2">
<select id="status" class="form-control">
<option value=""><?= htmlspecialchars(t("all_statuses")) ?></option>
<option value="slobodan"><?= htmlspecialchars(t("status_slobodan")) ?></option>
<option value="pregovori"><?= htmlspecialchars(t("status_pregovori")) ?></option>
<option value="zaposlen"><?= htmlspecialchars(t("status_zaposlen")) ?></option>
</select>
</div>
<div class="col-md-2">
<select id="country" class="form-control">
<option value=""><?= htmlspecialchars(t("country")) ?></option>
</select>
</div>
<div class="col-md-3"><button class="btn btn-block" id="searchBtn"><?= htmlspecialchars(t("search")) ?></button></div>
</div>
</div>
</div>
</div>
</div>

<div class="row" style="margin-top:20px;">
<div class="col-md-4">
<div class="dashboard-list-box">
<h4><a href="workers.php"><?= htmlspecialchars(t("workers")) ?></a></h4>
<ul id="workersList"></ul>
</div>
</div>
<div class="col-md-4">
<div class="dashboard-list-box">
<h4><a href="requests_review.php"><?= htmlspecialchars(t("my_requests")) ?></a></h4>
<ul id="requestsList"></ul>
</div>
</div>
<div class="col-md-4">
<div class="dashboard-list-box">
<h4><a href="match_history.php"><?= htmlspecialchars(t("matches")) ?></a></h4>
<ul id="matchesList"></ul>
</div>
</div>
</div>
</div>
</div>
</div>

<div class="modal fade" id="termsModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog" role="document" style="margin-top:80px;">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title"><?= htmlspecialchars(t("terms_of_use")) ?></h4>
      </div>
      <div class="modal-body">
        <p>Please review and accept the Terms of Use to continue.</p>
        <p><a href="terms.php" target="_blank" rel="noopener">Open Terms of Use</a></p>
        <label style="font-weight:normal;display:flex;align-items:center;gap:8px;">
          <input type="checkbox" id="termsAcceptCheckbox" value="1">
          I have read and accept the Terms of Use.
        </label>
        <div id="termsAcceptMsg" style="margin-top:8px;color:#b94a48;"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="acceptTermsBtn">Accept and Continue</button>
      </div>
    </div>
  </div>
</div>

<script>
window.APP = { 
  csrf: document.getElementById("csrf_token").value, 
  userId: <?= (int)$user["id"] ?>,
  roleId: <?= (int)($user["role_id"] ?? 0) ?>,
  mustAcceptTerms: <?= $mustAcceptTerms ? "true" : "false" ?>
};

function getWorkerLabel(w) {
  const first = (w.first_name || "").trim();
  const last = (w.last_name || "").trim();
  const full = (first + " " + last).trim();
  return full || ("Worker #" + (w.id || ""));
}

function maskName(name, fallbackPrefix) {
  const raw = String(name || "").trim();
  if (!raw) return fallbackPrefix + "***";
  const clean = raw.replace(/\s+/g, " ");
  const first = clean.slice(0, 3);
  return first + "*";
}

function matchDisplayRow(m) {
  const workerFull = m.worker_name 
    || ((m.first_name || "") + " " + (m.last_name || "")).trim() 
    || ("Worker #" + (m.worker_id || ""));
    
  const companySource = m.company_name_full 
    || m.company_name 
    || m.company_email 
    || ("Company #" + (m.company_id || ""));
    
  return {
    workerMasked: maskName(workerFull, "Wor"),
    companyMasked: maskName(companySource, "Com")
  };
}

function applyRoleVisibility() {
  const addAccountBtn = document.querySelector(".submit_listing");
  if (window.APP.roleId !== 1) {
    if (addAccountBtn) addAccountBtn.style.display = "none";
  }

  if (window.APP.roleId === 2 || window.APP.roleId === 3) {
    const requestsBox = document.getElementById("requestsList");
    if (requestsBox && requestsBox.parentElement && requestsBox.parentElement.parentElement) {
      requestsBox.parentElement.parentElement.style.display = "none";
    }
  }
}

async function loadWorkers() {
  const q = encodeURIComponent(document.getElementById("q").value.trim());
  const skills = encodeURIComponent(document.getElementById("skills").value.trim());
  const location = encodeURIComponent(document.getElementById("location").value.trim());
  const status = encodeURIComponent(document.getElementById("status").value);
  const country = encodeURIComponent(document.getElementById("country").value);

  const r = await fetch("../api/workers.php?q=" + q + "&skills=" + skills + "&location=" + location + "&status=" + status + "&country=" + country);
  const j = await r.json();
  const ul = document.getElementById("workersList");
  ul.innerHTML = "";

  if (!j.success || !Array.isArray(j.data)) {
    ul.innerHTML = "<li>Error loading workers</li>";
    return;
  }

  j.data.forEach(w => {
    const li = document.createElement("li");
    li.innerHTML = '<div class="list-box-listing"><div class="list-box-listing-content"><div class="inner">' +
      '<h3>' + (w.first_name || "") + ' ' + (w.last_name || "") + '</h3>' +
      '<span>' + (w.location || "") + ' | ' + (w.status || "") + '</span>' +
      '<div>' + (w.skills || "") + '</div>' +
      '</div></div></div>' +
      '<div class="buttons-to-right">' +
      '<a href="worker_view.php?worker_id=' + encodeURIComponent(w.id) + '" target="_blank" rel="noopener" class="button gray" onclick="viewProfile(' + w.id + ');return false;">View</a>';

    if (window.APP.roleId === 4) {
      li.innerHTML += '<a href="#" class="button" onclick="requestWorker(' + w.id + ');return false;">Request</a>';
    }


    li.innerHTML += '</div>';
    ul.appendChild(li);
  });
}

async function requestWorker(workerId) {
  if (!confirm("Send request for this worker?")) return;

  const payload = { csrf: window.APP.csrf, worker_id: workerId };
  const r = await fetch("../api/requests.php", {
    method: "POST",
    headers: {"Content-Type":"application/json"},
    credentials: "same-origin",
    body: JSON.stringify(payload)
  });
  const j = await r.json().catch(() => ({ success: false, error: "invalid_response" }));
  if (j.success) {
    loadRequests();
    alert("Request sent.");
  } else {
    alert(j.error || "Request failed");
  }
}

async function matchWorker(workerId) {
  if (!confirm("Create match for this worker?")) return;

  const payload = { csrf: window.APP.csrf, worker_id: workerId, status: "new" };
  const r = await fetch("../api/matches.php", {
    method: "POST",
    headers: {"Content-Type":"application/json"},
    credentials: "same-origin",
    body: JSON.stringify(payload)
  });
  const j = await r.json().catch(() => ({ success: false, error: "invalid_response" }));
  if (j.success) {
    loadMatches();
    alert("Match created.");
  } else {
    alert(j.error || "Match failed");
  }
}

async function viewProfile(workerId) {
  await fetch("../api/profile_views.php", {
    method: "POST",
    headers: {"Content-Type":"application/json"},
    credentials: "same-origin",
    body: JSON.stringify({ csrf: window.APP.csrf, worker_id: workerId })
  });
  window.location.href = "worker_view.php?worker_id=" + encodeURIComponent(workerId);
}

async function loadRequests() {
  const ul = document.getElementById("requestsList");
  ul.innerHTML = "";
  try {
    const r = await fetch("../api/requests.php", { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data)) {
      ul.innerHTML = "<li>No requests</li>";
      return;
    }
    j.data.forEach(x => {
      const li = document.createElement("li");
      const company = (x.company_email || "unknown_company");
      const agency = (x.agency_email || "admin");
      li.textContent = getWorkerLabel(x) + " - " + (x.status || "pending") + " | company: " + company + " | agency/admin: " + agency;
      ul.appendChild(li);
    });
  } catch (e) {
    ul.innerHTML = "<li>No requests</li>";
  }
}

async function loadMatches() {
  const ul = document.getElementById("matchesList");
  ul.innerHTML = "";
  try {
    const r = await fetch("../api/matches.php", { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      ul.innerHTML = "<li>No matches</li>";
      return;
    }

    const totalLi = document.createElement("li");
    totalLi.innerHTML = "<strong>Total matches: " + j.data.length + "</strong>";
    ul.appendChild(totalLi);

    j.data.slice(0, 3).forEach(x => {
      const li = document.createElement("li");
      const row = matchDisplayRow(x);
      li.textContent = row.workerMasked + " ↔ " + row.companyMasked;
      ul.appendChild(li);
    });
  } catch (e) {
    ul.innerHTML = "<li>No matches</li>";
  }
}

async function loadCountryFilter() {
  const countrySelect = document.getElementById("country");
  if (!countrySelect) return;
  try {
    const r = await fetch("../api/workers.php", { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data)) return;
    const countries = [...new Set(j.data.map(x => (x.country || "").trim()).filter(Boolean))];
    countries.forEach(c => {
      const op = document.createElement("option");
      op.value = c;
      op.textContent = c;
      countrySelect.appendChild(op);
    });
  } catch (e) {}
}

async function acceptTerms() {
  var checkbox = document.getElementById("termsAcceptCheckbox");
  var msg = document.getElementById("termsAcceptMsg");
  if (!checkbox || !checkbox.checked) {
    if (msg) msg.textContent = "You must accept Terms of Use.";
    return;
  }
  if (msg) msg.textContent = "Saving...";
  try {
    var r = await fetch("../api/terms_accept.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify({
        csrf: window.APP.csrf,
        accepted: 1,
        terms_version: "v1"
      })
    });
    var j = await r.json().catch(function(){ return { success:false, error:"invalid_response" }; });
    if (!j.success) {
      if (msg) msg.textContent = j.error || "Failed to save acceptance.";
      return;
    }
    $("#termsModal").modal("hide");
  } catch (e) {
    if (msg) msg.textContent = "Request failed.";
  }
}

document.getElementById("searchBtn").addEventListener("click", loadWorkers);
applyRoleVisibility();
loadCountryFilter().then(loadWorkers);
loadRequests();
loadMatches();

var acceptBtn = document.getElementById("acceptTermsBtn");
if (acceptBtn) {
  acceptBtn.addEventListener("click", acceptTerms);
}
if (window.APP.mustAcceptTerms) {
  $("#termsModal").modal("show");
}
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
<script src="assets/js/interface.js"></script>
</body>
</html>
