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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$isAdminOrModerator = ($roleId === 1 || $roleId === 5);
$isAgency = ($roleId === 3);

if (!$isAdminOrModerator && !$isAgency) {
    http_response_code(403);
    exit("Forbidden");
}

if ($isAgency) {
    $stmt = $pdo->prepare("
        SELECT
            wd.id,
            wd.worker_id,
            wd.agency_id,
            wd.consent_path,
            wd.passport_path,
            wd.diploma_path,
            wd.invitation_letter_path,
            wd.offer_letter_path,
            wd.created_at,
            wd.updated_at,
            w.first_name,
            w.last_name,
            u.email AS worker_email
        FROM worker_documents wd
        LEFT JOIN workers w ON w.id = wd.worker_id
        LEFT JOIN users u ON u.id = w.user_id
        WHERE wd.agency_id = ?
        ORDER BY wd.updated_at DESC, wd.created_at DESC, wd.id DESC
    ");
    $stmt->execute([(int)($user["id"] ?? 0)]);
} else {
    $stmt = $pdo->query("
        SELECT
            wd.id,
            wd.worker_id,
            wd.agency_id,
            wd.consent_path,
            wd.passport_path,
            wd.diploma_path,
            wd.invitation_letter_path,
            wd.offer_letter_path,
            wd.created_at,
            wd.updated_at,
            w.first_name,
            w.last_name,
            u.email AS worker_email
        FROM worker_documents wd
        LEFT JOIN workers w ON w.id = wd.worker_id
        LEFT JOIN users u ON u.id = w.user_id
        ORDER BY wd.updated_at DESC, wd.created_at DESC, wd.id DESC
    ");
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, "UTF-8"); }

function docLink(string $path): string
{
    $path = trim($path);
    if ($path === "") {
        return '<span class="text-muted">N/A</span>';
    }

    $safe = h($path);
    return '<a href="' . $safe . '" target="_blank" rel="noopener">Preview</a>';
}
?>
<!DOCTYPE html>
<html lang="<?= h(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $isAgency ? "Agency Documentation Review" : "Worker Documentation Review" ?> - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/dashboard.css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<style>
  .wrap { max-width: 1200px; margin: 30px auto; }
  .table > thead > tr > th, .table > tbody > tr > td { vertical-align: middle; }
  .muted { color: #777; }
</style>
</head>
<body>
<div class="wrap">
  <div class="clearfix" style="margin-bottom:15px;">
    <h3 style="margin:0;float:left;"><?= $isAgency ? "My Uploaded Worker Documentation" : "Worker Documentation Review" ?></h3>
    <div style="float:right;">
      <a href="<?= $isAgency ? "agency_dashboard.php" : "dashboard.php" ?>" class="btn btn-default"><i class="fa fa-arrow-left"></i> Back to dashboard</a>
    </div>
  </div>

  <?php if (empty($rows)): ?>
    <div class="alert alert-info">No uploaded documentation found.</div>
  <?php else: ?>
    <div class="table-responsive">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>#</th>
            <th>Worker</th>
            <th>Worker Email</th>
            <th>Uploaded By (User ID)</th>
            <th>Consent</th>
            <th>Passport</th>
            <th>Diploma</th>
            <th>Invitation Letter</th>
            <th>Offer Letter</th>
            <th>Updated</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <?php
            $wid = (int)($r["worker_id"] ?? 0);
            $name = trim((string)($r["first_name"] ?? "") . " " . (string)($r["last_name"] ?? ""));
            if ($name === "") $name = "Worker #".$wid;
          ?>
          <tr>
            <td><?= (int)($r["id"] ?? 0) ?></td>
            <td><?= h($name) ?></td>
            <td><?= h($r["worker_email"] ?? "n/a") ?></td>
            <td><?= (int)($r["agency_id"] ?? 0) ?></td>
            <td><?= docLink((string)($r["consent_path"] ?? "")) ?></td>
            <td><?= docLink((string)($r["passport_path"] ?? "")) ?></td>
            <td><?= docLink((string)($r["diploma_path"] ?? "")) ?></td>
            <td><?= docLink((string)($r["invitation_letter_path"] ?? "")) ?></td>
            <td><?= docLink((string)($r["offer_letter_path"] ?? "")) ?></td>
            <td><?= h($r["updated_at"] ?: $r["created_at"] ?: "-") ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
