<?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";
require_once "../includes/subscription_guard.php";

requirePageAuth();
$user = getAuthUser();
$redirectSubscription = enforceCompanyAccessOrRedirect($pdo, $user);
if ($redirectSubscription !== null) {
    header("Location: " . $redirectSubscription);
    exit;
}
$roleId = (int)($user["role_id"] ?? 0);
if ($roleId !== 4) {
    http_response_code(403);
    exit("Company 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>Company 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}
.company-card{background:#fff;border:1px solid #ececec;border-radius:8px;padding:15px;margin-bottom:20px}
.company-card h4{margin-top:0;margin-bottom:12px}
.company-card ul{margin:0;padding-left:18px}
.company-card li{margin-bottom:8px}
.hero-box{background:linear-gradient(135deg,#4b6cb7,#182848);color:#fff;border-radius:10px;padding:18px 20px;margin-bottom:20px}
.hero-box p{margin:0;opacity:.95}
@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="company_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="company_dashboard.php"><i class="fa fa-cogs"></i> Company Dashboard</a></li>
<li><a href="workers.php"><i class="fa fa-search"></i> Worker Search</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> 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="company_dashboard.php"><i class="fa fa-cogs"></i> Company Dashboard</a></li>
<li><a href="workers.php"><i class="fa fa-search"></i> Worker Search</a></li>
<li><a href="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Matched 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> Logout</a></li>
</ul>
</div>

<div class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2>Company Dashboard</h2></div></div></div>

<div class="hero-box">
  <h4 style="margin-top:0;">Welcome</h4>
  <p>Manage your open requests, active matches, and agency ratings from one place.</p>
  <div id="subscriptionInfo" style="margin-top:12px;font-size:14px;line-height:1.6;">
    <div>Subscription: <strong id="subStatus">Loading...</strong></div>
    <div>Requests used: <strong id="subUsage">Loading...</strong></div>
    <div>Expires at: <strong id="subExpires">Loading...</strong></div>
    <a id="renewBtn" href="subscription.php" class="btn btn-default btn-sm" style="margin-top:8px;display:none;">Renew Subscription</a>
  </div>
</div>

<div class="row">
  <div class="col-md-6">
    <div class="company-card">
      <h4>Open Requests</h4>
      <ul id="companyRequests"><li>Loading...</li></ul>
    </div>
  </div>
  <div class="col-md-6">
    <div class="company-card">
      <h4>Active Matches</h4>
      <ul id="companyMatches"><li>Loading...</li></ul>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <div class="company-card">
      <h4>Recent Agency Ratings</h4>
      <ul id="companyRatings"><li>Loading...</li></ul>
    </div>
  </div>
</div>

</div>
</div>
</div>

<script>
const userId = <?= (int)$user["id"] ?>;

function safeListItem(text) {
  const li = document.createElement("li");
  li.textContent = text;
  return li;
}

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

async function loadCompanyRequests() {
  const ul = document.getElementById("companyRequests");
  ul.innerHTML = "";
  try {
    const r = await fetch(`../api/requests.php?company_id=${userId}`, { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      ul.appendChild(safeListItem("No open requests."));
      return;
    }
    j.data.forEach(req => {
      const worker = req.worker_name || ("Worker #" + (req.worker_id || ""));
      const status = req.status || "pending";
      const agency = req.agency_name || "Direct";
      ul.appendChild(safeListItem(`${worker} - ${status} (${agency})`));
    });
  } catch (e) {
    ul.appendChild(safeListItem("Failed to load requests."));
  }
}

async function loadCompanyMatches() {
  const ul = document.getElementById("companyMatches");
  ul.innerHTML = "";
  try {
    const r = await fetch(`../api/matches.php?company_id=${userId}`, { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      ul.appendChild(safeListItem("No active matches."));
      return;
    }

    ul.appendChild(safeListItem(`Total matches: ${j.data.length}`));

    j.data.slice(0, 3).forEach(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 || ""));
      const workerMasked = maskName(workerFull, "Wor");
      const companyMasked = maskName(companySource, "Com");
      ul.appendChild(safeListItem(`${workerMasked} ↔ ${companyMasked}`));
    });
  } catch (e) {
    ul.appendChild(safeListItem("Failed to load matches."));
  }
}

async function loadCompanyRatings() {
  const ul = document.getElementById("companyRatings");
  ul.innerHTML = "";
  try {
    const r = await fetch(`../api/ratings.php?company_id=${userId}`, { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: [] }));
    if (!j.success || !Array.isArray(j.data) || j.data.length === 0) {
      ul.appendChild(safeListItem("No ratings available."));
      return;
    }
    j.data.forEach(rat => {
      const agency = rat.agency_email || "Agency";
      const value = rat.rating || "0";
      const comment = rat.comment || "";
      ul.appendChild(safeListItem("Rated " + agency + ": " + value + "/5" + (comment ? ' - "' + comment + '"' : "")));
    });
  } catch (e) {
    ul.appendChild(safeListItem("Failed to load ratings."));
  }
}

async function loadSubscriptionInfo() {
  const statusEl = document.getElementById("subStatus");
  const usageEl = document.getElementById("subUsage");
  const expEl = document.getElementById("subExpires");
  const renewBtn = document.getElementById("renewBtn");

  try {
    const r = await fetch("../api/subscriptions.php", { credentials: "same-origin" });
    const j = await r.json().catch(() => ({ success: false, data: null }));
    if (!j.success || !j.data || !j.data.subscription) {
      statusEl.textContent = "No active subscription";
      usageEl.textContent = "0 / 0";
      expEl.textContent = "N/A";
      renewBtn.style.display = "inline-block";
      return;
    }

    const sub = j.data.subscription;
    const status = String(sub.status || "unknown");
    const limit = parseInt(sub.monthly_request_limit || 0, 10);
    const used = parseInt(sub.requests_used || 0, 10);
    const expiresAt = sub.expires_at || "N/A";

    statusEl.textContent = status;
    usageEl.textContent = `${used} / ${limit} (remaining ${Math.max(0, limit - used)})`;
    expEl.textContent = expiresAt;

    const expired = !expiresAt || (new Date(expiresAt).getTime() < Date.now()) || status !== "active";
    renewBtn.style.display = expired ? "inline-block" : "none";
  } catch (e) {
    statusEl.textContent = "Unavailable";
    usageEl.textContent = "Unavailable";
    expEl.textContent = "Unavailable";
    renewBtn.style.display = "inline-block";
  }
}

loadCompanyRequests();
loadCompanyMatches();
loadCompanyRatings();
loadSubscriptionInfo();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/interface.js"></script>
</body>
</html>
