<?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) {
    http_response_code(403);
    exit("Agency only");
}
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user["id"] ?? 0));
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Agency 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 href="assets/css/font-awesome.min.css" rel="stylesheet">
<style>
.navbar .logo img{max-height:40px;width:auto;display:block}
#header .navbar-header{display:flex;align-items:center}
#navigation{display:flex;align-items:center;justify-content:flex-end}
.agency-hero{background:#f7f9fc;border:1px solid #eceff5;border-radius:10px;padding:18px 20px;margin-bottom:20px}
.agency-card{background:#fff;border:1px solid #ececec;border-radius:8px;padding:15px;margin-bottom:20px}
.agency-card h4{margin-top:0;margin-bottom:12px}
.agency-card ul{margin:0;padding-left:18px}
.agency-card li{margin-bottom:8px}
@media (max-width:767px){
  .navbar .logo img{max-height:34px}
}
</style>
</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="agency_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" 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="agency_dashboard.php"><i class="fa fa-cogs"></i> Agency Dashboard</a></li>
<li><a href="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> My Profile</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Match History</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>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li class="active"><a href="agency_dashboard.php"><i class="fa fa-cogs"></i> Agency Dashboard</a></li>
<li><a href="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> 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 class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2>Agency Dashboard</h2></div></div></div>

<div class="agency-hero">
  <h4 style="margin-top:0;">Agency Overview</h4>
  <p style="margin:0;">Track your worker requests and all active matches in one place.</p>
  <div style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;">
    <a href="nalog.php" class="btn btn-primary"><i class="fa fa-plus-circle"></i> Add Worker</a>
    <a href="agency_documents.php" class="btn btn-default"><i class="fa fa-file-text-o"></i> Add Documentation</a>
    <a href="worker_documents_review.php" class="btn btn-default"><i class="fa fa-folder-open-o"></i> Review Documentation</a>
  </div>
</div>

<div class="row">
<div class="col-md-6">
<div class="agency-card">
<h4>Agency Requests</h4>
<ul id="agencyRequests"><li>Loading...</li></ul>
</div>
</div>
<div class="col-md-6">
<div class="agency-card">
<h4>Agency Matches</h4>
<ul id="agencyMatches"><li>Loading...</li></ul>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
function safeLi(text) {
  var li = document.createElement("li");
  li.textContent = text;
  return li;
}

function maskName(name, fallbackPrefix) {
  var raw = String(name || "").trim();
  if (!raw) return fallbackPrefix + "***";
  return raw.slice(0, 3) + "*";
}

async function loadAgencyRequests(){
  var ul = document.getElementById("agencyRequests");
  ul.innerHTML = "";
  try {
    var r = await fetch("../api/requests.php", { credentials:"same-origin" });
    var j = await r.json().catch(function(){ return { success:false, data:[] }; });
    if(!j.success || !Array.isArray(j.data) || j.data.length === 0){
      ul.appendChild(safeLi("No requests."));
      return;
    }
    j.data.forEach(function(x){
      var workerName = ((x.first_name || "") + " " + (x.last_name || "")).trim();
      if (!workerName) {
        workerName = "Worker #" + (x.worker_id || "");
      }
      var li = safeLi(workerName + " - " + (x.status || "pending"));
      if (String(x.status || "").toLowerCase() === "approved") {
        var a = document.createElement("a");
        a.href = "agency_documents.php?request_id=" + encodeURIComponent(x.id || 0) + "&worker_id=" + encodeURIComponent(x.worker_id || 0);
        a.style.marginLeft = "8px";
        a.textContent = "[Upload docs]";
        li.appendChild(a);
      }
      ul.appendChild(li);
    });
  } catch (e) {
    ul.appendChild(safeLi("Failed to load requests."));
  }
}

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

    ul.appendChild(safeLi("Total matches: " + j.data.length));

    j.data.slice(0, 3).forEach(function(x){
      var workerName = x.worker_name || ((x.first_name || "") + " " + (x.last_name || "")).trim() || ("Worker #" + (x.worker_id || ""));
      var companySource = x.company_name_full || x.company_name || x.company_email || ("Company #" + (x.company_id || ""));
      var workerMasked = maskName(workerName, "Wor");
      var companyMasked = maskName(companySource, "Com");
      ul.appendChild(safeLi(workerMasked + " ↔ " + companyMasked));
    });
  } catch (e) {
    ul.appendChild(safeLi("Failed to load matches."));
  }
}
loadAgencyRequests();
loadAgencyMatches();
</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>
