<?php
session_start();
include 'config.php';
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

ini_set('display_errors', 0);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

date_default_timezone_set('Asia/Kolkata');

error_log("Attempting to access digital.php. Session data: " . print_r($_SESSION, true));

if (!isset($_SESSION['username'], $_SESSION['role'], $_SESSION['user_id'])) {
    $_SESSION['error_message'] = 'Please log in to access the admin dashboard.';
    header("Location: login.php");
    exit();
}

$role = strtolower(trim($_SESSION['role']));
if (!in_array($role, ['admin', 'superadmin'])) {
    $_SESSION['error_message'] = 'Unauthorized access. Admin or Super Admin role required.';
    header("Location: login.php");
    exit();
}

$base_url   = '//' . $_SERVER['HTTP_HOST'] . '/techknow/';
$upload_dir = 'Uploads/';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_email') {
    $email       = mysqli_real_escape_string($conn, $_POST['email']);
    $user_id     = (int)$_POST['user_id'];
    $document_id = (int)$_POST['document_id'];
    $username    = mysqli_real_escape_string($conn, $_POST['username']);
    $title       = mysqli_real_escape_string($conn, $_POST['title']);

    $query = "SELECT u.id, u.username, u.email, COALESCE(ds.status, 'Not Read') AS status, d.title 
              FROM users u 
              LEFT JOIN document_status ds ON u.id = ds.employee_id AND ds.document_id = ?
              JOIN documents d ON d.id = ?
              WHERE u.id = ? AND LOWER(u.role) = 'employee'";
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        $_SESSION['error_message'] = "Database error: Unable to verify user/document.";
    } else {
        $stmt->bind_param("iii", $document_id, $document_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        if ($user && $user['status'] !== 'Acknowledged') {
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host       = 'smtp.gmail.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'prabhakaran.cirs@gmail.com';
                $mail->Password   = 'rvlgkmpmyugdswqp';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port       = 587;
                $mail->CharSet    = 'UTF-8';
                $mail->Encoding   = 'base64';
                $mail->setFrom('prabhakaran.cirs@gmail.com', 'Mypeopleconnect Admin');
                $mail->addAddress($email, $username);
                $mail->Subject = 'Reminder: Acknowledge Document - ' . $title;
                $mail->Body    = "Dear $username,\n\nPlease review and acknowledge the document '$title' in the Mypeopleconnect portal.\n\nThank you,\nMypeopleconnect Team";
                $mail->isHTML(false);

                $documentPath = "$upload_dir/document_{$document_id}_{$user_id}.pdf";
                $cmd = "php generate_pdf.php $document_id $user_id " . escapeshellarg($documentPath);
                exec($cmd, $output, $return_var);

                if (file_exists($documentPath)) {
                    $mail->addAttachment($documentPath);
                }

                if ($mail->send()) {
                    $_SESSION['message'] = "Reminder email sent successfully to $username.";
                } else {
                    $_SESSION['error_message'] = "Failed to send reminder email to $username.";
                }
            } catch (Exception $e) {
                $_SESSION['error_message'] = "Failed to send reminder email: " . htmlspecialchars($e->getMessage());
            }
        } else {
            $_SESSION['error_message'] = "Cannot send reminder: User not found or document already acknowledged.";
        }
    }
    header("Location: digital.php");
    exit();
}

$debug_info     = [];
$user_count     = $conn->query("SELECT COUNT(*) AS count FROM users WHERE LOWER(role) = 'employee'")->fetch_assoc()['count'] ?? 0;
$document_count = $conn->query("SELECT COUNT(*) AS count FROM documents")->fetch_assoc()['count'] ?? 0;
$status_count   = $conn->query("SELECT COUNT(*) AS count FROM document_status")->fetch_assoc()['count'] ?? 0;

$titles = [];
$titles_sql = "SELECT DISTINCT title FROM documents ORDER BY title";
if ($titles_result = $conn->query($titles_sql)) {
    while ($row = $titles_result->fetch_assoc()) { $titles[] = $row['title']; }
    $titles_result->free();
}

$statuses = ['Not Read', 'Read', 'Acknowledged'];
$statuses_sql = "SELECT DISTINCT COALESCE(status, 'Not Read') AS status FROM document_status";
if ($statuses_result = $conn->query($statuses_sql)) {
    while ($row = $statuses_result->fetch_assoc()) {
        if (!in_array($row['status'], $statuses)) { $statuses[] = $row['status']; }
    }
    $statuses_result->free();
}

$usernames = [];
$usernames_sql = "SELECT DISTINCT username FROM users WHERE LOWER(role) = 'employee' ORDER BY username";
if ($usernames_result = $conn->query($usernames_sql)) {
    while ($row = $usernames_result->fetch_assoc()) { $usernames[] = $row['username']; }
    $usernames_result->free();
}

$activity_sql = "SELECT 
                    d.id   AS document_id, 
                    d.title, 
                    u.username, 
                    u.email, 
                    u.id   AS user_id,
                    COALESCE(ds.status, 'Not Read') AS status,
                    ds.acknowledged_at
                FROM users u
                CROSS JOIN documents d
                LEFT JOIN (
                    SELECT ds1.employee_id, ds1.document_id, ds1.status, ds1.acknowledged_at
                    FROM document_status ds1
                    WHERE ds1.id = (
                        SELECT MAX(ds2.id)
                        FROM document_status ds2
                        WHERE ds2.employee_id = ds1.employee_id 
                          AND ds2.document_id = ds1.document_id
                    )
                ) AS ds ON ds.document_id = d.id AND ds.employee_id = u.id
                WHERE LOWER(u.role) = 'employee'
                ORDER BY u.username ASC, d.title ASC";

$stmt = $conn->prepare($activity_sql);
$activity_data = [];
if ($stmt) {
    $stmt->execute();
    $activity_result = $stmt->get_result();
    while ($row = $activity_result->fetch_assoc()) { $activity_data[] = $row; }
    $stmt->close();
} else {
    $_SESSION['error_message'] = "Database error: Unable to fetch activity data.";
}

$conn->close();

$username_session = $_SESSION['username'] ?? '';
function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Digital Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;
  --radius: 12px;
  --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  font-family: 'Sora', system-ui, sans-serif;
}

html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

.layout { display: flex; min-height: 100vh; }

.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  cursor: pointer; border: none; background: none; width: 100%; text-align: left;
  transition: background .15s, color .15s;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; border-top: 1px solid rgba(255,255,255,.06); }

.content { flex: 1; margin-left: var(--sidebar-w); min-width: 0; display: flex; flex-direction: column; transition: margin .3s cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }

.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.topbar-spacer { flex: 1; }
.topbar-user { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ink-2); font-weight:500; }
.topbar-avatar {
  width: 30px; height: 30px; border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 20px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 20px; }
.card-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 20px; border-bottom: 1px solid var(--border);
}
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); display: flex; align-items: center; gap: 8px; }
.card-body { padding: 20px; }

.alert {
  padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500;
  display: flex; align-items: flex-start; gap: 10px; margin-bottom: 16px;
  border: 1px solid transparent; animation: fadeUp .25s ease;
}
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: #fee2e2; border-color: #fca5a5; color: #991b1b; }
.alert-warning  { background: #fef3c7; border-color: #fcd34d; color: #92400e; }
.alert-close { margin-left: auto; cursor: pointer; background: none; border: none; font-size: 16px; color: inherit; opacity: .6; padding: 0 4px; }
.alert-close:hover { opacity: 1; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

.btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 7px 14px; border-radius: 8px; border: 1px solid transparent;
  font-size: 12px; font-weight: 600; font-family: 'Sora', sans-serif;
  cursor: pointer; text-decoration: none; transition: opacity .15s; line-height: 1;
}
.btn:hover { opacity: .88; }
.btn-primary   { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
.btn-secondary { background: var(--ink); color: #fff; border-color: var(--ink); }
.btn-sm { padding: 5px 10px; font-size: 11px; border-radius: 6px; }

/* Filter selects */
.filter-bar {
  display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;
  padding: 16px 20px; border-bottom: 1px solid var(--border); background: var(--bg);
}
.filter-group { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 180px; }
.filter-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.filter-select {
  height: 36px; border: 1px solid var(--border); border-radius: 8px;
  padding: 0 10px; font-size: 13px; font-family: 'Sora', sans-serif;
  color: var(--ink); background: var(--surface); outline: none;
  transition: border-color .15s, box-shadow .15s;
}
.filter-select:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,.12); }

/* Table */
.tbl-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
thead th {
  background: var(--ink); color: rgba(255,255,255,.85);
  font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .8px;
  padding: 11px 14px; text-align: left; white-space: nowrap;
}
tbody td { padding: 11px 14px; border-bottom: 1px solid var(--border); color: var(--ink-2); vertical-align: middle; }
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #f8fafc; }

/* Status badges */
.badge {
  display: inline-flex; align-items: center; padding: 3px 10px;
  border-radius: 20px; font-size: 11px; font-weight: 700;
}
.badge-acknowledged { background: #d1fae5; color: #065f46; }
.badge-read         { background: #fef3c7; color: #92400e; }
.badge-not-read     { background: #fee2e2; color: #991b1b; }
.badge-success      { background: #d1fae5; color: #065f46; }
.badge-danger       { background: #fee2e2; color: #991b1b; }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
  .filter-bar { flex-direction: column; }
}
</style>
</head>
<body>
<div class="layout">

<!-- ── SIDEBAR ──────────────────────────────────────────────────────────── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="division_designation.php" class="nav-link"><i class="fas fa-tag"></i>          Division / Designation</a></li>
          <li><a href="digital.php"              class="nav-link active"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="ot_dashboard.php"            class="nav-link"><i class="fas fa-hourglass-half"></i>   OT Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="manager_hr_leave_apply.php"  class="nav-link"><i class="fas fa-calendar-plus"></i>    Apply Leave</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- ── CONTENT ───────────────────────────────────────────────────────────── -->
<div class="content" id="content">

  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>DAP</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Acceptance Confirmed</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session ?: 'Admin'); ?>
    </div>
  </div>

  <div class="page">

    <div class="page-header">
      <div class="page-title">Digital Dashboard</div>
      <div class="page-subtitle">Monitor document acknowledgment status across all employees</div>
    </div>

    <?php if (isset($_SESSION['error_message'])): ?>
      <div class="alert alert-danger" id="flashMsg">
        <i class="fas fa-exclamation-circle"></i>
        <span><?php echo h($_SESSION['error_message']); unset($_SESSION['error_message']); ?></span>
        <button class="alert-close" onclick="this.closest('.alert').remove()">×</button>
      </div>
    <?php endif; ?>
    <?php if (isset($_SESSION['message'])): ?>
      <div class="alert alert-success" id="flashMsg">
        <i class="fas fa-check-circle"></i>
        <span><?php echo h($_SESSION['message']); unset($_SESSION['message']); ?></span>
        <button class="alert-close" onclick="this.closest('.alert').remove()">×</button>
      </div>
    <?php endif; ?>

    <?php if (empty($activity_data)): ?>
      <div class="alert alert-warning">
        <i class="fas fa-exclamation-triangle"></i>
        <span>No activity records found. Employees: <?php echo $user_count; ?> | Documents: <?php echo $document_count; ?> | Statuses: <?php echo $status_count; ?></span>
      </div>
    <?php endif; ?>

    <!-- Filter card -->
    <div class="card">
      <div class="card-header">
        <div class="card-title"><i class="fas fa-filter"></i> Filter User Activity</div>
      </div>
      <div class="filter-bar">
        <div class="filter-group">
          <span class="filter-label">Document Title</span>
          <select id="titleFilter" class="filter-select" onchange="filterTable()">
            <option value="">All Titles</option>
            <?php foreach ($titles as $title): ?>
              <option value="<?php echo h($title); ?>"><?php echo h($title); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-group">
          <span class="filter-label">Username</span>
          <select id="usernameFilter" class="filter-select" onchange="filterTable()">
            <option value="">All Users</option>
            <?php foreach ($usernames as $username): ?>
              <option value="<?php echo h($username); ?>"><?php echo h($username); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-group">
          <span class="filter-label">Status</span>
          <select id="statusFilter" class="filter-select" onchange="filterTable()">
            <option value="">All Statuses</option>
            <?php foreach ($statuses as $status): ?>
              <option value="<?php echo h($status); ?>"><?php echo h($status); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
    </div>

    <!-- Activity table -->
    <div class="card">
      <div class="card-header">
        <div class="card-title"><i class="fas fa-table"></i> User Activity on Documents</div>
        <span style="font-size:12px;color:var(--muted);font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo count($activity_data); ?> records</span>
      </div>
      <div class="tbl-wrap">
        <table id="activityTable">
          <thead>
            <tr>
              <th>Document Title</th>
              <th>Username</th>
              <th>Status</th>
              <th>Acknowledgment</th>
              <th>Acknowledged At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($activity_data)): ?>
              <tr><td colspan="6" style="text-align:center;color:var(--muted);padding:24px">No activity records found.</td></tr>
            <?php else: ?>
              <?php foreach ($activity_data as $row):
                $status = $row['status'] ?? 'Not Read';
                $is_ack = ($status === 'Acknowledged');
                $ack_display = '—';
                if (!empty($row['acknowledged_at']) && $row['acknowledged_at'] !== '0000-00-00 00:00:00') {
                  $dt = new DateTime($row['acknowledged_at']);
                  $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                  $ack_display = $dt->format('d-m-Y H:i:s');
                }
                $badge_class = match($status) {
                  'Acknowledged' => 'badge-acknowledged',
                  'Read'         => 'badge-read',
                  default        => 'badge-not-read'
                };
              ?>
              <tr>
                <td style="font-weight:600;color:var(--ink)"><?php echo h($row['title']); ?></td>
                <td><?php echo h($row['username']); ?></td>
                <td><span class="badge <?php echo $badge_class; ?>"><?php echo h($status); ?></span></td>
                <td>
                  <span class="badge <?php echo $is_ack ? 'badge-success' : 'badge-danger'; ?>">
                    <?php echo $is_ack ? 'Acknowledged' : 'Not Acknowledged'; ?>
                  </span>
                </td>
                <td style="font-family:'JetBrains Mono',monospace;font-size:12px;color:var(--muted)"><?php echo h($ack_display); ?></td>
                <td>
                  <div style="display:flex;flex-wrap:wrap;gap:5px">
                    <a href="generate_pdf.php?document_id=<?php echo h($row['document_id']); ?>&user_id=<?php echo h($row['user_id']); ?>" class="btn btn-sm btn-primary">
                      <i class="fas fa-download"></i> Download
                    </a>
                    <?php if (!$is_ack): ?>
                      <form action="digital.php" method="post" style="display:inline;">
                        <input type="hidden" name="action" value="send_email">
                        <input type="hidden" name="email" value="<?php echo h($row['email']); ?>">
                        <input type="hidden" name="user_id" value="<?php echo h($row['user_id']); ?>">
                        <input type="hidden" name="document_id" value="<?php echo h($row['document_id']); ?>">
                        <input type="hidden" name="username" value="<?php echo h($row['username']); ?>">
                        <input type="hidden" name="title" value="<?php echo h($row['title']); ?>">
                        <button type="submit" class="btn btn-sm btn-secondary">
                          <i class="fas fa-envelope"></i> Send Reminder
                        </button>
                      </form>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}
document.addEventListener('DOMContentLoaded', function() {
  var fm = document.getElementById('flashMsg');
  if (!fm) return;
  setTimeout(function() {
    fm.style.transition = 'opacity .5s'; fm.style.opacity = '0';
    setTimeout(function() { if (fm.parentNode) fm.parentNode.removeChild(fm); }, 520);
  }, 5000);
});
function filterTable() {
  var titleFilter    = document.getElementById('titleFilter').value.toLowerCase().trim();
  var usernameFilter = document.getElementById('usernameFilter').value.toLowerCase().trim();
  var statusFilter   = document.getElementById('statusFilter').value.toLowerCase().trim();
  var rows = document.querySelectorAll('#activityTable tbody tr');
  rows.forEach(function(row) {
    if (!row.cells || row.cells.length < 3) return;
    var title    = row.cells[0].textContent.toLowerCase().trim();
    var username = row.cells[1].textContent.toLowerCase().trim();
    var status   = row.cells[2].textContent.toLowerCase().trim();
    var show = (!titleFilter || title.includes(titleFilter))
            && (!usernameFilter || username.includes(usernameFilter))
            && (!statusFilter || status.includes(statusFilter));
    row.style.display = show ? '' : 'none';
  });
}
</script>
</body>
</html>