<?php
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'] !== 'md') {
    header("Location: login.php"); exit();
}

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

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

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; } }

$me_stmt = $conn->prepare("SELECT first_name FROM users WHERE id = ?");
$me_stmt->bind_param("i",$md_id); $me_stmt->execute();
$me = $me_stmt->get_result()->fetch_assoc(); $me_stmt->close();

$mgr_stmt = $conn->query("SELECT id, first_name, last_name FROM users WHERE role = 'manager' ORDER BY first_name");
$managers = $mgr_stmt->fetch_all(MYSQLI_ASSOC);

$emp_stmt = $conn->query("SELECT id, first_name, last_name, reporting_manager_id FROM users WHERE role = 'employee' ORDER BY first_name");
$employees = $emp_stmt->fetch_all(MYSQLI_ASSOC);

$filter = [
    'status'   => $_GET['status']   ?? 'all',
    'priority' => $_GET['priority'] ?? 'all',
    'manager'  => (int)($_GET['manager']  ?? 0),
    'employee' => (int)($_GET['employee'] ?? 0),
    'from'     => $_GET['from']     ?? '',
    'to'       => $_GET['to']       ?? '',
    'search'   => trim($_GET['search'] ?? '')
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf']) && $_POST['csrf'] === $csrf_token) {
    if (isset($_POST['create_task'])) {
        $title=$trim=$_POST['title']??''; $title=trim($title);
        $desc=trim($_POST['description']??''); $assigned_to=(int)($_POST['assigned_to']??0);
        $priority=in_array($_POST['priority']??'',['Low','Medium','High'])?$_POST['priority']:'Medium';
        $start_date=$_POST['start_date']??''; $due_date=$_POST['due_date']??'';
        if(strlen($title)<3||$assigned_to<=0||!$start_date||!$due_date) set_flash('danger','Please fill all required fields.');
        elseif($start_date>$due_date) set_flash('danger','Start date cannot be after due date.');
        else {
            $stmt=$conn->prepare("INSERT INTO tasks (title,description,assigned_to,assigned_by,priority,start_date,due_date,status,remarks) VALUES(?,?,?,?,?,?,?,'Pending','')");
            $stmt->bind_param("ssissss",$title,$desc,$assigned_to,$md_id,$priority,$start_date,$due_date);
            if($stmt->execute()) set_flash('success','Task <strong>'.htmlspecialchars($title).'</strong> assigned successfully.');
            else set_flash('danger','Failed to create task.');
            $stmt->close();
        }
    } elseif(isset($_POST['update_status'])){
        $tid=(int)($_POST['task_id']??0); $st=$_POST['status']??'';
        if($tid>0&&in_array($st,['Pending','In Progress','Completed'])){
            $s=$conn->prepare("UPDATE tasks SET status=? WHERE task_id=?");
            $s->bind_param("si",$st,$tid); $s->execute(); $s->close();
            set_flash('success','Task status updated.');
        }
    } elseif(isset($_POST['delete_task'])){
        $tid=(int)($_POST['task_id']??0);
        if($tid>0){ $s=$conn->prepare("DELETE FROM tasks WHERE task_id=?"); $s->bind_param("i",$tid); $s->execute(); $s->close(); set_flash('warning','Task deleted.'); }
    } elseif(isset($_POST['save_md_remarks'])){
        $tid=(int)($_POST['task_id']??0); $rem=trim($_POST['md_remarks']??'');
        if($tid>0&&$rem!==''){
            $entry='[MD - '.date('d M Y H:i').'] '.$rem;
            $s=$conn->prepare("UPDATE tasks SET remarks=IF(remarks=''OR remarks IS NULL,?,CONCAT(remarks,'\n',?)) WHERE task_id=?");
            $s->bind_param("ssi",$entry,$entry,$tid); $s->execute(); $s->close();
            set_flash('success','MD remarks saved.');
        } else set_flash('warning','Remarks cannot be empty.');
    }
    $qs=http_build_query(array_filter($_GET));
    header("Location: tasks_md.php".($qs?"?$qs":"")); exit();
}

$where=[]; $types=""; $params=[];
if($filter['status']!=='all'){ $where[]="t.status=?"; $params[]=$filter['status']; $types.="s"; }
if($filter['priority']!=='all'){ $where[]="t.priority=?"; $params[]=$filter['priority']; $types.="s"; }
if($filter['manager']>0){ $where[]="t.assigned_by=?"; $params[]=$filter['manager']; $types.="i"; }
if($filter['employee']>0){ $where[]="t.assigned_to=?"; $params[]=$filter['employee']; $types.="i"; }
if($filter['from']){ $where[]="t.due_date>=?"; $params[]=$filter['from']; $types.="s"; }
if($filter['to']){ $where[]="t.due_date<=?"; $params[]=$filter['to']; $types.="s"; }
if($filter['search']!==''){ $where[]="t.title LIKE ?"; $params[]='%'.$filter['search'].'%'; $types.="s"; }
$where_sql=count($where)?"WHERE ".implode(" AND ",$where):"";

$stmt=$conn->prepare("SELECT t.*, emp.first_name AS emp_first, emp.last_name AS emp_last, emp.role AS emp_role,
    mgr.first_name AS mgr_first, mgr.last_name AS mgr_last, mgr.role AS assigner_role
    FROM tasks t JOIN users emp ON t.assigned_to=emp.id JOIN users mgr ON t.assigned_by=mgr.id
    $where_sql ORDER BY FIELD(t.status,'In Progress','Pending','Completed'), t.due_date ASC");
if($types) $stmt->bind_param($types,...$params);
$stmt->execute(); $tasks=$stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close();

$sum_res=$conn->query("SELECT status, due_date FROM tasks");
$all_tasks=$sum_res->fetch_all(MYSQLI_ASSOC);
$total=count($all_tasks); $completed=$pending=$in_progress=$overdue=0;
foreach($all_tasks as $t){
    if($t['status']==='Completed') $completed++;
    elseif($t['status']==='Pending') $pending++;
    else $in_progress++;
    if($t['due_date']<$today&&$t['status']!=='Completed') $overdue++;
}
$rate=$total>0?round($completed/$total*100):0;

$bd=$conn->query("SELECT u.first_name,u.last_name,COUNT(t.task_id) AS total,SUM(t.status='Completed') AS done,SUM(t.status='In Progress') AS inprog,SUM(t.status='Pending') AS pend FROM users u LEFT JOIN tasks t ON t.assigned_by=u.id WHERE u.role IN('manager','md') GROUP BY u.id ORDER BY u.first_name");
$breakdown=$bd->fetch_all(MYSQLI_ASSOC);
?>
<!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=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;
  --accent:#0ea5e9;--radius:12px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.06);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'Sora',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;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{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;transition:background .15s,color .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}.nav-link.active{background:rgba(59,130,246,.2);color:#60a5fa}
.nav-link i{width:16px;text-align:center;font-size:13px}.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.12);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px;border-top:1px solid rgba(255,255,255,.06)}
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s cubic-bezier(.4,0,.2,1)}
.content.expanded{margin-left:0}
.topbar{height:60px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 24px;position:sticky;top:0;z-index:100}
.hamburger-btn{width:36px;height:36px;border-radius:8px;border:1px solid var(--border);background:var(--surface);display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:15px;flex-shrink:0}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,#3b82f6,#6366f1);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700}
.page{padding:24px;flex:1}
.page-title{font-size:22px;font-weight:700;color:var(--ink);letter-spacing:-.4px;margin-bottom:4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-bottom:20px}

/* STAT GRID */
.stat-grid{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);padding:14px;box-shadow:var(--shadow);display:flex;align-items:center;gap:12px;transition:transform .18s,box-shadow .18s}
.stat-card:hover{transform:translateY(-2px);box-shadow:var(--shadow-md)}
.stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0}
.stat-num{font-size:22px;font-weight:700;font-family:'JetBrains Mono',monospace;line-height:1;margin-bottom:2px}
.stat-lbl{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}
.progress-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow);display:flex;flex-direction:column;justify-content:center}
.progress-bar-bg{background:#f1f5f9;border-radius:99px;height:8px;margin-top:6px}
.progress-bar-fill{height:8px;border-radius:99px;background:linear-gradient(90deg,#0ea5e9,#0284c7);transition:width .4s}

/* ALERT */
.alert{padding:12px 16px;border-radius:var(--radius);margin-bottom:12px;font-size:13px;font-weight:500;display:flex;align-items:center;gap:8px;animation:fadeUp .25s ease}
.alert-success{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
.alert-danger{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5}
.alert-warning{background:#fef3c7;color:#92400e;border:1px solid #fde68a}
@keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}

/* PANEL */
.panel{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;margin-bottom:16px;box-shadow:var(--shadow)}
.panel-header{padding:14px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.panel-header.sky{background:linear-gradient(135deg,#0ea5e9,#0284c7);color:#fff;border-bottom:none}
.panel-header.dark-hd{background:linear-gradient(135deg,var(--ink),#1e293b);color:#fff;border-bottom:none}
.panel-title{font-size:14px;font-weight:700}
.panel-subtitle{font-size:11px;opacity:.75;margin-top:2px}
.panel-body{padding:20px}

/* FORM ELEMENTS */
.form-row{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:12px}
.form-group{display:flex;flex-direction:column;gap:4px;flex:1;min-width:140px}
.form-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--muted)}
.form-control,.form-select{height:36px;border:1px solid var(--border);border-radius:8px;padding:0 10px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s,box-shadow .15s;width:100%}
.form-control:focus,.form-select:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(14,165,233,.15);background:var(--surface)}
textarea.form-control{height:auto;padding:8px 10px;resize:vertical}
.btn{height:36px;padding:0 16px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;display:inline-flex;align-items:center;gap:6px;transition:background .15s,border-color .15s,color .15s;text-decoration:none;white-space:nowrap}
.btn-primary{background:var(--accent);color:#fff}.btn-primary:hover{background:#0284c7}
.btn-ink{background:var(--ink);color:#fff}.btn-ink:hover{background:#1e293b}
.btn-ghost{background:var(--bg);color:var(--ink-2);border:1px solid var(--border)}.btn-ghost:hover{background:var(--border)}
.btn-success{background:#059669;color:#fff}.btn-success:hover{background:#047857}
.btn-danger{background:#dc2626;color:#fff}.btn-danger:hover{background:#b91c1c}
.btn-outline-danger{background:transparent;border:1.5px solid #dc2626;color:#dc2626}.btn-outline-danger:hover{background:#fee2e2}
.btn-outline-accent{background:transparent;border:1.5px solid var(--accent);color:var(--accent)}.btn-outline-accent:hover{background:#e0f2fe}
.btn-sm{height:30px;padding:0 12px;font-size:11px;border-radius:7px}

/* ASSIGN TABS */
.assign-tabs{display:flex;gap:4px;border-bottom:2px solid var(--border);margin-bottom:0}
.atab{padding:7px 18px;border:2px solid transparent;border-bottom:none;border-radius:8px 8px 0 0;font-size:13px;font-weight:600;font-family:'Sora',sans-serif;color:var(--muted);background:none;cursor:pointer;margin-bottom:-2px;transition:color .15s,background .15s}
.atab.active{color:var(--accent);background:var(--surface);border-color:var(--border) var(--border) var(--surface) var(--border)}
.tab-pane{border:1px solid var(--border);border-top:none;border-radius:0 8px 8px 8px;padding:16px;background:#fafcff}

/* FILTER BAR */
.filter-bar{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;padding:14px 16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:16px;box-shadow:var(--shadow)}
.filter-group{display:flex;flex-direction:column;gap:4px}
.filter-group.grow{flex:1;min-width:160px}
.filter-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}

/* TASK CARD */
.task-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:12px;overflow:hidden;transition:box-shadow .18s;box-shadow:var(--shadow)}
.task-card:hover{box-shadow:var(--shadow-md)}
.task-card.overdue{border-left:4px solid #ef4444}
.tc-header{padding:14px 20px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap}
.tc-body{padding:12px 20px}
.tc-actions{padding:10px 20px;background:#f8fafc;border-top:1px solid var(--border);display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.tc-remarks-panel{padding:0 20px 16px}
.task-title{font-size:14px;font-weight:700;color:var(--ink);margin-bottom:4px}
.task-assignees{font-size:11px;color:var(--muted);display:flex;align-items:center;gap:6px;flex-wrap:wrap}

/* BADGES */
.pbadge{display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:700;padding:3px 8px;border-radius:99px;text-transform:uppercase;letter-spacing:.5px}
.ph{background:#fee2e2;color:#b91c1c}.pm{background:#fef9c3;color:#a16207}.pl{background:#dcfce7;color:#166534}
.sbadge{display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:700;padding:3px 9px;border-radius:99px}
.sc{background:#dcfce7;color:#166534}.si{background:#dbeafe;color:#1d4ed8}.sp{background:#f1f5f9;color:#475569}
.so{background:#fee2e2;color:#b91c1c}.smd{background:#e0f2fe;color:#0284c7}.sna{background:#f8fafc;color:#94a3b8;border:1px solid var(--border)}

/* META */
.meta-row{display:flex;flex-wrap:wrap;gap:18px;font-size:12px;color:var(--muted);margin-bottom:10px}
.meta-item strong{color:var(--ink);display:block;font-size:10px;text-transform:uppercase;letter-spacing:.5px;font-weight:600;margin-bottom:1px}
.remarks-box{background:#f8fafc;border:1px solid var(--border);border-radius:8px;padding:10px 14px;font-size:12px;color:var(--ink);white-space:pre-line;margin-top:8px}
.section-head{font-size:13px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:8px;margin-bottom:14px}
.section-cnt{font-size:10px;font-weight:700;padding:2px 8px;border-radius:99px;background:var(--accent);color:#fff}

/* BREAKDOWN TABLE */
.tbl-wrap{overflow-x:auto}
table.breakdown{width:100%;border-collapse:collapse;font-size:13px}
table.breakdown thead th{background:var(--ink);color:rgba(255,255,255,.85);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.7px;padding:9px 16px;text-align:left}
table.breakdown tbody td{padding:10px 16px;border-bottom:1px solid var(--border);color:var(--ink-2)}
table.breakdown tbody tr:last-child td{border-bottom:none}
table.breakdown tbody tr:hover td{background:#f8fafc}

@media(max-width:1100px){.stat-grid{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:16px}.stat-grid{grid-template-columns:repeat(2,1fr)}}
</style>
</head>
<body>
<script>const ALL_EMPLOYEES=<?= json_encode($employees) ?>;</script>
<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">MD Portal</div></div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_md.php"               class="nav-link"><i class="fas fa-sitemap"></i> Organisation</a></li>
      <li class="nav-item"><a href="payroll_md_dashboard.php"       class="nav-link"><i class="fas fa-money-bill"></i> Payroll</a></li>
      <li class="nav-item"><a href="daily_reports_dashboard_md.php" class="nav-link"><i class="fas fa-chart-line"></i> Reports</a></li>
      <li class="nav-item"><a href="md_leave_approval.php"          class="nav-link"><i class="fas fa-umbrella-beach"></i> Leave Approval</a></li>
      <li class="nav-item"><a href="mdmobile.php"                   class="nav-link"><i class="fas fa-mobile-alt"></i> Attendance</a></li>
      <li class="nav-item"><a href="tasks_md.php"                   class="nav-link active"><i class="fas fa-tasks"></i> Tasks</a></li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link danger"><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>Tasks</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">All Tasks</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username,0,1)) ?></div>
      <?= htmlspecialchars($username) ?>
    </div>
  </div>

  <div class="page">
    <div class="page-title">All Tasks Overview</div>
    <div class="page-subtitle">Create, track and manage tasks across all managers and employees</div>

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

    <!-- STAT CARDS -->
    <div class="stat-grid">
      <div class="stat-card">
        <div class="stat-icon" style="background:#e0f2fe"><i class="fas fa-layer-group" style="color:#0ea5e9"></i></div>
        <div><div class="stat-lbl">Total</div><div class="stat-num" style="color:#0ea5e9"><?= $total ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#dcfce7"><i class="fas fa-circle-check" style="color:#22c55e"></i></div>
        <div><div class="stat-lbl">Done</div><div class="stat-num" style="color:#22c55e"><?= $completed ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#dbeafe"><i class="fas fa-spinner" style="color:#2563eb"></i></div>
        <div><div class="stat-lbl">In Progress</div><div class="stat-num" style="color:#2563eb"><?= $in_progress ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#fef9c3"><i class="fas fa-hourglass-half" style="color:#f59e0b"></i></div>
        <div><div class="stat-lbl">Pending</div><div class="stat-num" style="color:#f59e0b"><?= $pending ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#fee2e2"><i class="fas fa-triangle-exclamation" style="color:#ef4444"></i></div>
        <div><div class="stat-lbl">Overdue</div><div class="stat-num" style="color:#ef4444"><?= $overdue ?></div></div>
      </div>
      <div class="progress-card">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span class="stat-lbl">Completion</span>
          <span style="font-size:14px;font-weight:700;color:var(--accent)"><?= $rate ?>%</span>
        </div>
        <div class="progress-bar-bg"><div class="progress-bar-fill" style="width:<?= $rate ?>%"></div></div>
      </div>
    </div>

    <!-- CREATE TASK -->
    <div class="panel">
      <div class="panel-header sky">
        <div>
          <div class="panel-title"><i class="fas fa-plus-circle" style="margin-right:6px"></i>Create New Task</div>
          <div class="panel-subtitle">Assign directly to a Manager or Employee</div>
        </div>
        <button class="btn btn-ghost btn-sm" id="toggleCreate" onclick="togglePanel()"><i class="fas fa-chevron-down" id="createChev"></i></button>
      </div>
      <div id="createBody" class="panel-body">
        <form method="POST" id="createForm">
          <input type="hidden" name="csrf"        value="<?= $csrf_token ?>">
          <input type="hidden" name="create_task" value="1">
          <input type="hidden" name="assigned_to" id="assignedToHidden">

          <div style="margin-bottom:16px">
            <div class="form-label" style="margin-bottom:8px">Assign To <span style="color:#dc2626">*</span></div>
            <div class="assign-tabs">
              <button type="button" class="atab active" id="tabMgr" onclick="switchTab('mgr')"><i class="fas fa-user-tie" style="margin-right:5px"></i>Manager</button>
              <button type="button" class="atab" id="tabEmp" onclick="switchTab('emp')"><i class="fas fa-user" style="margin-right:5px"></i>Employee</button>
            </div>
            <div class="tab-pane">
              <div id="paneMgr">
                <div class="form-group" style="max-width:360px">
                  <label class="form-label">Select Manager</label>
                  <select id="mgrSelect" class="form-select" onchange="sync()">
                    <option value="">— Select manager —</option>
                    <?php foreach ($managers as $m): ?>
                    <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['first_name'].' '.$m['last_name']) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div id="paneEmp" style="display:none">
                <div class="form-row">
                  <div class="form-group">
                    <label class="form-label">Filter by Manager <span style="font-weight:400;color:var(--muted)">(optional)</span></label>
                    <select id="empMgrFilter" class="form-select" onchange="filterEmps()">
                      <option value="0">All Managers</option>
                      <?php foreach ($managers as $m): ?>
                      <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['first_name'].' '.$m['last_name']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <div class="form-group">
                    <label class="form-label">Select Employee</label>
                    <select id="empSelect" class="form-select" onchange="sync()">
                      <option value="">— Select employee —</option>
                      <?php foreach ($employees as $e): ?>
                      <option value="<?= $e['id'] ?>" data-mgr="<?= (int)$e['reporting_manager_id'] ?>"><?= htmlspecialchars($e['first_name'].' '.$e['last_name']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group" style="flex:2;min-width:220px">
              <label class="form-label">Task Title <span style="color:#dc2626">*</span></label>
              <input type="text" name="title" class="form-control" placeholder="e.g. Prepare Q3 report" required maxlength="150">
            </div>
            <div class="form-group" style="min-width:130px">
              <label class="form-label">Priority</label>
              <select name="priority" class="form-select">
                <option value="Low">Low</option>
                <option value="Medium" selected>Medium</option>
                <option value="High">High</option>
              </select>
            </div>
            <div class="form-group" style="min-width:150px">
              <label class="form-label">Start Date <span style="color:#dc2626">*</span></label>
              <input type="date" name="start_date" class="form-control" required min="<?= $today ?>">
            </div>
            <div class="form-group" style="min-width:150px">
              <label class="form-label">Due Date <span style="color:#dc2626">*</span></label>
              <input type="date" name="due_date" class="form-control" required min="<?= $today ?>">
            </div>
          </div>
          <div class="form-row">
            <div class="form-group" style="flex:3">
              <label class="form-label">Description <span style="font-weight:400;color:var(--muted)">(optional)</span></label>
              <textarea name="description" class="form-control" rows="2" placeholder="Describe the task objectives…"></textarea>
            </div>
            <div class="form-group" style="justify-content:flex-end;min-width:160px">
              <label class="form-label">&nbsp;</label>
              <button type="submit" class="btn btn-ink" style="width:100%" onclick="return checkAssign()">
                <i class="fas fa-paper-plane"></i> Assign Task
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- BREAKDOWN -->
    <?php if (!empty($breakdown)): ?>
    <div class="panel">
      <div class="panel-header dark-hd">
        <div class="panel-title"><i class="fas fa-sitemap" style="margin-right:6px"></i>Assigner-wise Breakdown</div>
      </div>
      <div class="tbl-wrap">
        <table class="breakdown">
          <thead>
            <tr><th>Assigned By</th><th>Total</th><th>Done</th><th>In Progress</th><th>Pending</th><th>Completion</th></tr>
          </thead>
          <tbody>
            <?php foreach ($breakdown as $b):
              $br = $b['total']>0 ? round($b['done']/$b['total']*100) : 0; ?>
            <tr>
              <td style="font-weight:600"><i class="fas fa-user-tie" style="color:var(--muted);margin-right:6px"></i><?= htmlspecialchars($b['first_name'].' '.$b['last_name']) ?></td>
              <td style="font-weight:700"><?= $b['total'] ?></td>
              <td><span class="sbadge sc"><?= $b['done'] ?></span></td>
              <td><span class="sbadge si"><?= $b['inprog'] ?></span></td>
              <td><span class="sbadge" style="background:#fef9c3;color:#a16207"><?= $b['pend'] ?></span></td>
              <td>
                <div style="display:flex;align-items:center;gap:8px">
                  <div style="flex:1;background:#f1f5f9;border-radius:99px;height:6px;min-width:70px">
                    <div style="width:<?= $br ?>%;background:var(--accent);height:6px;border-radius:99px"></div>
                  </div>
                  <span style="font-size:11px;font-weight:700;color:var(--accent);min-width:32px"><?= $br ?>%</span>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

    <!-- FILTERS -->
    <div class="panel">
      <div class="panel-header">
        <div class="panel-title" style="display:flex;align-items:center;gap:6px"><i class="fas fa-filter" style="color:var(--accent)"></i> Filter Tasks</div>
        <?php if($filter['status']!=='all'||$filter['priority']!=='all'||$filter['manager']>0||$filter['employee']>0||$filter['from']||$filter['to']||$filter['search']): ?>
        <a href="tasks_md.php" class="btn btn-outline-danger btn-sm"><i class="fas fa-times"></i> Clear</a>
        <?php endif; ?>
      </div>
      <div class="panel-body">
        <form method="GET">
          <div class="filter-bar" style="background:var(--bg);border:none;padding:0;box-shadow:none;margin-bottom:0">
            <div class="filter-group">
              <span class="filter-label">Status</span>
              <select name="status" class="form-select form-select" style="min-width:120px;height:34px">
                <option value="all">All</option>
                <?php foreach(['Pending','In Progress','Completed'] as $s): ?>
                <option value="<?= $s ?>" <?= $filter['status']===$s?'selected':'' ?>><?= $s ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="filter-group">
              <span class="filter-label">Priority</span>
              <select name="priority" class="form-select" style="min-width:110px;height:34px">
                <option value="all">All</option>
                <?php foreach(['Low','Medium','High'] as $p): ?>
                <option value="<?= $p ?>" <?= $filter['priority']===$p?'selected':'' ?>><?= $p ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="filter-group">
              <span class="filter-label">Assigned By</span>
              <select name="manager" class="form-select" style="min-width:150px;height:34px">
                <option value="0">All</option>
                <?php foreach($managers as $m): ?>
                <option value="<?= $m['id'] ?>" <?= $filter['manager']==$m['id']?'selected':'' ?>><?= htmlspecialchars($m['first_name'].' '.$m['last_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="filter-group">
              <span class="filter-label">Assigned To</span>
              <select name="employee" class="form-select" style="min-width:150px;height:34px">
                <option value="0">All</option>
                <?php foreach($employees as $e): ?>
                <option value="<?= $e['id'] ?>" <?= $filter['employee']==$e['id']?'selected':'' ?>><?= htmlspecialchars($e['first_name'].' '.$e['last_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="filter-group">
              <span class="filter-label">Due From – To</span>
              <div style="display:flex;gap:4px">
                <input type="date" name="from" class="form-control" style="min-width:130px;height:34px" value="<?= htmlspecialchars($filter['from']) ?>">
                <input type="date" name="to"   class="form-control" style="min-width:130px;height:34px" value="<?= htmlspecialchars($filter['to']) ?>">
              </div>
            </div>
            <div class="filter-group grow">
              <span class="filter-label">Search Title</span>
              <input type="text" name="search" class="form-control" style="height:34px" placeholder="Type to search…" value="<?= htmlspecialchars($filter['search']) ?>">
            </div>
            <div style="display:flex;gap:6px;align-items:flex-end">
              <button type="submit" class="btn btn-ink btn-sm"><i class="fas fa-search"></i> Apply</button>
              <a href="tasks_md.php" class="btn btn-ghost btn-sm">Reset</a>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- TASK LIST -->
    <div class="section-head">
      <i class="fas fa-list-check" style="color:var(--accent)"></i>
      Task List
      <span class="section-cnt"><?= count($tasks) ?></span>
    </div>

    <?php if (empty($tasks)): ?>
    <div class="panel"><div class="panel-body" style="text-align:center;padding:48px;color:var(--muted)">
      <i class="fas fa-inbox" style="font-size:36px;display:block;margin-bottom:12px;opacity:.4"></i>
      <p>No tasks found for the selected filters.</p>
    </div></div>
    <?php endif; ?>

    <?php foreach ($tasks as $t):
      $is_overdue = ($t['due_date'] < $today && $t['status'] !== 'Completed');
      $pri_cls    = $t['priority']==='High'?'ph':($t['priority']==='Low'?'pl':'pm');
      $by_md      = ($t['assigner_role'] === 'md');
    ?>
    <div class="task-card <?= $is_overdue?'overdue':'' ?>">
      <div class="tc-header">
        <div>
          <div class="task-title"><?= htmlspecialchars($t['title']) ?></div>
          <div class="task-assignees">
            <i class="fas fa-user-tie"></i>
            <?= htmlspecialchars($t['mgr_first'].' '.$t['mgr_last']) ?>
            <?php if ($by_md): ?><span class="sbadge smd"><i class="fas fa-crown" style="font-size:.55rem"></i>MD</span><?php endif; ?>
            <span style="color:var(--border)">→</span>
            <i class="fas fa-user"></i>
            <?= htmlspecialchars($t['emp_first'].' '.$t['emp_last']) ?>
            <span style="color:var(--border)">(<?= htmlspecialchars($t['emp_role']) ?>)</span>
          </div>
        </div>
        <div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
          <span class="pbadge <?= $pri_cls ?>"><i class="fas fa-flag" style="font-size:.55rem"></i><?= $t['priority'] ?></span>
          <?php if($t['status']==='Completed'): ?><span class="sbadge sc"><i class="fas fa-circle-check" style="font-size:.6rem"></i>Completed</span>
          <?php elseif($t['status']==='In Progress'): ?><span class="sbadge si"><i class="fas fa-spinner fa-spin" style="font-size:.6rem"></i>In Progress</span>
          <?php else: ?><span class="sbadge sp">Pending</span><?php endif; ?>
          <?php if ($is_overdue): ?><span class="sbadge so"><i class="fas fa-triangle-exclamation" style="font-size:.6rem"></i>Overdue</span><?php endif; ?>
          <?php if (!empty($t['accepted'])): ?><span class="sbadge" style="background:#ede9fe;color:#6d28d9">Accepted</span><?php else: ?><span class="sbadge sna">Not Accepted</span><?php endif; ?>
        </div>
      </div>

      <div class="tc-body">
        <?php if (!empty($t['description'])): ?>
        <p style="font-size:12px;color:var(--muted);margin-bottom:10px"><?= htmlspecialchars($t['description']) ?></p>
        <?php endif; ?>
        <div class="meta-row">
          <div class="meta-item"><strong>Start</strong><?= htmlspecialchars($t['start_date']??'—') ?></div>
          <div class="meta-item"><strong>Due</strong><span class="<?= $is_overdue?'':'' ?>" style="<?= $is_overdue?'color:#dc2626;font-weight:700':'' ?>"><?= htmlspecialchars($t['due_date']??'—') ?></span></div>
          <div class="meta-item"><strong>Accepted At</strong><?= !empty($t['start_time'])?date('d M H:i',strtotime($t['start_time'])):'<em style="color:var(--muted)">—</em>' ?></div>
          <div class="meta-item"><strong>Finished At</strong><?= !empty($t['end_time'])?date('d M H:i',strtotime($t['end_time'])):'<em style="color:var(--muted)">—</em>' ?></div>
          <?php if (!empty($t['start_time']) && empty($t['end_time'])): ?>
          <div class="meta-item"><strong>Time</strong><span style="background:#eff6ff;color:#2563eb;border-radius:6px;padding:2px 8px;font-size:11px;font-weight:600"><i class="fas fa-stopwatch" style="margin-right:3px"></i>Ongoing</span></div>
          <?php elseif (!empty($t['end_time'])): ?>
          <div class="meta-item"><strong>Time Spent</strong><span style="background:#eff6ff;color:#2563eb;border-radius:6px;padding:2px 8px;font-size:11px;font-weight:600"><i class="fas fa-clock" style="margin-right:3px"></i><?= (int)$t['time_spent'] ?> min</span></div>
          <?php endif; ?>
        </div>
        <?php if (!empty($t['remarks'])): ?>
        <div class="remarks-box"><?= nl2br(htmlspecialchars($t['remarks'])) ?></div>
        <?php endif; ?>
      </div>

      <div class="tc-actions">
        <?php if ($t['status'] !== 'Completed'): ?>
        <form method="POST" style="display:flex;gap:6px;align-items:center">
          <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-select" style="width:auto;height:30px;font-size:11px;border-radius:7px">
            <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>
          <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check"></i> Update</button>
        </form>
        <?php else: ?>
          <span style="font-size:11px;color:var(--muted);font-style:italic"><i class="fas fa-lock" style="margin-right:4px"></i>Completed — locked</span>
        <?php endif; ?>

        <button class="btn btn-outline-accent btn-sm" onclick="toggleRemarks(<?= $t['task_id'] ?>)">
          <i class="fas fa-comment-dots"></i> Add Remarks
        </button>

        <form method="POST" style="margin-left:auto" onsubmit="return confirm('Delete this task permanently?')">
          <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 btn-outline-danger btn-sm"><i class="fas fa-trash"></i> Delete</button>
        </form>
      </div>

      <div id="remarks_<?= $t['task_id'] ?>" class="tc-remarks-panel" style="display:none">
        <form method="POST">
          <input type="hidden" name="csrf"            value="<?= $csrf_token ?>">
          <input type="hidden" name="save_md_remarks" value="1">
          <input type="hidden" name="task_id"         value="<?= $t['task_id'] ?>">
          <textarea name="md_remarks" class="form-control" rows="2" style="margin-bottom:8px" placeholder="Enter MD feedback…" required></textarea>
          <button type="submit" class="btn btn-ink btn-sm"><i class="fas fa-save"></i> Save Remarks</button>
        </form>
      </div>
    </div>
    <?php endforeach; ?>

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

<script>
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}

// Create panel toggle
let panelOpen = true;
function togglePanel(){
  panelOpen = !panelOpen;
  document.getElementById('createBody').style.display = panelOpen?'':'none';
  document.getElementById('createChev').className = panelOpen?'fas fa-chevron-up':'fas fa-chevron-down';
}

// Assign tabs
let activeTab = 'mgr';
function switchTab(tab){
  activeTab = tab;
  document.getElementById('paneMgr').style.display = tab==='mgr'?'':'none';
  document.getElementById('paneEmp').style.display = tab==='emp'?'':'none';
  document.getElementById('tabMgr').classList.toggle('active', tab==='mgr');
  document.getElementById('tabEmp').classList.toggle('active', tab==='emp');
  document.getElementById('assignedToHidden').value = '';
}
function sync(){
  const sel = activeTab==='mgr' ? document.getElementById('mgrSelect') : document.getElementById('empSelect');
  document.getElementById('assignedToHidden').value = sel.value;
}
function filterEmps(){
  const mgrId = parseInt(document.getElementById('empMgrFilter').value,10);
  const empSel = document.getElementById('empSelect');
  empSel.innerHTML = '<option value="">— Select employee —</option>';
  ALL_EMPLOYEES.forEach(e => {
    if(mgrId===0||parseInt(e.reporting_manager_id,10)===mgrId){
      const o=document.createElement('option');
      o.value=e.id; o.dataset.mgr=e.reporting_manager_id;
      o.textContent=e.first_name+' '+e.last_name;
      empSel.appendChild(o);
    }
  });
  document.getElementById('assignedToHidden').value='';
}
function checkAssign(){
  const v=document.getElementById('assignedToHidden').value;
  if(!v||v==='0'){ alert('Please select a Manager or Employee to assign the task.'); return false; }
  return true;
}

// Remarks toggle
function toggleRemarks(id){
  const el=document.getElementById('remarks_'+id);
  el.style.display=el.style.display==='none'?'block':'none';
}

// Auto-dismiss alert
const al=document.querySelector('.alert');
if(al) setTimeout(()=>al.style.opacity='0',4000);
</script>
</body>
</html>