<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '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'] !== 'manager') { header("Location: login.php"); exit(); }

/*
 * ── ID TYPE FIX (confirmed) ───────────────────────────────────────
 * Confirmed from the actual schema:
 *   users.id            = varchar(11)   ← employee/manager id, e.g. "12"
 *   tasks.assigned_to   = int(11) NOT NULL
 *   tasks.assigned_by   = int(11) NOT NULL
 *
 * Because users.id is a VARCHAR, it must never be cast with (int) in
 * PHP before use — that was the earlier bug (dropdown values all
 * became "0"). Every id from users.id (manager_id, assigned_to,
 * assigned_by, team_ids) is kept and compared as a STRING here, and
 * bound with "s". As long as the id VALUE itself is a clean numeric
 * string (e.g. "12"), MySQL stores it correctly into the int(11)
 * columns — this only works because this system's ids happen to be
 * numeric-looking strings, not because varchar->int is safe in
 * general.
 *
 * A guard is added below so that if $assigned_to or $manager_id is
 * ever not a clean digit string, task creation is rejected instead of
 * silently storing a corrupted "0" (which is what produced the old
 * orphaned rows with a blank "Assigned by:").
 *
 * task_id is the tasks table's own auto-increment PRIMARY KEY (not a
 * users.id), so it's the one id always safely handled as a PHP int.
 *
 * ── INVISIBLE-WHITESPACE FIX (new) ────────────────────────────────
 * Plain trim() only strips ASCII whitespace (space, \t, \n, \r, \0,
 * \x0B). Some rows in users.id came in with invisible Unicode
 * whitespace baked in (non-breaking space U+00A0, zero-width space
 * U+200B, BOM U+FEFF — typically left behind by Excel/CSV imports).
 * Those bytes are still there after trim(), so ctype_digit() fails
 * even though the id "looks" numeric on screen — this is what was
 * producing the "not a valid numeric id" error. clean_id() strips
 * those too, and is applied consistently to BOTH $team_ids and
 * $assigned_to so the in_array() comparison still matches.
 * ------------------------------------------------------------------
 */
$manager_id       = trim((string)$_SESSION['user_id']);
$manager_username = trim($_SESSION['username'] ?? '');
$today            = date('Y-m-d');

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

function h($s): string {
    // htmlspecialchars() only accepts strings. Database fields such as
    // task_id/time_spent may be returned by mysqli as integers, so always
    // normalize scalar values to a string before escaping.
    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');
}
function set_flash($type, $msg) { $_SESSION['flash'] = ['type' => $type, 'msg' => $msg]; }
function get_flash() { if (isset($_SESSION['flash'])) { $f = $_SESSION['flash']; unset($_SESSION['flash']); return $f; } return null; }

/**
 * Trims an id AND strips invisible unicode whitespace that plain
 * trim() misses (non-breaking space, zero-width space, BOM). Used on
 * every users.id value we compare or bind, so a dirty DB value and a
 * dirty submitted value still match each other.
 */
function clean_id($id): string {
    $id = trim((string)$id);
    return preg_replace('/[\x{00A0}\x{200B}\x{FEFF}\s]+/u', '', $id) ?? $id;
}

$stmt = $conn->prepare("SELECT CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,'')) AS name FROM users WHERE id = ?");
$stmt->bind_param("s", $manager_id);
$stmt->execute();
$manager_name = trim($stmt->get_result()->fetch_assoc()['name'] ?? '') ?: 'Manager';
$stmt->close();

/*
 * TEAM LOOKUP — brought in line with myteam.php
 * ------------------------------------------------
 * This page used to find the manager's team with:
 *   WHERE reporting_manager_id = ? AND role = 'employee'
 * myteam.php (the source of truth for "who is on my team") instead
 * matches on the reporting_manager TEXT column against either the
 * manager's username OR their full name, case-insensitively, because
 * some employee rows store the manager's full name there instead of
 * their username. Using reporting_manager_id here meant a manager
 * could see a different team on the Tasks page than on the My Team
 * page (and could fail to see, or fail to assign tasks to, people who
 * only had the text-based relationship set). We now use the exact
 * same MGR_MATCH_SQL condition, the exact same bindManagerMatch()
 * helper, and the same GROUP BY dedup safeguard as myteam.php, so
 * "my team" means the same thing everywhere in the app — a change to
 * either file's matching rule can no longer accidentally leave the
 * other page out of sync.
 */
const MGR_MATCH_SQL = "(LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)))";

/**
 * Binds the two manager-match params ($manager_username, $manager_name)
 * onto the front of whatever other params a given statement needs.
 * Same helper, same signature as myteam.php — kept identical so the
 * "who is my team" logic can never drift between the two pages again.
 */
function bindManagerMatch(mysqli_stmt $stmt, string $extraTypes, array $extraParams, string $manager_username, string $manager_name): void {
    $types  = "ss" . $extraTypes;
    $params = array_merge([$manager_username, $manager_name], $extraParams);
    $stmt->bind_param($types, ...$params);
}

$team_sql = "
    SELECT u.id, u.first_name, u.last_name
    FROM users u
    WHERE " . MGR_MATCH_SQL . " AND u.role = 'employee' AND u.status = 'active'
    GROUP BY u.id
    ORDER BY u.first_name
";
$stmt = $conn->prepare($team_sql);
bindManagerMatch($stmt, "", [], $manager_username, $manager_name);
$stmt->execute();
$team = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// team_ids: keep as strings, exactly as users.id comes back from
// mysqli — but run through clean_id() so any invisible unicode
// whitespace in the stored id doesn't break the ctype_digit()/
// in_array() checks below. Do NOT cast with (int) — that silently
// zeroes out any id that isn't purely numeric digits.
$team_ids = array_map('clean_id', array_column($team, 'id'));

$filter = [
    'status'   => $_GET['status'] ?? 'all',
    'priority' => $_GET['priority'] ?? 'all',
    // '0' is the sentinel meaning "All" (matches the dropdown's hidden
    // "All" option value below). Kept as string for the <select>
    // "selected" comparisons in the HTML, cast to int only when bound.
    'employee' => trim((string)($_GET['employee'] ?? '0')),
    'from'     => $_GET['from'] ?? '',
    'to'       => $_GET['to'] ?? '',
    'search'   => trim($_GET['search'] ?? ''),
];

/* ── POST HANDLING ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf']) && $_POST['csrf'] === $csrf_token) {
    if (isset($_POST['create_task'])) {
        $title       = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');

        // assigned_to is a users.id value — kept and compared as a
        // string (see the ID TYPE note above), and run through
        // clean_id() to strip invisible unicode whitespace that plain
        // trim() misses. Do NOT cast to (int).
        $assigned_to = clean_id($_POST['assigned_to'] ?? '');

        $priority   = in_array($_POST['priority'] ?? '', ['Low','Medium','High'], true) ? $_POST['priority'] : 'Medium';
        $start_date = $_POST['start_date'] ?? '';
        $due_date   = $_POST['due_date'] ?? '';

        // Field-level validation. Each case reports specifically so the
        // real cause is visible instead of hidden behind one generic
        // message.
        $errors = [];
        if (strlen($title) < 3) {
            $errors[] = 'Task title must be at least 3 characters long.';
        }
        
      if (empty($team)) {
    $errors[] = 'You have no active team members to assign a task to. Check the My Team page — if someone is missing there too, their Reporting Manager field needs to match your username or full name.';
} elseif ($assigned_to === '') {
    $errors[] = 'Please select a team member from the "Assign To" dropdown.';
} elseif (!in_array($assigned_to, $team_ids, true)) {
    $errors[] = 'You can only assign tasks to your own team members.';
}

        if (!$start_date) {
            $errors[] = 'Please choose a start date.';
        }
        if (!$due_date) {
            $errors[] = 'Please choose a due date.';
        }
        if ($start_date && $due_date && $start_date > $due_date) {
            $errors[] = 'Start date cannot be after due date.';
        }

        if ($errors) {
            set_flash('danger', implode(' ', $errors));
        } else {
            $stmt = $conn->prepare("INSERT INTO tasks (title,description,assigned_to,assigned_by,priority,start_date,due_date,status) VALUES (?,?,?,?,?,?,?,'Pending')");
            $stmt->bind_param("sssssss", $title, $description, $assigned_to, $manager_id, $priority, $start_date, $due_date);
            $stmt->execute() ? set_flash('success', "Task <strong>".h($title)."</strong> created.") : set_flash('danger', 'Failed to create task: '.h($conn->error));
            $stmt->close();
        }
    } elseif (isset($_POST['accept_task'])) {
        $task_id = (int)($_POST['task_id'] ?? 0);
        if ($task_id > 0) {
            $stmt = $conn->prepare("UPDATE tasks SET start_time=NOW(),status='In Progress' WHERE task_id=? AND assigned_to=? AND start_time IS NULL");
            $stmt->bind_param("is", $task_id, $manager_id);
            $stmt->execute();
            $stmt->affected_rows > 0 ? set_flash('success','Task accepted and started.') : set_flash('danger','Task already started or not found.');
            $stmt->close();
        }
    } elseif (isset($_POST['finish_task'])) {
        $task_id = (int)($_POST['task_id'] ?? 0);
        if ($task_id > 0) {
            $stmt = $conn->prepare("SELECT start_time FROM tasks WHERE task_id=? AND assigned_to=?");
            $stmt->bind_param("is", $task_id, $manager_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            if ($result && $result['start_time']) {
                $start = new DateTime($result['start_time']);
                $end = new DateTime();
                $interval = $start->diff($end);
                $minutes = ($interval->days * 1440) + ($interval->h * 60) + $interval->i;
                $stmt = $conn->prepare("UPDATE tasks SET end_time=NOW(),time_spent=?,status='Completed' WHERE task_id=? AND assigned_to=? AND status!='Completed'");
                $stmt->bind_param("iis", $minutes, $task_id, $manager_id);
                $stmt->execute();
                $stmt->affected_rows > 0 ? set_flash('success',"Task finished. Time spent: $minutes min.") : set_flash('danger','Task already completed.');
                $stmt->close();
            } else {
                set_flash('warning','Task not started yet.');
            }
        }
    } elseif (isset($_POST['update_status'])) {
        $task_id = (int)($_POST['task_id'] ?? 0);
        $status  = $_POST['status'] ?? '';
        if ($task_id > 0 && in_array($status, ['Pending','In Progress','Completed'], true) && count($team_ids) > 0) {
            $in = implode(',', array_fill(0, count($team_ids), '?'));
            $stmt = $conn->prepare("UPDATE tasks SET status=? WHERE task_id=? AND assigned_to IN ($in)");
            $types  = 'si' . str_repeat('s', count($team_ids));
            $params = array_merge([$status, $task_id], $team_ids);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            set_flash('success','Team task status updated.');
            $stmt->close();
        }
    } elseif (isset($_POST['delete_task'])) {
        $task_id = (int)($_POST['task_id'] ?? 0);
        if ($task_id > 0) {
            $stmt = $conn->prepare("DELETE FROM tasks WHERE task_id=? AND assigned_by=?");
            $stmt->bind_param("is", $task_id, $manager_id);
            $stmt->execute();
            $stmt->affected_rows > 0 ? set_flash('warning','Task deleted.') : set_flash('danger','Cannot delete — not your task.');
            $stmt->close();
        }
    }
    $qs = http_build_query(array_filter($_GET));
    header("Location: tasks_manager.php" . ($qs ? "?$qs" : "")); exit();
}

$flash = get_flash();

/* ── TEAM TASKS ── */
$where = []; $types = ""; $params = [];
if (count($team_ids) > 0) {
    $in = implode(',', array_fill(0, count($team_ids), '?'));
    $where[] = "t.assigned_to IN ($in)";
    $types .= str_repeat('s', count($team_ids));
    $params = array_merge($params, $team_ids);
} else {
    $where[] = "t.assigned_by=?";
    $types .= "s";
    $params[] = $manager_id;
}
if ($filter['status'] !== 'all') { $where[] = "t.status=?"; $types .= "s"; $params[] = $filter['status']; }
if ($filter['priority'] !== 'all') { $where[] = "t.priority=?"; $types .= "s"; $params[] = $filter['priority']; }
if ($filter['employee'] !== '' && $filter['employee'] !== '0') {
    $where[] = "t.assigned_to=?"; $types .= "s"; $params[] = $filter['employee'];
}
if ($filter['from']) { $where[] = "t.due_date>=?"; $types .= "s"; $params[] = $filter['from']; }
if ($filter['to']) { $where[] = "t.due_date<=?"; $types .= "s"; $params[] = $filter['to']; }
if ($filter['search'] !== '') { $where[] = "t.title LIKE ?"; $types .= "s"; $params[] = '%'.$filter['search'].'%'; }
$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";
// GROUP BY t.task_id: same duplicate-row safeguard as myteam.php, in
// case a joined users row is ever multiplied by another table.
$stmt = $conn->prepare("SELECT t.*,u.first_name AS emp_first,u.last_name AS emp_last,ab.first_name AS assigner_first,ab.last_name AS assigner_last,ab.role AS assigner_role FROM tasks t JOIN users u ON t.assigned_to=u.id JOIN users ab ON t.assigned_by=ab.id $where_sql GROUP BY t.task_id ORDER BY FIELD(t.status,'In Progress','Pending','Completed'),t.due_date ASC");
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$team_tasks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* ── MY TASKS ── */
$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("s", $manager_id);
$stmt->execute();
$my_tasks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* ── SUMMARY ── */
$summary = ['total'=>0,'completed'=>0,'pending'=>0,'in_progress'=>0,'overdue'=>0];
if (count($team_ids) > 0) {
    $in = implode(',', array_fill(0, count($team_ids), '?'));
    $s = $conn->prepare("SELECT status,due_date FROM tasks WHERE assigned_to IN ($in)");
    $s->bind_param(str_repeat('s', count($team_ids)), ...$team_ids);
} else {
    $s = $conn->prepare("SELECT status,due_date FROM tasks WHERE assigned_by=?");
    $s->bind_param("s", $manager_id);
}
$s->execute();
$all_team = $s->get_result()->fetch_all(MYSQLI_ASSOC);
$s->close();
foreach ($all_team as $t) {
    $summary['total']++;
    if ($t['status'] === 'Completed') $summary['completed']++;
    elseif ($t['status'] === 'Pending') $summary['pending']++;
    else $summary['in_progress']++;
    if ($t['due_date'] < $today && $t['status'] !== 'Completed') $summary['overdue']++;
}
$summary['completion_rate'] = $summary['total'] > 0 ? round($summary['completed'] / $summary['total'] * 100) : 0;
?>
<!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 · Tasks</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=DM+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=DM+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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<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:'DM Sans',system-ui,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{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;transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.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-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:8px 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:15px;text-align:center;font-size:12px;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:10px 8px;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 ease}
.content.expanded{margin-left:0}
.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 22px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:34px;height:34px;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:14px;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)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px}
.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,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{padding:22px;flex:1}
.page-header{margin-bottom:22px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-top:2px}
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:18px;overflow:hidden}
.dash-card-header{padding:16px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:14px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:13px}
.dash-card-body{padding:18px}

/* Stats */
.stats-row{display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:20px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);padding:14px 12px;box-shadow:var(--shadow);text-align:center;cursor:pointer;text-decoration:none;transition:transform .15s,box-shadow .15s;display:block;color:inherit}
.stat-card:hover{transform:translateY(-2px);box-shadow:var(--shadow-md);color:inherit;text-decoration:none}
.stat-card.active-filter{border-color:var(--accent);box-shadow:0 0 0 2px rgba(79,70,229,.15)}
.stat-num{font-size:22px;font-weight:800;color:var(--ink);line-height:1;font-family:'DM Mono',monospace}
.stat-lbl{font-size:11px;color:var(--muted);margin-top:4px;font-weight:500}
.stat-num.blue{color:var(--accent)}
.stat-num.green{color:var(--green)}
.stat-num.cyan{color:var(--accent-2)}
.stat-num.amber{color:var(--amber)}
.stat-num.red{color:var(--red)}
.stat-num.gray{color:var(--muted)}

/* Task Cards */
.task-card{background:var(--surface);border:1.5px solid var(--border);border-radius:var(--radius-sm);margin-bottom:12px;box-shadow:var(--shadow);overflow:hidden;transition:box-shadow .15s}
.task-card:hover{box-shadow:var(--shadow-md)}
.task-card.overdue{border-left:4px solid var(--red)}
.task-card.md-task{border-left:4px solid var(--accent-2)}
.task-card-body{padding:16px}
.task-title{font-size:14px;font-weight:700;color:var(--ink);margin-bottom:4px}
.task-desc{font-size:12px;color:var(--muted);margin-bottom:12px;line-height:1.5}
.task-meta{display:flex;flex-wrap:wrap;gap:12px;font-size:12px;color:var(--ink-2);margin-bottom:12px}
.task-meta strong{font-weight:600}
.divider{height:1px;background:var(--border);margin:12px 0}

/* Form */
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.form-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
.form-group{display:flex;flex-direction:column;gap:5px}
.form-label{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.form-control,.form-select{width:100%;padding:9px 12px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'DM Sans',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s;-webkit-appearance:none}
.form-control:focus,.form-select:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}
textarea.form-control{resize:vertical;min-height:80px;line-height:1.6}

/* Badges */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600;white-space:nowrap}
.badge-success{background:#d1fae5;color:#065f46}
.badge-warning{background:#fef3c7;color:#92400e}
.badge-danger{background:#fee2e2;color:#991b1b}
.badge-info{background:#dbeafe;color:#1e40af}
.badge-purple{background:#ede9fe;color:#5b21b6}
.badge-cyan{background:#cffafe;color:#164e63}

/* Buttons */
.btn-primary-sm{padding:7px 14px;background:var(--accent);color:#fff;border:none;border-radius:var(--radius-sm);font-size:12px;font-weight:700;cursor:pointer;font-family:'DM Sans',sans-serif;transition:background .15s;display:inline-flex;align-items:center;gap:5px}
.btn-primary-sm:hover{background:#4338ca}
.btn-success-sm{padding:7px 14px;background:#d1fae5;color:#065f46;border:none;border-radius:var(--radius-sm);font-size:12px;font-weight:700;cursor:pointer;font-family:'DM Sans',sans-serif;transition:all .15s;display:inline-flex;align-items:center;gap:5px}
.btn-success-sm:hover{background:#059669;color:#fff}
.btn-danger-sm{padding:7px 14px;background:#fee2e2;color:#991b1b;border:none;border-radius:var(--radius-sm);font-size:12px;font-weight:700;cursor:pointer;font-family:'DM Sans',sans-serif;transition:all .15s;display:inline-flex;align-items:center;gap:5px}
.btn-danger-sm:hover{background:#dc2626;color:#fff}
.btn-outline-sm{padding:7px 14px;background:transparent;color:var(--muted);border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-weight:600;cursor:pointer;font-family:'DM Sans',sans-serif;transition:all .15s;text-decoration:none;display:inline-flex;align-items:center;gap:5px}
.btn-outline-sm:hover{background:var(--bg);color:var(--ink);text-decoration:none}
.btn-submit-full{width:100%;padding:11px;background:linear-gradient(135deg,var(--accent),#6366f1);color:#fff;border:none;border-radius:var(--radius-sm);font-size:14px;font-weight:700;cursor:pointer;font-family:'DM Sans',sans-serif;transition:opacity .15s}
.btn-submit-full:hover{opacity:.9}

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

/* Section heading */
.section-heading{font-size:15px;font-weight:700;color:var(--ink);margin:24px 0 14px;display:flex;align-items:center;gap:8px}
.section-heading i{color:var(--accent)}
.count-badge{background:var(--accent);color:#fff;font-size:11px;font-weight:700;padding:2px 9px;border-radius:20px}

/* Filter row */
.filter-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end}
.fg{display:flex;flex-direction:column;gap:4px;flex:1;min-width:120px}
.fg label{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px}

/* Progress bar */
.progress-bar-wrap{height:6px;background:var(--border);border-radius:3px;margin-top:4px;overflow:hidden}
.progress-bar-fill{height:100%;background:linear-gradient(90deg,var(--accent),var(--accent-2));border-radius:3px;transition:width .5s}

.empty-alert{background:#f8fafc;border:1px dashed var(--border);border-radius:var(--radius-sm);padding:28px;text-align:center;color:var(--muted);font-size:13px}
.empty-alert i{font-size:28px;display:block;margin-bottom:8px;opacity:.3}

@media(max-width:992px){.stats-row{grid-template-columns:repeat(3,1fr)}}
@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{padding:14px}.stats-row{grid-template-columns:repeat(2,1fr)}.form-grid,.form-grid-3{grid-template-columns:1fr}}


/* ═══ MOBILE SIDEBAR FIX - SAME AS DASHBOARD_MANAGER ═══ */
.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}
@media(max-width:768px){
  body{overflow-x:hidden}
  .layout{min-width:0;width:100%}
  .sidebar{transform:translateX(-100%) !important;left:0;top:0;bottom:0;height:100vh;z-index:300}
  .sidebar.open{transform:translateX(0) !important}
  .content{margin-left:0 !important;width:100%;max-width:100%;min-width:0}
  .content.expanded{margin-left:0 !important}
  .topbar{padding:0 12px;gap:8px}
  .page{padding:13px !important}
  .topbar-user span{max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
  .stats-row{grid-template-columns:repeat(2,1fr)}
  .form-grid,.form-grid-3{grid-template-columns:1fr}
  .filter-row{display:block}
  .fg{margin-bottom:10px;min-width:0;width:100%}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay.active{display:none !important;opacity:0 !important}
  .content{margin-left:var(--sidebar-w)}
}

</style>
</head>
<body>
<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">Manager</div>
    </div>
  </div>
  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_manager.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a></li>
    <li class="nav-item"><a href="myteam.php" class="nav-link"><i class="fas fa-sitemap"></i> My Team</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="manager_daily_report.php" class="nav-link"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link"><i class="fas fa-file-alt"></i> Daily Reports</a></li>
    <li class="nav-item"><a href="leave_dashboard_manager.php" class="nav-link"><i class="fas fa-umbrella-beach"></i> Team Leaves</a></li>
    <li class="nav-item"><a href="manager_hr_leave_apply.php" class="nav-link"><i class="fas fa-plane-departure"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="tasks_manager.php" class="nav-link active"><i class="fas fa-tasks"></i> Tasks</a></li>
   <li class="nav-item"><a href="manager_expenses.php" class="nav-link"><i class="fas fa-receipt"></i> Claims</a></li>
   <li class="nav-item"><a href="apply_grievance_manager.php" class="nav-link"><i class="fas fa-exclamation-circle"></i> Grievance</a></li>
  </ul>
  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item"><a href="logout.php" class="nav-link danger"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
    </ul>
  </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>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">Tasks</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($manager_name, 0, 1)) ?></div>
      <span><?= h($manager_name) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title"><i class="fas fa-tasks" style="color:var(--accent);margin-right:8px;font-size:18px"></i>Team Tasks</div>
      <div class="page-subtitle"><?= date('l, F j, Y') ?> · Task Management</div>
    </div>

    <?php if ($flash): ?>
      <div class="alert-custom alert-<?= $flash['type'] === 'success' ? 'success' : ($flash['type'] === 'warning' ? 'warning' : 'error') ?>-custom">
        <i class="fas fa-<?= $flash['type'] === 'success' ? 'check-circle' : ($flash['type'] === 'warning' ? 'exclamation-triangle' : 'times-circle') ?>"></i>
        <span><?= $flash['msg'] ?></span>
      </div>
    <?php endif; ?>

    <?php if (empty($team)): ?>
      <div class="alert-custom alert-warning-custom">
        <i class="fas fa-info-circle"></i>
        <span>No active team members are currently linked to you as a reporting manager. Check the <a href="myteam.php">My Team</a> page — if someone is missing there too, their <strong>Reporting Manager</strong> field may need to be set to your username or full name.</span>
      </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-row">
      <a href="?status=all" class="stat-card <?= $filter['status']==='all'?'active-filter':'' ?>"><div class="stat-num blue"><?= $summary['total'] ?></div><div class="stat-lbl">Total</div></a>
      <a href="?status=Completed" class="stat-card <?= $filter['status']==='Completed'?'active-filter':'' ?>"><div class="stat-num green"><?= $summary['completed'] ?></div><div class="stat-lbl">Done</div></a>
      <a href="?status=In Progress" class="stat-card <?= $filter['status']==='In Progress'?'active-filter':'' ?>"><div class="stat-num cyan"><?= $summary['in_progress'] ?></div><div class="stat-lbl">In Progress</div></a>
      <a href="?status=Pending" class="stat-card <?= $filter['status']==='Pending'?'active-filter':'' ?>"><div class="stat-num amber"><?= $summary['pending'] ?></div><div class="stat-lbl">Pending</div></a>
      <div class="stat-card"><div class="stat-num red"><?= $summary['overdue'] ?></div><div class="stat-lbl">Overdue</div></div>
      <div class="stat-card">
        <div class="stat-num gray"><?= $summary['completion_rate'] ?>%</div>
        <div class="stat-lbl">Completion</div>
        <div class="progress-bar-wrap"><div class="progress-bar-fill" style="width:<?= $summary['completion_rate'] ?>%"></div></div>
      </div>
    </div>

    <!-- My Tasks -->
    <div class="section-heading"><i class="fas fa-user-check"></i> My Tasks <span class="count-badge"><?= count($my_tasks) ?></span></div>
    <?php if (empty($my_tasks)): ?>
      <div class="empty-alert"><i class="fas fa-inbox"></i>No tasks assigned to you at the moment.</div>
    <?php else: ?>
      <?php foreach ($my_tasks as $t):
        $is_overdue=($t['due_date']<$today&&$t['status']!=='Completed');
        $is_md=($t['assigner_role']??'')==='md';
        $assigner=h(($t['assigner_first']??'').' '.($t['assigner_last']??''));
      ?>
      <div class="task-card <?= $is_overdue?'overdue':'' ?> <?= $is_md?'md-task':'' ?>">
        <div class="task-card-body">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:8px">
            <div>
              <div class="task-title"><?= h($t['title']) ?></div>
              <div class="task-desc"><?= h($t['description']?:'No description') ?></div>
            </div>
            <div style="display:flex;gap:6px;flex-wrap:wrap;flex-shrink:0">
              <?php if($t['status']==='Completed'): ?><span class="badge-custom badge-success"><i class="fas fa-check-circle"></i> Completed</span>
              <?php elseif($t['status']==='In Progress'): ?><span class="badge-custom badge-info"><i class="fas fa-spinner"></i> In Progress</span>
              <?php else: ?><span class="badge-custom" style="background:#f1f5f9;color:var(--muted)">Pending</span><?php endif; ?>
              <?php if($is_overdue): ?><span class="badge-custom badge-danger">Overdue</span><?php endif; ?>
              <?php if($is_md): ?><span class="badge-custom badge-cyan"><i class="fas fa-star"></i> MD Task</span><?php endif; ?>
            </div>
          </div>
          <div class="task-meta">
            <span><strong>Assigned by:</strong> <?= $assigner ?></span>
            <span><strong>Due:</strong> <?= h($t['due_date']) ?></span>
            <?php if($t['start_time']): ?><span><strong>Started:</strong> <?= date('d M H:i',strtotime($t['start_time'])) ?></span><?php endif; ?>
            <?php if($t['time_spent']): ?><span><strong>Time:</strong> <?= h((string)$t['time_spent']) ?> min</span><?php endif; ?>
          </div>
          <?php if(!empty($t['remarks'])): ?>
            <div style="background:#f8fafc;border-left:3px solid var(--accent);border-radius:0 var(--radius-sm) var(--radius-sm) 0;padding:10px 14px;font-size:12px;color:var(--ink-2);margin-top:8px"><?= nl2br(h($t['remarks'])) ?></div>
          <?php endif; ?>
          <?php if($t['status']!=='Completed'): ?>
            <div class="divider"></div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
              <?php if($t['status']==='Pending'): ?>
                <form method="POST" class="d-inline">
                  <input type="hidden" name="csrf" value="<?= $csrf_token ?>">
                  <input type="hidden" name="accept_task" value="1">
                  <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
                  <button type="submit" class="btn-success-sm"><i class="fas fa-play"></i> Accept & Start</button>
                </form>
              <?php endif; ?>
              <?php if($t['status']==='In Progress'): ?>
                <form method="POST" class="d-inline" id="finishForm<?= $t['task_id'] ?>">
                  <input type="hidden" name="csrf" value="<?= $csrf_token ?>">
                  <input type="hidden" name="finish_task" value="1">
                  <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
                </form>
                <button type="button" class="btn-danger-sm" onclick="if(confirm('Finish this task now?')) document.getElementById('finishForm<?= $t['task_id'] ?>').submit()"><i class="fas fa-flag-checkered"></i> Finish Task</button>
              <?php endif; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>

    <!-- Create Task -->
    <div class="dash-card" style="margin-top:28px">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-plus-circle"></i> Assign New Task to Team</div>
      </div>
      <div class="dash-card-body">
        <?php if (empty($team)): ?>
          <div class="empty-alert"><i class="fas fa-user-slash"></i>No team members available to assign a task to.</div>
        <?php else: ?>
        <form method="POST">
          <input type="hidden" name="csrf" value="<?= $csrf_token ?>">
          <input type="hidden" name="create_task" value="1">
          <div class="form-grid" style="margin-bottom:14px">
            <div class="form-group">
              <label class="form-label">Task Title *</label>
              <input type="text" name="title" class="form-control" required placeholder="Enter task title…">
            </div>
            <div class="form-group">
              <label class="form-label">Assign To *</label>
              <select name="assigned_to" class="form-control" required>
                <option value="">Select team member</option>
                <?php foreach ($team as $m): ?>
                  <option value="<?= h(clean_id($m['id'])) ?>"><?= h($m['first_name'].' '.$m['last_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          <div class="form-grid-3" style="margin-bottom:14px">
            <div class="form-group">
              <label class="form-label">Priority</label>
              <select name="priority" class="form-control">
                <option value="Low">Low</option>
                <option value="Medium" selected>Medium</option>
                <option value="High">High</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Start Date *</label>
              <input type="date" name="start_date" class="form-control" required min="<?= $today ?>">
            </div>
            <div class="form-group">
              <label class="form-label">Due Date *</label>
              <input type="date" name="due_date" class="form-control" required min="<?= $today ?>">
            </div>
          </div>
          <div class="form-group" style="margin-bottom:14px">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" placeholder="Task details…"></textarea>
          </div>
          <button type="submit" class="btn-submit-full"><i class="fas fa-paper-plane"></i> Create & Assign Task</button>
        </form>
        <?php endif; ?>
      </div>
    </div>

    <!-- Filter & Team Tasks -->
    <div class="section-heading"><i class="fas fa-users"></i> Team Tasks <span class="count-badge"><?= count($team_tasks) ?></span></div>

    <div class="dash-card">
      <div class="dash-card-body">
        <form method="GET">
          <div class="filter-row">
            <div class="fg"><label>Status</label>
              <select name="status" class="form-control">
                <option value="all" <?= $filter['status']==='all'?'selected':'' ?>>All</option>
                <option value="Pending" <?= $filter['status']==='Pending'?'selected':'' ?>>Pending</option>
                <option value="In Progress" <?= $filter['status']==='In Progress'?'selected':'' ?>>In Progress</option>
                <option value="Completed" <?= $filter['status']==='Completed'?'selected':'' ?>>Completed</option>
              </select>
            </div>
            <div class="fg"><label>Priority</label>
              <select name="priority" class="form-control">
                <option value="all">All</option>
                <option value="Low" <?= $filter['priority']==='Low'?'selected':'' ?>>Low</option>
                <option value="Medium" <?= $filter['priority']==='Medium'?'selected':'' ?>>Medium</option>
                <option value="High" <?= $filter['priority']==='High'?'selected':'' ?>>High</option>
              </select>
            </div>
            <div class="fg"><label>Member</label>
              <select name="employee" class="form-control">
                <option value="0">All</option>
                <?php foreach ($team as $m): ?>
                  <option value="<?= h(clean_id($m['id'])) ?>" <?= $filter['employee']===clean_id($m['id'])?'selected':'' ?>><?= h($m['first_name'].' '.$m['last_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="fg"><label>From</label><input type="date" name="from" class="form-control" value="<?= h($filter['from']) ?>"></div>
            <div class="fg"><label>To</label><input type="date" name="to" class="form-control" value="<?= h($filter['to']) ?>"></div>
            <div style="display:flex;gap:6px;align-items:flex-end">
              <button type="submit" class="btn-primary-sm"><i class="fas fa-search"></i> Filter</button>
              <a href="tasks_manager.php" class="btn-outline-sm">Reset</a>
            </div>
          </div>
        </form>
      </div>
    </div>

    <?php if (empty($team_tasks)): ?>
      <div class="empty-alert"><i class="fas fa-filter"></i>No team tasks found with current filters.</div>
    <?php else: ?>
      <?php foreach ($team_tasks as $t):
        $is_overdue=($t['due_date']<$today&&$t['status']!=='Completed');
        $is_md=($t['assigner_role']??'')==='md';
      ?>
      <div class="task-card <?= $is_overdue?'overdue':'' ?> <?= $is_md?'md-task':'' ?>">
        <div class="task-card-body">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:8px">
            <div>
              <div class="task-title"><?= h($t['title']) ?></div>
              <div class="task-desc"><?= h($t['description']?:'No description') ?></div>
            </div>
            <div style="display:flex;gap:6px;flex-wrap:wrap;flex-shrink:0">
              <?php if($t['status']==='Completed'): ?><span class="badge-custom badge-success"><i class="fas fa-check-circle"></i> Completed</span>
              <?php elseif($t['status']==='In Progress'): ?><span class="badge-custom badge-info"><i class="fas fa-spinner"></i> In Progress</span>
              <?php else: ?><span class="badge-custom" style="background:#f1f5f9;color:var(--muted)">Pending</span><?php endif; ?>
              <?php if($t['priority']==='High'): ?><span class="badge-custom badge-danger">High</span>
              <?php elseif($t['priority']==='Medium'): ?><span class="badge-custom badge-warning">Medium</span>
              <?php else: ?><span class="badge-custom badge-info">Low</span><?php endif; ?>
              <?php if($is_overdue): ?><span class="badge-custom badge-danger">Overdue</span><?php endif; ?>
              <?php if($is_md): ?><span class="badge-custom badge-cyan">MD</span><?php endif; ?>
            </div>
          </div>
          <div class="task-meta">
            <span><strong>Assigned to:</strong> <?= h(($t['emp_first']??'').' '.($t['emp_last']??'')) ?></span>
            <span><strong>Assigned by:</strong> <?= h(($t['assigner_first']??'').' '.($t['assigner_last']??'')) ?></span>
            <span><strong>Due:</strong> <?= date('d M Y',strtotime($t['due_date'])) ?></span>
            <?php if($t['time_spent']): ?><span><strong>Time:</strong> <?= h((string)$t['time_spent']) ?> min</span><?php endif; ?>
          </div>
          <?php if(!empty($t['remarks'])): ?>
            <div style="background:#f8fafc;border-left:3px solid var(--accent);border-radius:0 var(--radius-sm) var(--radius-sm) 0;padding:10px 14px;font-size:12px;color:var(--ink-2);margin-bottom:10px"><?= nl2br(h($t['remarks'])) ?></div>
          <?php endif; ?>
          <div class="divider"></div>
          <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap">
            <form method="POST" class="d-inline">
              <input type="hidden" name="csrf" value="<?= $csrf_token ?>">
              <input type="hidden" name="update_status" value="1">
              <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
              <select name="status" class="form-control" style="width:auto;display:inline-block;font-size:12px;padding:5px 10px" onchange="this.form.submit()">
                <option value="Pending" <?= $t['status']==='Pending'?'selected':'' ?>>Pending</option>
                <option value="In Progress" <?= $t['status']==='In Progress'?'selected':'' ?>>In Progress</option>
                <option value="Completed" <?= $t['status']==='Completed'?'selected':'' ?>>Completed</option>
              </select>
            </form>
            <form method="POST" class="d-inline" onsubmit="return confirm('Delete this task?')">
              <input type="hidden" name="csrf" value="<?= $csrf_token ?>">
              <input type="hidden" name="delete_task" value="1">
              <input type="hidden" name="task_id" value="<?= $t['task_id'] ?>">
              <button type="submit" class="btn-danger-sm"><i class="fas fa-trash"></i> Delete</button>
            </form>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (!sb || !ov) return;
  const isOpen = sb.classList.contains('open');
  sb.classList.toggle('open', !isOpen);
  ov.classList.toggle('active', !isOpen);
}
function closeSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (sb) sb.classList.remove('open');
  if (ov) ov.classList.remove('active');
}
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeSidebar();
});
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('#sidebar .nav-link').forEach(function(a) {
    a.addEventListener('click', function() {
      if (window.innerWidth <= 768) closeSidebar();
    });
  });
});
</script>
</body>
</html>