<?php
declare(strict_types=1);

session_start();
require_once 'config.php';

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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'employee') {
    header("Location: login.php");
    exit();
}

$user_id  = (int)$_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'User';
$today    = date('Y-m-d');

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf_token = $_SESSION['csrf_token'];

// Release the PHP session lock on normal page loads. This prevents one open
// request from blocking navigation to other MPC pages for the same employee.
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

if (!function_exists('set_flash')) {
    function set_flash($t, $m) { $_SESSION['flash'] = ['type' => $t, 'msg' => $m]; }
}
if (!function_exists('get_flash')) {
    function get_flash() {
        if (isset($_SESSION['flash'])) { $f = $_SESSION['flash']; unset($_SESSION['flash']); return $f; }
        return null;
    }
}
if (!function_exists('h')) {
    function h($s): string {
        if ($s === null) {
            $s = '';
        } elseif (is_bool($s)) {
            $s = $s ? '1' : '0';
        } elseif (!is_string($s) && !is_numeric($s)) {
            $s = '';
        } else {
            $s = (string)$s;
        }

        return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!isset($conn)) { $conn = $db ?? $mysqli ?? null; }
if (!$conn) die('Database connection configuration not found.');

/* ── POST ACTIONS ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $csrf_token) {
        set_flash('danger', 'Invalid request.');
        header("Location: tasks_employee.php");
        exit();
    }

    $action  = trim($_POST['action'] ?? '');
    $task_id = (int)($_POST['task_id'] ?? 0);

    if ($action === 'start_task' && $task_id > 0) {
        $stmt = $conn->prepare("
            UPDATE tasks
            SET start_time = NOW(),
                status = 'In Progress',
                end_time = NULL,
                time_spent = NULL
            WHERE task_id = ?
              AND assigned_to = ?
              AND status = 'Pending'
              AND (start_time IS NULL OR start_time = '0000-00-00 00:00:00')
        ");
        if (!$stmt) {
            set_flash('danger', 'DB error: ' . $conn->error);
        } else {
            $stmt->bind_param("ii", $task_id, $user_id);
            $stmt->execute();

            if ($stmt->affected_rows > 0) {
                set_flash('success', 'Task started successfully. Status is now In Progress.');
            } else {
                set_flash('warning', 'Task could not be started. It may already be in progress or completed.');
            }

            $stmt->close();
        }
    } elseif ($action === 'save_remarks' && $task_id > 0) {
        $remarks = trim($_POST['remarks'] ?? '');
        if ($remarks === '') {
            set_flash('warning', 'Remark cannot be empty.');
        } else {
            $entry = date('d M Y H:i') . ' — ' . $remarks;
            $stmt = $conn->prepare("UPDATE tasks SET remarks=IF(remarks IS NULL OR remarks='' OR remarks='None', ?, CONCAT(remarks, '\n', ?)) WHERE task_id=? AND assigned_to=?");
            $stmt->bind_param("ssii", $entry, $entry, $task_id, $user_id);
            $stmt->execute() ? set_flash('success', 'Remark saved.') : set_flash('danger', 'Error: ' . $stmt->error);
            $stmt->close();
        }
    } elseif ($action === 'finish_task' && $task_id > 0) {
        $stmt = $conn->prepare("SELECT start_time FROM tasks WHERE task_id=? AND assigned_to=? AND status='In Progress'");
        $stmt->bind_param("ii", $task_id, $user_id);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$row || empty($row['start_time'])) {
            set_flash('warning', 'Task must be in progress to finish it.');
        } else {
            $start = new DateTime($row['start_time']);
            $end   = new DateTime();
            $diff  = $start->diff($end);
            $mins  = max(1, ($diff->days * 1440) + ($diff->h * 60) + $diff->i);
            $stmt = $conn->prepare("
                UPDATE tasks
                SET end_time = NOW(),
                    time_spent = ?,
                    status = 'Completed'
                WHERE task_id = ?
                  AND assigned_to = ?
                  AND status = 'In Progress'
            ");

            if (!$stmt) {
                set_flash('danger', 'DB error: ' . $conn->error);
            } else {
                $stmt->bind_param("iii", $mins, $task_id, $user_id);
                $stmt->execute();

                if ($stmt->affected_rows > 0) {
                    set_flash('success', "Task completed successfully. Time: {$mins} mins.");
                } else {
                    set_flash('warning', 'Task was not completed because it is no longer in progress.');
                }

                $stmt->close();
            }
        }
    }
    // Persist flash data and release the session before redirecting.
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_write_close();
    }
    header("Location: tasks_employee.php");
    exit();
}

/* ── DATA FETCHING ── */
$stmt = $conn->prepare("
    SELECT t.*, ab.first_name AS assigner_first, ab.last_name AS assigner_last, ab.role AS assigner_role
    FROM tasks t
    JOIN users ab ON t.assigned_by = ab.id
    WHERE t.assigned_to = ?
    ORDER BY FIELD(t.status,'In Progress','Pending','Completed'), t.due_date ASC
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$tasks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$active_tasks    = array_filter($tasks, fn($t) => $t['status'] !== 'Completed');
$completed_tasks = array_filter($tasks, fn($t) => $t['status'] === 'Completed');

$total           = count($tasks);
$completed_count = count($completed_tasks);
$inprog_count    = count(array_filter($tasks, fn($t) => $t['status'] === 'In Progress'));
$overdue_count   = count(array_filter($active_tasks, fn($t) => !empty($t['due_date']) && $t['due_date'] < $today));
?>
<!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 · My Tasks</title>
<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"></noscript>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:Inter,Segoe UI,Roboto,Arial,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-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:300;
  display:flex;flex-direction:column;overflow-y:auto;
  transition:transform .28s cubic-bezier(.4,0,.2,1);
  scrollbar-width:none;
}
.sidebar::-webkit-scrollbar{display:none}
.sidebar-brand{padding:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-list{list-style:none;padding:0}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:9px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:16px;text-align:center;font-size:13px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px 8px;border-top:1px solid rgba(255,255,255,.06)}
.sidebar-user-info{display:flex;align-items:center;gap:10px;padding:10px 14px;margin:0 8px 4px;border-radius:8px;background:rgba(255,255,255,.04)}
.sidebar-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700;flex-shrink:0}
.sidebar-uname{font-size:12px;font-weight:600;color:rgba(255,255,255,.8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sidebar-role{font-size:10px;color:rgba(255,255,255,.35);text-transform:uppercase;letter-spacing:.8px}

/* ═══ OVERLAY ═══ */
.sidebar-overlay{
  display:none;position:fixed;inset:0;
  background:rgba(0,0,0,.55);z-index:290;
  backdrop-filter:blur(2px);opacity:0;transition:opacity .28s;
}
.sidebar-overlay.active{display:block;opacity:1}

/* ═══ CONTENT ═══ */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column}
.topbar{height:56px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 18px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:36px;height:36px;border-radius:8px;border:1px solid var(--border);background:transparent;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:12px;color:var(--muted);overflow:hidden}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px;white-space:nowrap}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500;flex-shrink:0}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}

/* ═══ PAGE ═══ */
.page{padding:18px;flex:1;max-width:100%}
.page-header{margin-bottom:18px;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:12px;color:var(--muted);margin-top:2px}
.back-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-weight:600;color:var(--ink-2);text-decoration:none;box-shadow:var(--shadow);transition:background .15s;white-space:nowrap}
.back-btn:hover{background:var(--bg);color:var(--ink)}

/* ═══ STATS ═══ */
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow);display:flex;align-items:center;gap:12px}
.stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0}
.stat-icon.blue{background:#dbeafe;color:#1d4ed8}
.stat-icon.indigo{background:#e0e7ff;color:#4338ca}
.stat-icon.green{background:#d1fae5;color:#059669}
.stat-icon.red{background:#fee2e2;color:#dc2626}
.stat-label{font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.stat-value{font-size:22px;font-weight:700;color:var(--ink);letter-spacing:-.5px;line-height:1.2}

/* ═══ DASH CARD ═══ */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:16px;overflow:hidden}
.dash-card-header{padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:13px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:12px}
.dash-card-body{padding:16px}

/* ═══ TASK ITEMS ═══ */
.task-item{border:1px solid var(--border);border-radius:10px;margin-bottom:10px;overflow:hidden;transition:box-shadow .2s}
.task-item:hover{box-shadow:var(--shadow-md)}
.task-item.overdue{border-left:4px solid var(--red)}
.task-item.in-progress{border-left:4px solid var(--accent)}
.task-header{padding:11px 14px;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
.task-body{padding:2px 14px 12px}
.task-title-text{font-size:14px;font-weight:700;color:var(--ink);margin-bottom:4px}
.task-desc-text{font-size:12px;color:var(--muted);line-height:1.6}
.task-meta{display:flex;align-items:center;gap:12px;margin-top:8px;font-size:11.5px;color:var(--muted);flex-wrap:wrap}
.task-footer{padding:9px 14px;background:#f8fafc;border-top:1px solid var(--border);display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.remarks-area{background:#f1f5f9;border:1px solid var(--border);border-radius:8px;padding:9px 11px;font-size:11.5px;white-space:pre-wrap;line-height:1.7;color:var(--ink-2);margin-top:8px}
.remarks-collapse{margin-top:10px;border-top:1px solid var(--border);padding-top:10px;display:none}
.remarks-collapse.open{display:block}

/* ═══ BADGES ═══ */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:10.5px;font-weight:600;white-space:nowrap}
.badge-pending{background:#f1f5f9;color:#475569}
.badge-progress{background:#e0e7ff;color:#4338ca}
.badge-completed{background:#d1fae5;color:#065f46}
.badge-high{background:#fee2e2;color:#991b1b}
.badge-medium{background:#fef3c7;color:#92400e}
.badge-low{background:#d1fae5;color:#065f46}
.badge-overdue{background:#fee2e2;color:#991b1b}
.badge-purple{background:#ede9fe;color:#5b21b6}
.badge-role{background:#f1f5f9;color:var(--muted);font-size:9.5px;padding:2px 6px;border-radius:10px;margin-left:3px}
.time-chip{display:inline-flex;align-items:center;gap:4px;background:#e0e7ff;color:#4338ca;font-size:10.5px;font-weight:700;padding:3px 9px;border-radius:20px}.live-timer{background:#d1fae5;color:#065f46}

/* ═══ BUTTONS ═══ */
.btn-action{display:inline-flex;align-items:center;gap:5px;padding:7px 14px;border-radius:20px;font-size:12px;font-weight:700;border:none;cursor:pointer;font-family:Inter,Segoe UI,Roboto,Arial,sans-serif;transition:opacity .15s,transform .15s;-webkit-tap-highlight-color:transparent}
.btn-action:hover{opacity:.88;transform:translateY(-1px)}
.btn-action:active{transform:translateY(0)}
.btn-start{background:linear-gradient(135deg,#059669,#10b981);color:#fff}
.btn-finish{background:linear-gradient(135deg,var(--accent),#6366f1);color:#fff}
.btn-remarks{background:var(--surface);border:1px solid var(--border) !important;color:var(--ink-2)}
.btn-save-rem{padding:7px 16px;border-radius:20px;border:none;background:#0f172a;color:#fff;font-size:12px;font-weight:700;cursor:pointer;font-family:Inter,Segoe UI,Roboto,Arial,sans-serif;margin-top:6px}

/* ═══ REMARK FORM ═══ */
.remarks-form textarea{width:100%;border:1.5px solid var(--border);border-radius:8px;padding:9px 12px;font-size:13px;font-family:Inter,Segoe UI,Roboto,Arial,sans-serif;color:var(--ink);background:var(--bg);outline:none;resize:vertical;min-height:70px;transition:border-color .15s}
.remarks-form textarea:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}

/* ═══ ALERTS ═══ */
.alert-custom{padding:12px 14px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:14px;display:flex;align-items:flex-start;gap:10px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}
.alert-danger-custom{background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}
.alert-warning-custom{background:#fef3c7;border-left:3px solid var(--amber);color:#78350f}

/* ═══ TABLE ═══ */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.dash-table{width:100%;border-collapse:collapse;font-size:12.5px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.6px;padding:10px 12px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 12px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}

/* ═══ EMPTY STATE ═══ */
.empty-state{text-align:center;padding:40px 24px;color:var(--muted)}
.empty-state i{font-size:32px;display:block;margin-bottom:10px;opacity:.3}

/* ═══ RESPONSIVE ═══ */
@media(max-width:992px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .content{margin-left:0}
  .page{padding:14px}
  .stats-grid{grid-template-columns:repeat(2,1fr)}
  .page-header{flex-direction:column;gap:8px}
}
</style>
</head>
<body>

<!-- OVERLAY -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<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 Portal</div>
      <div class="brand-sub">Employee</div>
    </div>
  </div>

  <div class="sidebar-user-info">
    <div class="sidebar-avatar"><?= strtoupper(substr($username, 0, 2)) ?></div>
    <div>
      <div class="sidebar-uname"><?= h($username) ?></div>
      <div class="sidebar-role">Employee</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul class="nav-list">
    <li class="nav-item"><a href="dashboard_employee.php" class="nav-link"><i class="fas fa-gauge-high"></i> Dashboard</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul class="nav-list">
    <li class="nav-item"><a href="apply_leave.php" class="nav-link"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense.php" class="nav-link"><i class="fas fa-receipt"></i> Expenses</a></li>
    <li class="nav-item"><a href="tasks_employee.php" class="nav-link active"><i class="fas fa-list-check"></i> My Tasks</a></li>
    <li class="nav-item"><a href="daily_report.php" class="nav-link"><i class="fas fa-file-lines"></i> Attendance &amp; Daily Report</a></li>
    <li class="nav-item"><a href="employee_grievance.php" class="nav-link"><i class="fas fa-exclamation-triangle"></i> Grievance</a></li>
  </ul>

  <div class="sidebar-footer">
    <ul class="nav-list">
      <li class="nav-item">
        <a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')">
          <i class="fas fa-right-from-bracket"></i> Logout
        </a>
      </li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()" aria-label="Toggle menu">
      <i class="fas fa-bars"></i>
    </button>
    <div class="topbar-breadcrumb">
      <span>Employee</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span>Work</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span class="current">My Tasks</span>
    </div>
    <div class="topbar-spacer"></div>
    <span style="font-size:11px;font-weight:600;background:#f1f5f9;color:var(--muted);padding:4px 10px;border-radius:20px;border:1px solid var(--border);white-space:nowrap;display:none" class="date-chip">
      <?= date('d M Y') ?>
    </span>
    <div class="topbar-user" style="margin-left:8px">
      <div class="topbar-avatar"><?= strtoupper(substr($username, 0, 2)) ?></div>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">My Worklist</div>
        <div class="page-subtitle">Manage and track your assigned tasks · <?= date('l, d M Y') ?></div>
      </div>
      <a href="dashboard_employee.php" class="back-btn"><i class="fas fa-arrow-left" style="font-size:10px"></i> Dashboard</a>
    </div>

    <?php if ($flash = get_flash()): ?>
      <div class="alert-custom alert-<?= $flash['type'] ?>-custom">
        <i class="fas fa-<?= $flash['type'] === 'success' ? 'check-circle' : ($flash['type'] === 'warning' ? 'exclamation-triangle' : 'exclamation-circle') ?>" style="margin-top:1px;flex-shrink:0"></i>
        <span><?= h($flash['msg']) ?></span>
      </div>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-layer-group"></i></div>
        <div><div class="stat-label">Total</div><div class="stat-value"><?= $total ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon indigo"><i class="fas fa-spinner"></i></div>
        <div><div class="stat-label">In Progress</div><div class="stat-value"><?= $inprog_count ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-circle-check"></i></div>
        <div><div class="stat-label">Completed</div><div class="stat-value"><?= $completed_count ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon red"><i class="fas fa-clock-rotate-left"></i></div>
        <div><div class="stat-label">Overdue</div><div class="stat-value"><?= $overdue_count ?></div></div>
      </div>
    </div>

    <!-- ACTIVE TASKS -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-play-circle"></i> Current Tasks</div>
        <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px"><?= count($active_tasks) ?> active</span>
      </div>
      <div class="dash-card-body">
        <?php if (empty($active_tasks)): ?>
          <div class="empty-state">
            <i class="fas fa-check-circle"></i>
            <p>All caught up! No active tasks.</p>
          </div>
        <?php else: ?>
          <?php foreach ($active_tasks as $t):
            $overdue = !empty($t['due_date']) && $t['due_date'] < $today;
            $is_prog = $t['status'] === 'In Progress';
            $item_cls = $is_prog ? 'in-progress' : ($overdue ? 'overdue' : '');
          ?>
          <div class="task-item <?= $item_cls ?>">
            <div class="task-header">
              <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
                <?php if ($is_prog): ?>
                  <span class="badge-custom badge-progress"><i class="fas fa-spinner fa-spin" style="font-size:9px"></i>In Progress</span>
                <?php else: ?>
                  <span class="badge-custom badge-pending"><i class="fas fa-clock" style="font-size:9px"></i>Pending</span>
                <?php endif; ?>
                <span class="badge-custom badge-<?= strtolower($t['priority']) ?>">
                  <i class="fas fa-flag" style="font-size:9px"></i><?= h($t['priority']) ?>
                </span>
                <?php if ($overdue): ?>
                  <span class="badge-custom badge-overdue"><i class="fas fa-exclamation-triangle" style="font-size:9px"></i>Overdue</span>
                <?php endif; ?>
              </div>
              <div style="font-size:11px;color:var(--muted);white-space:nowrap">Due: <strong><?= h($t['due_date']) ?></strong></div>
            </div>

            <div class="task-body">
              <div class="task-title-text"><?= h($t['title']) ?></div>
              <div class="task-desc-text"><?= h($t['description']) ?></div>
              <div class="task-meta">
                <span>
                  <i class="fas fa-user-edit" style="margin-right:3px"></i>
                  <?= h($t['assigner_first']) ?> <?= h($t['assigner_last']) ?>
                  <span class="badge-role"><?= h($t['assigner_role']) ?></span>
                </span>
                <?php if ($t['start_time']): ?>
                  <span class="time-chip">
                    <i class="fas fa-stopwatch" style="font-size:9px"></i>
                    Started <?= date('H:i', strtotime($t['start_time'])) ?>
                  </span>
                <?php endif; ?>
              </div>

              <?php if (!empty($t['remarks']) && $t['remarks'] !== 'None'): ?>
                <div class="remarks-area"><?= nl2br(h($t['remarks'])) ?></div>
              <?php endif; ?>

              <div class="remarks-collapse" id="rem-<?= $t['task_id'] ?>">
                <div class="remarks-form">
                  <form method="POST">
                    <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                    <input type="hidden" name="action" value="save_remarks">
                    <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
                    <textarea name="remarks" placeholder="Write a progress note..."></textarea>
                    <button type="submit" class="btn-save-rem"><i class="fas fa-save" style="font-size:11px;margin-right:4px"></i>Save Note</button>
                  </form>
                </div>
              </div>
            </div>

            <div class="task-footer">
              <?php if ($t['status'] === 'Pending'): ?>
                <form method="POST" style="margin:0">
                  <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                  <input type="hidden" name="action" value="start_task">
                  <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
                  <button type="submit" class="btn-action btn-start">
                    <i class="fas fa-play" style="font-size:10px"></i>Start Task
                  </button>
                </form>
              <?php else: ?>
                <form method="POST" style="margin:0" onsubmit="return confirm('Mark this task as finished?')">
                  <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                  <input type="hidden" name="action" value="finish_task">
                  <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
                  <button type="submit" class="btn-action btn-finish">
                    <i class="fas fa-check-double" style="font-size:10px"></i>Mark Finished
                  </button>
                </form>
              <?php endif; ?>

              <button class="btn-action btn-remarks" onclick="toggleRemark(<?= $t['task_id'] ?>)">
                <i class="fas fa-comment-dots" style="font-size:10px"></i>Add Note
              </button>
            </div>
          </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- COMPLETED HISTORY -->
    <?php if (!empty($completed_tasks)): ?>
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-history"></i> Completed History</div>
        <span style="font-size:10px;font-weight:600;background:#d1fae5;color:#065f46;padding:3px 9px;border-radius:20px"><?= $completed_count ?> done</span>
      </div>
      <div class="dash-card-body" style="padding:0">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Task</th>
                <th>Assigned By</th>
                <th>Completed</th>
                <th>Time</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($completed_tasks as $t): ?>
              <tr>
                <td style="color:var(--muted);font-size:11px"><?= $i++ ?></td>
                <td><strong style="font-size:13px"><?= h($t['title']) ?></strong></td>
                <td style="font-size:11px;color:var(--muted)"><?= h($t['assigner_first']) ?> <?= h($t['assigner_last']) ?></td>
                <td style="font-size:11px;white-space:nowrap"><?= !empty($t['end_time']) ? date('d M, H:i', strtotime($t['end_time'])) : '—' ?></td>
                <td>
                  <span class="badge-custom badge-purple">
                    <i class="fas fa-stopwatch" style="font-size:9px"></i><?= h($t['time_spent']) ?> mins
                  </span>
                </td>
                <td><span class="badge-custom badge-completed"><i class="fas fa-check" style="font-size:9px"></i>Done</span></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <?php endif; ?>

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

<script>
function toggleSidebar() {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  if (sidebar.classList.contains('open')) {
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
  } else {
    sidebar.classList.add('open');
    overlay.classList.add('active');
  }
}
function closeSidebar() {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('sidebarOverlay').classList.remove('active');
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSidebar(); });

function toggleRemark(taskId) {
  const el = document.getElementById('rem-' + taskId);
  el.classList.toggle('open');
}
function updateLiveTimers() {
  document.querySelectorAll('.live-timer').forEach(function (el) {
    const startValue = el.getAttribute('data-start');
    if (!startValue) return;

    const start = new Date(startValue.replace(' ', 'T'));
    if (isNaN(start.getTime())) return;

    const diff = Math.max(0, Math.floor((Date.now() - start.getTime()) / 1000));
    const h = String(Math.floor(diff / 3600)).padStart(2, '0');
    const m = String(Math.floor((diff % 3600) / 60)).padStart(2, '0');
    const s = String(diff % 60).padStart(2, '0');

    const span = el.querySelector('span');
    if (span) span.textContent = h + ':' + m + ':' + s;
  });
}

updateLiveTimers();
setInterval(updateLiveTimers, 1000);

// No page reload/polling is used here. The timer updates only the visible
// elapsed-time text for already-started tasks.
document.addEventListener('DOMContentLoaded', function () {
  document.documentElement.classList.add('page-ready');
});
</script>
</body>
</html>