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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
if ($roleId === 3) {
    http_response_code(403);
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Forbidden</title><link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"></head><body style="padding:40px;font-family:Arial,sans-serif;"><h3>Forbidden</h3><p>You do not have access to this page.</p><p><a href="dashboard.php" class="btn btn-primary">Return to Dashboard</a></p></body></html>';
    exit;
}
$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>Companies - 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">
</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>
<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"></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="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><a href="workers.php"><i class="fa fa-users"></i> <?= ($roleId === 3 ? "My Workers" : "Workers") ?></a></li>
<?php if ($roleId !== 3): ?>
<li><a href="agencies.php"><i class="fa fa-building"></i> Agencies</a></li>
<li class="active"><a href="companies.php"><i class="fa fa-briefcase"></i> Companies</a></li>
<?php endif; ?>
<li><a href="match_history.php"><i class="fa fa-link"></i> Match History</a></li>
</ul>
</div>
<div class="dashboard-content">
<div id="titlebar"><h2>All Companies</h2></div>
<div class="dashboard-list-box">
<h4>Company Search</h4>
<div class="padding-20">
<div class="row">
<div class="col-md-4"><select id="companyCountry" class="form-control"><option value="">All countries</option></select></div>
<div class="col-md-4"><select id="companyPlan" class="form-control"><option value="">All subscription plans</option><option value="1">Plan 1</option><option value="2">Plan 2</option><option value="3">Plan 3</option></select></div>
<div class="col-md-4"><button class="btn btn-block" id="companySearchBtn">Search</button></div>
</div>
</div>
<ul id="companiesList"></ul>
</div>
</div>
</div>
</div>

<script>
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 loadCompanyCountries() {
  var r = await fetch("../api/companies.php", { credentials: "same-origin" });
  var j = await r.json().catch(function(){ return { success:false, data:[] }; });
  if (!j.success || !Array.isArray(j.data)) return;
  var countries = Array.from(new Set(j.data.map(function(x){ return x.country; }).filter(Boolean)));
  var s = document.getElementById("companyCountry");
  countries.forEach(function(c){
    var o = document.createElement("option");
    o.value = c;
    o.textContent = c;
    s.appendChild(o);
  });
}

async function loadCompanies() {
  var ul = document.getElementById("companiesList");
  ul.innerHTML = "<li>Loading...</li>";

  var qs = new URLSearchParams();
  var country = document.getElementById("companyCountry").value;
  var plan = document.getElementById("companyPlan").value;
  if (country) qs.set("country", country);
  if (plan) qs.set("plan_id", plan);

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

  if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
    ul.innerHTML = "<li>No companies found</li>";
    return;
  }

  j.data.forEach(function(c){
    var li = document.createElement("li");
    li.innerHTML =
      "<strong>" + esc(c.name || c.email || ("Company #" + (c.id || ""))) + "</strong>" +
      " | country: " + esc(c.country || "n/a") +
      " | plan: " + esc(c.plan_name || "n/a") +
      ' | <a href="company_view.php?company_id=' + encodeURIComponent(c.id || 0) + '" target="_blank" rel="noopener">View profile</a>';
    ul.appendChild(li);
  });
}

document.getElementById("companySearchBtn").addEventListener("click", loadCompanies);
loadCompanyCountries().then(loadCompanies);
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
