<?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 !== 1 && $roleId !== 5) {
    http_response_code(403);
    echo "Forbidden";
    exit;
}
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user['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>Requests Review - 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">
<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="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 class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2>Requests Review (Admin/Moderator)</h2></div></div></div>

<div class="dashboard-list-box">
<h4>Pending company requests</h4>
<div class="padding-20">
<input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
<ul id="requestsList"></ul>
</div>
</div>
</div>
</div>
</div>

<script>
window.APP = {
  csrf: document.getElementById("csrf_token").value
};

function esc(s) {
  return String(s || "").replace(/[&<>"']/g, function(ch){
    return ({'&':'&amp;','<':'<','>':'>','"':'"',"'":'&#039;'})[ch];
  });
}

async function loadRequests() {
  const ul = document.getElementById("requestsList");
  ul.innerHTML = "<li>Loading...</li>";

  const r = await fetch("../api/requests.php?status=pending", { 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 pending requests.</li>";
    return;
  }

  ul.innerHTML = "";
  j.data.forEach(x => {
    const li = document.createElement("li");
    li.style.marginBottom = "10px";
    li.innerHTML =
      "<strong>" + esc((x.first_name || "") + " " + (x.last_name || "")) + "</strong>" +
      " | company: " + esc(x.company_email || "unknown_company") +
      " | status: " + esc(x.status || "pending") +
      ' <a href="#" class="button gray" onclick="viewProfile(' + Number(x.worker_id || 0) + ');return false;">View</a>' +
      ' <a href="#" class="button" onclick="matchRequest(' + Number(x.id || 0) + ',' + Number(x.worker_id || 0) + ');return false;">Match</a>' +
      ' <a href="#" class="button" style="background:#c0392b;" onclick="deleteRequest(' + Number(x.id || 0) + ');return false;">Delete</a>';
    ul.appendChild(li);
  });
}

async function viewProfile(workerId) {
  window.open("worker_view.php?worker_id=" + encodeURIComponent(workerId), "_blank", "noopener");
}

async function matchRequest(requestId, workerId) {
  if (!confirm("Create match and mark request approved?")) return;

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

  const rr = await fetch("../api/requests.php", {
    method: "PUT",
    headers: {"Content-Type":"application/json"},
    credentials: "same-origin",
    body: JSON.stringify({ csrf: window.APP.csrf, id: requestId, status: "approved" })
  });
  const rj = await rr.json().catch(() => ({ success: false, error: "invalid_response" }));
  if (!rj.success) {
    alert(rj.error || "Request status update failed");
    return;
  }

  alert("Matched and approved.");
  loadRequests();
}

async function deleteRequest(requestId) {
  if (!confirm("Delete this request?")) return;

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

loadRequests();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
