<?php
declare(strict_types=1);

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'config.php';
require_once 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Mpdf\Mpdf;

header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");

function generate_csrf_token(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validate_csrf(): bool {
    return !empty($_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token']);
}

function set_flash(string $type, string $message): void {
    $_SESSION['flash'] = compact('type', 'message');
}

function get_flash(): ?array {
    if (!isset($_SESSION['flash'])) return null;
    $f = $_SESSION['flash'];
    unset($_SESSION['flash']);
    return $f;
}

if (!isset($_SESSION['user_id'], $_SESSION['role'])) {
    die("Session expired. <a href='index.php'>Login Again</a>");
}

$user_id = (int)$_SESSION['user_id'];
$role    = strtolower(trim($_SESSION['role']));
$username_session = $_SESSION['username'] ?? 'Admin';

if (!in_array($role, ['hr', 'admin', 'hr_admin', 'superadmin'], true)) {
    die("Access Denied.");
}

$flash = get_flash();

/*
 * NOTE ON SCOPE: this dashboard is role-gated (hr/admin/hr_admin/superadmin),
 * not manager-gated, so it intentionally shows ALL employees' tasks rather
 * than a single manager's direct reports. It does not need the
 * reporting_manager-matching logic used in myteam.php / tasks_manager.php.
 * The Division filter below is a straightforward text-column filter, kept
 * as-is for that reason.
 */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['task_id'], $_POST['status'])) {
    if (!validate_csrf()) {
        set_flash('error', 'Invalid CSRF token. Please try again.');
    } else {
        $task_id    = (int)$_POST['task_id'];
        $new_status = trim($_POST['status']);
        $allowed = ['Pending', 'InProgress', 'Completed', 'Rejected'];
        if (in_array($new_status, $allowed, true)) {
            $stmt = $conn->prepare("UPDATE tasks SET status = ? WHERE task_id = ?");
            $stmt->bind_param("si", $new_status, $task_id);
            if ($stmt->execute()) {
                set_flash('success', 'Status updated successfully.');
            } else {
                set_flash('error', 'Database error: ' . $conn->error);
            }
            $stmt->close();
        } else {
            set_flash('error', 'Invalid status value.');
        }
    }
    $redirect = "task_dashboard.php?" . http_build_query($_GET);
    header("Location: $redirect");
    exit;
}

$status_filter   = $_GET['status']   ?? 'All';
$employee_filter = $_GET['employee'] ?? 'All';
$division_filter = $_GET['division'] ?? 'All';

if (!in_array($status_filter, ['All', 'Pending', 'InProgress', 'Completed', 'Rejected'], true)) {
    $status_filter = 'All';
}
if ($employee_filter !== 'All' && !ctype_digit($employee_filter)) {
    $employee_filter = 'All';
}

function get_tasks(mysqli $conn, string $status, string $employee, string $division): array {
    // GROUP BY t.task_id guards against duplicate rows the same way
    // myteam.php guards against duplicate users when joined tables
    // could otherwise multiply matches.
    $sql = "
        SELECT t.task_id, t.title, t.description, t.due_date, t.created_at, t.status, t.priority,
               CONCAT(u.first_name, ' ', u.last_name) AS employee_name, u.division
        FROM tasks t
        JOIN users u ON t.assigned_to = u.id
        WHERE 1=1
    ";
    $params = []; $types = "";
    if ($status !== 'All')   { $sql .= " AND t.status = ?";      $params[] = $status;          $types .= "s"; }
    if ($employee !== 'All') { $sql .= " AND t.assigned_to = ?"; $params[] = (int)$employee;   $types .= "i"; }
    if ($division !== 'All') { $sql .= " AND u.division = ?";    $params[] = $division;         $types .= "s"; }
    $sql .= " GROUP BY t.task_id ORDER BY t.created_at DESC";
    $stmt = $conn->prepare($sql);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while ($row = $result->fetch_assoc()) $data[] = $row;
    return $data;
}

$tasks     = get_tasks($conn, $status_filter, $employee_filter, $division_filter);
$divisions = $conn->query("SELECT DISTINCT division FROM users WHERE role = 'employee' AND division IS NOT NULL AND division != '' ORDER BY division");
$employees = $conn->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM users WHERE role = 'employee' ORDER BY first_name");

function h($s) { return htmlspecialchars($s ?? '', 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 · Task 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 */
.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 */
.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 */
.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 */
.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; }

/* ALERTS */
.alert {
  padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500;
  display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px;
  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; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

/* CARD */
.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; gap: 8px;
  padding: 16px 20px; border-bottom: 1px solid var(--border);
}
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); }
.card-body { padding: 20px; }

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

/* BUTTONS */
.btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: 8px; border: none; font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif; cursor: pointer; transition: opacity .15s; text-decoration: none; }
.btn-primary { background: #1d4ed8; color: #fff; }
.btn-primary:hover { opacity: .88; }
.btn-success { background: #059669; color: #fff; }
.btn-success:hover { opacity: .88; }
.btn-purple  { background: #7c3aed; color: #fff; }
.btn-purple:hover { opacity: .88; }
.btn-sm { padding: 5px 10px; font-size: 12px; border-radius: 6px; }

/* TABLE */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
thead th { background: #f8fafc; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .6px; color: var(--muted); padding: 10px 14px; border-bottom: 1px solid var(--border); white-space: nowrap; }
tbody td { padding: 12px 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 { background: #f8fafc; }

/* BADGES */
.badge { display: inline-flex; align-items: center; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.badge-Pending    { background: #fef3c7; color: #92400e; }
.badge-InProgress { background: #dbeafe; color: #1e40af; }
.badge-Completed  { background: #d1fae5; color: #065f46; }
.badge-Rejected   { background: #fee2e2; color: #991b1b; }
.priority-high   { color: #dc2626; font-weight: 600; }
.priority-medium { color: #d97706; }
.priority-low    { color: #059669; }

.no-tasks { text-align: center; padding: 48px; color: var(--muted); font-size: 14px; }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
}
</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" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <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="digital.php"              class="nav-link"><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 open" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <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 active"><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="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="https://pupa.mypeopleconnect.app/" class="nav-link"><i class="fas fa-id-card"></i> PEP Login</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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Task Dashboard</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); ?>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">Task Management Dashboard</div>
      <div class="page-subtitle">Monitor and update task status across all employees</div>
    </div>

    <?php if ($flash): ?>
      <div class="alert alert-<?php echo $flash['type'] === 'success' ? 'success' : 'danger'; ?>">
        <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo h($flash['message']); ?>
      </div>
    <?php endif; ?>

    <!-- Filters -->
    <div class="card">
      <div class="card-header">
        <i class="fas fa-filter" style="color:var(--muted)"></i>
        <div class="card-title">Filters &amp; Export</div>
      </div>
      <div class="card-body">
        <form method="GET">
          <div class="filter-row">
            <div class="filter-group">
              <label class="filter-label">Division</label>
              <select name="division" class="form-select">
                <option value="All">All Divisions</option>
                <?php while ($d = $divisions->fetch_assoc()): ?>
                  <option value="<?php echo h($d['division']); ?>" <?php echo $division_filter === $d['division'] ? 'selected' : ''; ?>>
                    <?php echo h($d['division']); ?>
                  </option>
                <?php endwhile; ?>
              </select>
            </div>
            <div class="filter-group">
              <label class="filter-label">Status</label>
              <select name="status" class="form-select">
                <option value="All">All</option>
                <?php foreach (['Pending','InProgress','Completed','Rejected'] as $s): ?>
                  <option value="<?php echo $s; ?>" <?php echo $status_filter === $s ? 'selected' : ''; ?>>
                    <?php echo $s === 'InProgress' ? 'In Progress' : $s; ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="filter-group">
              <label class="filter-label">Employee</label>
              <select name="employee" class="form-select">
                <option value="All">All Employees</option>
                <?php while ($e = $employees->fetch_assoc()): ?>
                  <option value="<?php echo $e['id']; ?>" <?php echo $employee_filter == $e['id'] ? 'selected' : ''; ?>>
                    <?php echo h($e['name']); ?>
                  </option>
                <?php endwhile; ?>
              </select>
            </div>
            <div style="display:flex;gap:8px;align-items:flex-end;">
              <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Filter</button>
              <a href="?<?php echo http_build_query([...$_GET, 'export' => 'excel']); ?>" class="btn btn-success"><i class="fas fa-file-excel"></i> Excel</a>
              <a href="?<?php echo http_build_query([...$_GET, 'export' => 'pdf']); ?>"   class="btn btn-purple"><i class="fas fa-file-pdf"></i> PDF</a>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- Table -->
    <div class="card">
      <div class="card-header">
        <i class="fas fa-tasks" style="color:var(--muted)"></i>
        <div class="card-title">Tasks <span style="color:var(--muted);font-weight:400;font-size:13px;">(<?php echo count($tasks); ?> records)</span></div>
      </div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Division</th><th>Employee</th><th>Title</th><th>Description</th>
              <th>Priority</th><th>Created</th><th>Due Date</th><th>Status</th><th>Change Status</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($tasks): ?>
            <?php foreach ($tasks as $row): ?>
              <tr>
                <td><?php echo h($row['division'] ?: '—'); ?></td>
                <td><?php echo h($row['employee_name']); ?></td>
                <td><?php echo h($row['title'] ?: '—'); ?></td>
                <td title="<?php echo h($row['description'] ?? ''); ?>">
                  <?php echo h(substr($row['description'] ?? '', 0, 80)) . (strlen($row['description'] ?? '') > 80 ? '…' : ''); ?>
                </td>
                <td class="priority-<?php echo strtolower($row['priority'] ?? 'medium'); ?>">
                  <?php echo h(ucfirst($row['priority'] ?? '—')); ?>
                </td>
                <td><?php echo $row['created_at'] ? date('d M Y', strtotime($row['created_at'])) : '—'; ?></td>
                <td><?php echo $row['due_date']   ? date('d M Y', strtotime($row['due_date']))   : '—'; ?></td>
                <td><span class="badge badge-<?php echo h($row['status']); ?>"><?php echo h($row['status']); ?></span></td>
                <td>
                  <form method="POST" style="display:flex;gap:6px;align-items:center;">
                    <input type="hidden" name="csrf_token" value="<?php echo generate_csrf_token(); ?>">
                    <input type="hidden" name="task_id" value="<?php echo $row['task_id']; ?>">
                    <select name="status" class="form-select" style="height:32px;font-size:12px;min-width:120px;">
                      <?php foreach (['Pending','InProgress','Completed','Rejected'] as $opt): ?>
                        <option value="<?php echo $opt; ?>" <?php echo $row['status'] === $opt ? 'selected' : ''; ?>>
                          <?php echo $opt === 'InProgress' ? 'In Progress' : $opt; ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                    <button type="submit" class="btn btn-primary btn-sm">Update</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr><td colspan="9" class="no-tasks"><i class="fas fa-inbox" style="font-size:32px;margin-bottom:8px;display:block;"></i>No tasks found with current filters.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

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

<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');
}
</script>
</body>
</html>