<?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();
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user['id'] ?? 0));
$roleId = (int)($user["role_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>Match History - 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="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><a href="dashboard.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="match_history.php"><i class="fa fa-link"></i> Match History</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="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("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>Global Match History</h2></div></div></div>

<div class="row">
<div class="col-md-12">
<div class="dashboard-list-box">
<h4>All Matches</h4>
<div class="padding-20">
<div class="row">
<div class="col-md-4">
<select id="statusFilter" class="form-control">
<option value="">All statuses</option>
<option value="new">new</option>
<option value="contacted">contacted</option>
<option value="in_progress">in_progress</option>
<option value="hired">hired</option>
<option value="archived">archived</option>
</select>
</div>
<div class="col-md-2">
<button class="btn btn-block" id="loadBtn">Load</button>
</div>
</div>
</div>
<ul id="historyList"></ul>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
window.APP = {
  roleId: <?= (int)$roleId ?>,
  csrf: "<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>"
};

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

async function loadHistory() {
  const ul = document.getElementById("historyList");
  ul.innerHTML = "<li>Loading...</li>";
  const status = encodeURIComponent(document.getElementById("statusFilter").value || "");
  const url = "../api/matches.php?global=1" + (status ? "&status=" + status : "");
  try {
    const r = await fetch(url, { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    ul.innerHTML = "";
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      ul.innerHTML = "<li>No match history found yet.</li>";
      return;
    }
    const totalLi = document.createElement("li");
    totalLi.innerHTML = "<strong>Total matches: " + j.data.length + "</strong>";
    ul.appendChild(totalLi);

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

    j.data.forEach(function (m) {
      const li = document.createElement("li");
      const workerName = ((m.first_name || "") + " " + (m.last_name || "")).trim() || ("Worker #" + (m.worker_id || ""));
      const companySource = (m.company_name || m.company_email || ("Company #" + (m.company_id || "")));
      const workerMasked = maskName(workerName, "Wor");
      const companyMasked = maskName(companySource, "Com");
      const whoMatched = (window.APP.roleId === 1 || window.APP.roleId === 5)
        ? (workerName + " ↔ " + companySource)
        : (workerMasked + " ↔ " + companyMasked);
      li.innerHTML =
        "<strong>" + esc(whoMatched) + "</strong>" +
        " | status: " + esc(m.status || "new") +
        " | agency: " + esc(m.agency_email || "n/a") +
        " | score: " + esc(m.score || "0") +
        " | matched_at: " + esc(m.created_at || "n/a");
      ul.appendChild(li);
    });
  } catch (e) {
    ul.innerHTML = "<li>Failed to load history</li>";
  }
}

document.getElementById("loadBtn").addEventListener("click", loadHistory);
loadHistory();
</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>
