<?php
/* TaskManagement.php - Enhanced Task Management with Dashboard
 * Pattern: Gradient banner + collapsible dashboard + CSS xcrud overlay
 * DB: direct mysqli to evergreentest | PHP 5.x compatible
 */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity = 0;

// ─── API MODE ───────────────────────────────────────────────
if (isset($_GET['api'])) {
    ob_start();
    include('includes/session.inc');
    ob_end_clean();
    header('Content-Type: application/json');

    $conn = new mysqli('localhost', 'sooggoo', '4Compassion*', 'evergreentest');
    if ($conn->connect_error) {
        echo json_encode(array('success' => false, 'error' => 'DB connection failed'));
        exit;
    }
    $conn->set_charset('utf8');
    $userId = isset($_SESSION['UserID']) ? $_SESSION['UserID'] : '';
    $action = isset($_GET['action']) ? $_GET['action'] : '';

    // ── Dashboard Metrics ──
    if ($action === 'dashboard') {
        $data = array();

        // Total tasks
        $r = $conn->query("SELECT COUNT(*) as cnt FROM task_management");
        $data['total'] = ($r) ? intval($r->fetch_assoc()['cnt']) : 0;

        // By status
        $r = $conn->query("SELECT
            COALESCE(status,'') as status,
            COUNT(*) as cnt
            FROM task_management GROUP BY status ORDER BY cnt DESC");
        $statuses = array();
        if ($r) { while ($row = $r->fetch_assoc()) { $statuses[] = $row; } }
        $data['by_status'] = $statuses;

        // By priority
        $r = $conn->query("SELECT
            COALESCE(priority,'') as priority,
            COUNT(*) as cnt
            FROM task_management GROUP BY priority ORDER BY cnt DESC");
        $priorities = array();
        if ($r) { while ($row = $r->fetch_assoc()) { $priorities[] = $row; } }
        $data['by_priority'] = $priorities;

        // By department
        $r = $conn->query("SELECT
            COALESCE(d.departmentname, 'Unassigned') as dept,
            COUNT(*) as cnt
            FROM task_management t
            LEFT JOIN department d ON t.allocated_to_department = d.departmentid
            GROUP BY dept ORDER BY cnt DESC LIMIT 10");
        $depts = array();
        if ($r) { while ($row = $r->fetch_assoc()) { $depts[] = $row; } }
        $data['by_department'] = $depts;

        // By user (top 10 assignees)
        $r = $conn->query("SELECT
            COALESCE(w.realname, t.allocated_to_user, 'Unassigned') as assignee,
            COUNT(*) as cnt
            FROM task_management t
            LEFT JOIN www_users w ON t.allocated_to_user = w.userid
            GROUP BY assignee ORDER BY cnt DESC LIMIT 10");
        $users = array();
        if ($r) { while ($row = $r->fetch_assoc()) { $users[] = $row; } }
        $data['by_user'] = $users;

        // Tasks created per month (last 12 months) — try date column
        $dateCol = 'date';
        $checkCol = $conn->query("SHOW COLUMNS FROM task_management LIKE 'date'");
        if (!$checkCol || $checkCol->num_rows == 0) {
            $checkCol2 = $conn->query("SHOW COLUMNS FROM task_management LIKE 'created_at'");
            if ($checkCol2 && $checkCol2->num_rows > 0) $dateCol = 'created_at';
            else {
                $checkCol3 = $conn->query("SHOW COLUMNS FROM task_management LIKE 'date_created'");
                if ($checkCol3 && $checkCol3->num_rows > 0) $dateCol = 'date_created';
                else $dateCol = '';
            }
        }
        $trend = array();
        if ($dateCol) {
            $r = $conn->query("SELECT DATE_FORMAT($dateCol, '%Y-%m') as mth, COUNT(*) as cnt
                               FROM task_management
                               WHERE $dateCol >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
                               GROUP BY mth ORDER BY mth");
            if ($r) { while ($row = $r->fetch_assoc()) { $trend[] = $row; } }
        }
        $data['monthly_trend'] = $trend;

        // Quick KPIs
        // Open/Pending
        $r = $conn->query("SELECT COUNT(*) as cnt FROM task_management WHERE LOWER(COALESCE(status,'')) IN ('open','pending','in progress','new','')");
        $data['open'] = ($r) ? intval($r->fetch_assoc()['cnt']) : 0;

        // Completed
        $r = $conn->query("SELECT COUNT(*) as cnt FROM task_management WHERE LOWER(COALESCE(status,'')) IN ('completed','done','closed','resolved')");
        $data['completed'] = ($r) ? intval($r->fetch_assoc()['cnt']) : 0;

        // Overdue (if due_date column exists)
        $data['overdue'] = 0;
        $checkDue = $conn->query("SHOW COLUMNS FROM task_management LIKE 'due_date'");
        if ($checkDue && $checkDue->num_rows > 0) {
            $r = $conn->query("SELECT COUNT(*) as cnt FROM task_management WHERE due_date < CURDATE() AND LOWER(COALESCE(status,'')) NOT IN ('completed','done','closed','resolved')");
            $data['overdue'] = ($r) ? intval($r->fetch_assoc()['cnt']) : 0;
        }

        // My tasks
        $safeUser = $conn->real_escape_string($userId);
        $r = $conn->query("SELECT COUNT(*) as cnt FROM task_management WHERE allocated_to_user='$safeUser' OR process_owner='$safeUser'");
        $data['my_tasks'] = ($r) ? intval($r->fetch_assoc()['cnt']) : 0;

        // Recent tasks (last 10)
        $orderCol = $dateCol ? $dateCol : 'id';
        $r = $conn->query("SELECT t.id, t.task,
            COALESCE(t.status,'') as status,
            COALESCE(t.priority,'') as priority,
            COALESCE(w.realname, t.allocated_to_user) as assigned_to,
            COALESCE(w2.realname, t.process_owner) as owner,
            COALESCE(d.departmentname,'') as dept
            " . ($dateCol ? ", t.$dateCol as task_date" : "") . "
            FROM task_management t
            LEFT JOIN www_users w ON t.allocated_to_user = w.userid
            LEFT JOIN www_users w2 ON t.process_owner = w2.userid
            LEFT JOIN department d ON t.allocated_to_department = d.departmentid
            ORDER BY t.$orderCol DESC LIMIT 10");
        $recent = array();
        if ($r) { while ($row = $r->fetch_assoc()) { $recent[] = $row; } }
        $data['recent'] = $recent;

        // Get all column names for schema awareness
        $cols = array();
        $cr = $conn->query("SHOW COLUMNS FROM task_management");
        if ($cr) { while ($row = $cr->fetch_assoc()) { $cols[] = $row['Field']; } }
        $data['columns'] = $cols;

        echo json_encode(array('success' => true, 'data' => $data));
        exit;
    }

    echo json_encode(array('success' => false, 'error' => 'Unknown action'));
    exit;
}

// ─── PAGE RENDER ────────────────────────────────────────────
include('includes/session.inc');
$Title = _('Task Management');

// ── Output header + loading modal, then flush ──
include('includes/newheader.php');
?>

<!-- Loading Modal -->
<div id="tmLoadingModal" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.92);z-index:99999;display:flex;align-items:center;justify-content:center;font-family:'Poppins',sans-serif;transition:opacity 0.5s;">
    <div style="text-align:center;">
        <div style="width:48px;height:48px;border:4px solid #E5E7EB;border-top-color:#2AABB3;border-radius:50%;animation:tmspin 0.8s linear infinite;margin:0 auto 16px;"></div>
        <div style="font-size:16px;font-weight:600;color:#1F2937;">Loading Task Management</div>
        <div style="font-size:13px;color:#6B7280;margin-top:4px;">Preparing dashboard & data...</div>
    </div>
</div>
<style>@keyframes tmspin{to{transform:rotate(360deg);}}</style>

<?php
// Force browser to render loading modal
if (function_exists('ob_flush')) { @ob_flush(); }
@flush();
?>

<style>
/* ─── Task Management Dashboard Styles ─── */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

:root {
    --tm-primary: #2AABB3;
    --tm-primary-dark: #1E8F96;
    --tm-primary-darker: #187278;
    --tm-primary-light: #E6F7F8;
    --tm-success: #52C41A;
    --tm-warning: #FAAD14;
    --tm-danger: #FF4D4F;
    --tm-purple: #8B5CF6;
    --tm-text: #1F2937;
    --tm-text-sec: #6B7280;
    --tm-border: #E5E7EB;
    --tm-bg: #F3F4F6;
    --tm-white: #FFFFFF;
    --tm-shadow: 0 1px 3px rgba(0,0,0,0.08);
    --tm-shadow-lg: 0 4px 15px rgba(0,0,0,0.1);
    --tm-radius: 10px;
}

.tm-wrapper { font-family: 'Poppins', sans-serif !important; color: var(--tm-text); }

/* ─── Banner ─── */
.tm-banner {
    background: linear-gradient(135deg, var(--tm-primary) 0%, var(--tm-primary-darker) 100%);
    padding: 22px 30px;
    color: white;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}
.tm-banner h1 { margin: 0; font-size: 22px; font-weight: 600; }
.tm-banner-sub { font-size: 13px; opacity: 0.85; margin-top: 2px; }
.tm-banner-actions { display: flex; gap: 10px; align-items: center; }
.tm-banner-btn {
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    padding: 8px 18px;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;
}
.tm-banner-btn-white { background: white; color: var(--tm-primary-dark); }
.tm-banner-btn-white:hover { background: #f0fffe; }
.tm-banner-btn-ghost { background: rgba(255,255,255,0.15); color: white; border: 1px solid rgba(255,255,255,0.3); }
.tm-banner-btn-ghost:hover { background: rgba(255,255,255,0.25); }

/* ─── Toggle ─── */
.tm-dash-toggle {
    padding: 10px 30px;
    background: white;
    border-bottom: 1px solid var(--tm-border);
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 600;
    color: var(--tm-primary-dark);
    user-select: none;
    transition: background 0.15s;
}
.tm-dash-toggle:hover { background: var(--tm-primary-light); }
.tm-dash-toggle .arrow { transition: transform 0.3s; font-size: 10px; }
.tm-dash-toggle .arrow.collapsed { transform: rotate(-90deg); }

/* ─── Dashboard ─── */
.tm-dashboard {
    padding: 20px 28px 24px;
    background: var(--tm-bg);
    overflow: hidden;
    transition: max-height 0.4s ease, padding 0.3s ease;
}
.tm-dashboard.collapsed { max-height: 0 !important; padding: 0 28px; overflow: hidden; }

/* KPI Grid */
.tm-kpi-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
    margin-bottom: 20px;
}
.tm-kpi {
    background: white;
    border-radius: var(--tm-radius);
    padding: 18px;
    box-shadow: var(--tm-shadow);
    border-left: 4px solid var(--tm-primary);
    transition: transform 0.2s, box-shadow 0.2s;
}
.tm-kpi:hover { transform: translateY(-2px); box-shadow: var(--tm-shadow-lg); }
.tm-kpi-icon { font-size: 22px; margin-bottom: 8px; }
.tm-kpi-value { font-size: 28px; font-weight: 700; line-height: 1; margin-bottom: 4px; }
.tm-kpi-label { font-size: 11px; color: var(--tm-text-sec); text-transform: uppercase; letter-spacing: 0.5px; font-weight: 500; }

/* Chart Grid */
.tm-chart-grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 16px;
    margin-bottom: 20px;
}
.tm-chart-card {
    background: white;
    border-radius: var(--tm-radius);
    padding: 18px;
    box-shadow: var(--tm-shadow);
}
.tm-chart-title { font-size: 14px; font-weight: 600; margin: 0 0 2px; }
.tm-chart-sub { font-size: 11px; color: var(--tm-text-sec); margin: 0 0 14px; }
.tm-chart-container { position: relative; height: 220px; }

/* Recent Tasks */
.tm-recent-card {
    background: white;
    border-radius: var(--tm-radius);
    padding: 18px;
    box-shadow: var(--tm-shadow);
}
.tm-recent-title { font-size: 14px; font-weight: 600; margin: 0 0 14px; display: flex; align-items: center; gap: 8px; }
.tm-recent-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.tm-recent-table th {
    text-align: left;
    padding: 8px 12px;
    background: var(--tm-bg);
    font-weight: 600;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    color: var(--tm-text-sec);
    border-bottom: 2px solid var(--tm-border);
}
.tm-recent-table td {
    padding: 9px 12px;
    border-bottom: 1px solid var(--tm-border);
}
.tm-recent-table tr:hover td { background: #FAFBFC; }
.tm-status-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: capitalize;
}
.tm-priority-dot {
    width: 8px; height: 8px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 4px;
}

/* ─── Xcrud Overlay ─── */
.tm-xcrud-section { padding: 0 24px 30px; }

.tm-xcrud-section .xcrud-nav { font-family: 'Poppins', sans-serif !important; }

/* Xcrud table styling */
.tm-xcrud-section .xcrud-row,
.tm-xcrud-section .xcrud-list {
    font-family: 'Poppins', sans-serif !important;
}
.tm-xcrud-section .xcrud-list .xcrud-thead th {
    background: linear-gradient(135deg, var(--tm-primary) 0%, var(--tm-primary-dark) 100%) !important;
    color: white !important;
    font-family: 'Poppins', sans-serif !important;
    font-weight: 600 !important;
    font-size: 12px !important;
    text-transform: uppercase !important;
    letter-spacing: 0.5px !important;
    padding: 12px 14px !important;
    border: none !important;
}
.tm-xcrud-section .xcrud-list td {
    font-family: 'Poppins', sans-serif !important;
    font-size: 13px !important;
    padding: 10px 14px !important;
    border-bottom: 1px solid var(--tm-border) !important;
    vertical-align: middle !important;
}
.tm-xcrud-section .xcrud-list tr:hover td { background: var(--tm-primary-light) !important; }
.tm-xcrud-section .xcrud-list tr:nth-child(even) td { background: #FAFBFC !important; }
.tm-xcrud-section .xcrud-list tr:nth-child(even):hover td { background: var(--tm-primary-light) !important; }
.tm-xcrud-section .xcrud-top,
.tm-xcrud-section .xcrud-nav {
    background: white !important;
    border: 1px solid var(--tm-border) !important;
    border-radius: 8px 8px 0 0 !important;
    padding: 12px 16px !important;
}
.tm-xcrud-section .xcrud-list { border-radius: 0 0 8px 8px !important; overflow: hidden; box-shadow: var(--tm-shadow); }

/* Buttons inside xcrud */
.tm-xcrud-section .xcrud-action,
.tm-xcrud-section .btn-default,
.tm-xcrud-section .xcrud-search-toggle,
.tm-xcrud-section .xcrud-csv {
    font-family: 'Poppins', sans-serif !important;
    border-radius: 6px !important;
    font-size: 12px !important;
    font-weight: 500 !important;
}
.tm-xcrud-section .btn-primary,
.tm-xcrud-section .xcrud-save {
    background: var(--tm-primary) !important;
    border-color: var(--tm-primary) !important;
    color: white !important;
    font-family: 'Poppins', sans-serif !important;
    border-radius: 6px !important;
}
.tm-xcrud-section .btn-primary:hover,
.tm-xcrud-section .xcrud-save:hover { background: var(--tm-primary-dark) !important; }

/* Xcrud pagination */
.tm-xcrud-section .xcrud-pagination a,
.tm-xcrud-section .xcrud-pagination span {
    border-radius: 6px !important;
    font-family: 'Poppins', sans-serif !important;
    font-size: 12px !important;
}
.tm-xcrud-section .xcrud-pagination .active a {
    background: var(--tm-primary) !important;
    border-color: var(--tm-primary) !important;
}

/* Xcrud tabs */
.tm-xcrud-section .xcrud-nav-tabs > li > a {
    font-family: 'Poppins', sans-serif !important;
    font-weight: 500 !important;
    border-radius: 8px 8px 0 0 !important;
}
.tm-xcrud-section .xcrud-nav-tabs > li.active > a {
    color: var(--tm-primary-dark) !important;
    border-bottom-color: var(--tm-primary) !important;
}

/* Responsive */
@media (max-width: 1200px) { .tm-kpi-grid { grid-template-columns: repeat(3, 1fr); } .tm-chart-grid { grid-template-columns: 1fr 1fr; } }
@media (max-width: 768px) { .tm-kpi-grid { grid-template-columns: 1fr 1fr; } .tm-chart-grid { grid-template-columns: 1fr; } .tm-banner { padding: 16px; } }
</style>

<div class="tm-wrapper">
    <!-- Banner -->
    <div class="tm-banner">
        <div>
            <div class="tm-banner-sub">Home &gt; Task Management</div>
            <h1>📋 Task Management</h1>
        </div>
        <div class="tm-banner-actions">
            <button class="tm-banner-btn tm-banner-btn-ghost" onclick="window.location.href='KanbanBoard.php'">📊 Kanban Board</button>
            <button class="tm-banner-btn tm-banner-btn-white" onclick="document.querySelector('.xcrud-action[data-task=create],.xcrud-action[title=Add],.xcrud-add').click()">＋ New Task</button>
        </div>
    </div>

    <!-- Dashboard Toggle -->
    <div class="tm-dash-toggle" id="tmToggle" onclick="TM.toggleDash()">
        <span class="arrow" id="tmArrow">▼</span> Dashboard & Analytics
    </div>

    <!-- Dashboard -->
    <div class="tm-dashboard" id="tmDashboard">
        <!-- KPIs -->
        <div class="tm-kpi-grid" id="tmKpiGrid">
            <div class="tm-kpi" style="border-left-color:var(--tm-primary);">
                <div class="tm-kpi-icon">📋</div>
                <div class="tm-kpi-value" id="kpiTotal">-</div>
                <div class="tm-kpi-label">Total Tasks</div>
            </div>
            <div class="tm-kpi" style="border-left-color:#F97316;">
                <div class="tm-kpi-icon">⏳</div>
                <div class="tm-kpi-value" id="kpiOpen">-</div>
                <div class="tm-kpi-label">Open / Pending</div>
            </div>
            <div class="tm-kpi" style="border-left-color:var(--tm-success);">
                <div class="tm-kpi-icon">✅</div>
                <div class="tm-kpi-value" id="kpiCompleted">-</div>
                <div class="tm-kpi-label">Completed</div>
            </div>
            <div class="tm-kpi" style="border-left-color:var(--tm-danger);">
                <div class="tm-kpi-icon">⚠️</div>
                <div class="tm-kpi-value" id="kpiOverdue">-</div>
                <div class="tm-kpi-label">Overdue</div>
            </div>
            <div class="tm-kpi" style="border-left-color:var(--tm-purple);">
                <div class="tm-kpi-icon">👤</div>
                <div class="tm-kpi-value" id="kpiMyTasks">-</div>
                <div class="tm-kpi-label">My Tasks</div>
            </div>
        </div>

        <!-- Charts -->
        <div class="tm-chart-grid">
            <div class="tm-chart-card">
                <div class="tm-chart-title">📊 Status Distribution</div>
                <div class="tm-chart-sub">Task breakdown by current status</div>
                <div class="tm-chart-container"><canvas id="chartStatus"></canvas></div>
            </div>
            <div class="tm-chart-card">
                <div class="tm-chart-title">👥 Department Workload</div>
                <div class="tm-chart-sub">Tasks allocated per department</div>
                <div class="tm-chart-container"><canvas id="chartDept"></canvas></div>
            </div>
            <div class="tm-chart-card">
                <div class="tm-chart-title">📈 Monthly Trend</div>
                <div class="tm-chart-sub">Tasks created over time</div>
                <div class="tm-chart-container"><canvas id="chartTrend"></canvas></div>
            </div>
        </div>

        <!-- Recent Tasks Table -->
        <div class="tm-recent-card">
            <div class="tm-recent-title">🕐 Recent Tasks</div>
            <table class="tm-recent-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Subject</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Assigned To</th>
                        <th>Department</th>
                        <th>Owner</th>
                    </tr>
                </thead>
                <tbody id="tmRecentBody">
                    <tr><td colspan="7" style="text-align:center;padding:20px;color:var(--tm-text-sec);">Loading...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Xcrud Section -->
    <div class="tm-xcrud-section">
        <?php
        echo '<div class="col-sm-12">';
        $userid = $_SESSION['UserID'];

        include('xcrud/xcrud.php');
        $xcrud = Xcrud::get_instance();
        $xcrud->table('task_management');
        $xcrud->order_by('id', 'desc');
        $xcrud->default_tab('Task Profile');

        $xcrud->relation('allocated_to_department', 'department', 'departmentid', 'departmentname');
        $xcrud->relation('allocated_to_user', 'www_users', 'userid', 'realname');
        $xcrud->relation('process_owner', 'www_users', 'userid', 'realname');

        $timenow = date('Y-m-d H:i:s');
        $log = "Entered by: " . $userid . " Date : " . $timenow;
        $xcrud->pass_default('log', $log);
        $xcrud->pass_var('log', $log);
        $xcrud->before_insert('taskmanagement');
        $xcrud->before_update('update_logtask');
        $xcrud->disabled('log');
        $xcrud->unset_remove();
        $xcrud->label('task', 'Subject (short description not more than 20 characters)');
        $xcrud->label('allocated_to_user', 'Who will do this task?');

        $attachments = $xcrud->nested_table('Task Files', 'id', 'task_attachments', 'id');
        $attachments->change_type('image', 'image', '', array('thumbs' =>
            array(
                array('width' => '200', 'height' => '200', 'marker' => '_th'),
                array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
            )));

        echo $xcrud->render();
        echo '</div>';
        ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
var TM = {
    charts: [],
    palette: ['#2AABB3','#8B5CF6','#F97316','#EC4899','#22C55E','#EAB308','#6366F1','#06B6D4','#EF4444','#14B8A6','#F43F5E','#0EA5E9'],

    statusColors: {
        'open': '#3B82F6', 'new': '#3B82F6', 'pending': '#F59E0B', 'in progress': '#8B5CF6',
        'completed': '#22C55E', 'done': '#22C55E', 'closed': '#94A3B8', 'resolved': '#06B6D4',
        'on hold': '#EF4444', 'cancelled': '#9CA3AF', '': '#D1D5DB'
    },
    priorityColors: {
        'urgent': '#EF4444', 'high': '#F97316', 'medium': '#EAB308', 'low': '#22C55E',
        'critical': '#DC2626', 'normal': '#3B82F6', '': '#D1D5DB'
    },

    init: function() {
        // Restore toggle state
        var saved = localStorage.getItem('tm_dash_collapsed');
        if (saved === '1') {
            document.getElementById('tmDashboard').classList.add('collapsed');
            document.getElementById('tmArrow').classList.add('collapsed');
        }
        TM.loadDashboard();
    },

    toggleDash: function() {
        var dash = document.getElementById('tmDashboard');
        var arrow = document.getElementById('tmArrow');
        if (dash.classList.contains('collapsed')) {
            dash.classList.remove('collapsed');
            dash.style.maxHeight = dash.scrollHeight + 'px';
            arrow.classList.remove('collapsed');
            localStorage.setItem('tm_dash_collapsed', '0');
        } else {
            dash.style.maxHeight = dash.scrollHeight + 'px';
            setTimeout(function() { dash.classList.add('collapsed'); }, 10);
            arrow.classList.add('collapsed');
            localStorage.setItem('tm_dash_collapsed', '1');
        }
    },

    loadDashboard: function() {
        fetch('TaskManagement.php?api=1&action=dashboard')
        .then(function(r) { return r.json(); })
        .then(function(r) {
            if (!r.success) return;
            var d = r.data;

            // KPIs
            document.getElementById('kpiTotal').textContent = d.total;
            document.getElementById('kpiOpen').textContent = d.open;
            document.getElementById('kpiCompleted').textContent = d.completed;
            document.getElementById('kpiOverdue').textContent = d.overdue;
            document.getElementById('kpiMyTasks').textContent = d.my_tasks;

            // Completion % badge
            var pct = d.total > 0 ? Math.round((d.completed / d.total) * 100) : 0;

            TM.renderCharts(d);
            TM.renderRecentTable(d.recent);

            // Fade out loading modal
            var modal = document.getElementById('tmLoadingModal');
            if (modal) {
                modal.style.opacity = '0';
                setTimeout(function() { modal.style.display = 'none'; }, 500);
            }

            // Set dashboard max-height for animation
            var dash = document.getElementById('tmDashboard');
            if (!dash.classList.contains('collapsed')) {
                dash.style.maxHeight = dash.scrollHeight + 'px';
            }
        })
        .catch(function() {
            var modal = document.getElementById('tmLoadingModal');
            if (modal) { modal.style.opacity = '0'; setTimeout(function() { modal.style.display = 'none'; }, 500); }
        });
    },

    renderCharts: function(d) {
        TM.charts.forEach(function(c) { if(c) c.destroy(); });
        TM.charts = [];

        var defaultFont = { family: 'Poppins', size: 11 };

        // 1. Status Distribution (doughnut)
        if (d.by_status.length > 0) {
            var sLabels = d.by_status.map(function(s) { return s.status || 'Unset'; });
            var sData = d.by_status.map(function(s) { return parseInt(s.cnt); });
            var sColors = d.by_status.map(function(s) {
                return TM.statusColors[(s.status || '').toLowerCase()] || TM.palette[Math.floor(Math.random()*TM.palette.length)];
            });
            TM.charts.push(new Chart(document.getElementById('chartStatus'), {
                type: 'doughnut',
                data: {
                    labels: sLabels,
                    datasets: [{ data: sData, backgroundColor: sColors, borderWidth: 2, borderColor: '#fff', hoverOffset: 8 }]
                },
                options: {
                    responsive: true, maintainAspectRatio: false, cutout: '58%',
                    plugins: { legend: { position: 'bottom', labels: { padding: 12, usePointStyle: true, pointStyle: 'circle', font: defaultFont } } }
                }
            }));
        }

        // 2. Department Workload (horizontal bar)
        if (d.by_department.length > 0) {
            var dLabels = d.by_department.map(function(x) { return x.dept; });
            var dData = d.by_department.map(function(x) { return parseInt(x.cnt); });
            var dColors = d.by_department.map(function(x, i) { return TM.palette[i % TM.palette.length]; });
            TM.charts.push(new Chart(document.getElementById('chartDept'), {
                type: 'bar',
                data: {
                    labels: dLabels,
                    datasets: [{ label: 'Tasks', data: dData, backgroundColor: dColors, borderRadius: 5, borderSkipped: false }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true, maintainAspectRatio: false,
                    scales: {
                        x: { beginAtZero: true, grid: { color: '#F3F4F6' }, ticks: { font: defaultFont } },
                        y: { grid: { display: false }, ticks: { font: defaultFont } }
                    },
                    plugins: { legend: { display: false } }
                }
            }));
        }

        // 3. Monthly Trend (line)
        if (d.monthly_trend.length > 0) {
            var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            var tLabels = d.monthly_trend.map(function(m) {
                var parts = m.mth.split('-');
                return months[parseInt(parts[1])-1] + ' ' + parts[0].slice(2);
            });
            var tData = d.monthly_trend.map(function(m) { return parseInt(m.cnt); });
            TM.charts.push(new Chart(document.getElementById('chartTrend'), {
                type: 'line',
                data: {
                    labels: tLabels,
                    datasets: [{
                        label: 'Tasks Created',
                        data: tData,
                        borderColor: '#2AABB3',
                        backgroundColor: 'rgba(42,171,179,0.12)',
                        fill: true,
                        tension: 0.4,
                        pointRadius: 4,
                        pointHoverRadius: 7,
                        pointBackgroundColor: '#2AABB3',
                        borderWidth: 2.5
                    }]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    scales: {
                        x: { grid: { display: false }, ticks: { font: defaultFont } },
                        y: { beginAtZero: true, grid: { color: '#F3F4F6' }, ticks: { font: defaultFont, stepSize: 1 } }
                    },
                    plugins: { legend: { display: false } }
                }
            }));
        } else {
            document.getElementById('chartTrend').parentElement.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--tm-text-sec);font-size:13px;">No date column found for trend</div>';
        }
    },

    renderRecentTable: function(recent) {
        var tbody = document.getElementById('tmRecentBody');
        if (!recent || recent.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--tm-text-sec);">No tasks found</td></tr>';
            return;
        }
        var html = '';
        recent.forEach(function(t) {
            var statusLower = (t.status || '').toLowerCase();
            var statusColor = TM.statusColors[statusLower] || '#D1D5DB';
            var priColor = TM.priorityColors[(t.priority || '').toLowerCase()] || '#D1D5DB';

            html += '<tr>';
            html += '<td><strong>#' + t.id + '</strong></td>';
            html += '<td>' + TM.esc(t.task || '') + '</td>';
            html += '<td><span class="tm-status-badge" style="background:' + TM.hexToRgba(statusColor, 0.15) + ';color:' + statusColor + ';">' + TM.esc(t.status || 'Unset') + '</span></td>';
            html += '<td><span class="tm-priority-dot" style="background:' + priColor + ';"></span>' + TM.esc(t.priority || '—') + '</td>';
            html += '<td>' + TM.esc(t.assigned_to || '—') + '</td>';
            html += '<td>' + TM.esc(t.dept || '—') + '</td>';
            html += '<td>' + TM.esc(t.owner || '—') + '</td>';
            html += '</tr>';
        });
        tbody.innerHTML = html;
    },

    esc: function(s) {
        if (!s) return '';
        var d = document.createElement('div');
        d.appendChild(document.createTextNode(s));
        return d.innerHTML;
    },

    hexToRgba: function(hex, alpha) {
        if (!hex || hex.charAt(0) !== '#') return 'rgba(200,200,200,' + alpha + ')';
        var r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
        return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
    }
};

// Init on DOM ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', TM.init);
} else {
    TM.init();
}

// Refresh dashboard after xcrud operations
jQuery(document).on('xcrudafterrequest', function() {
    TM.loadDashboard();
});
</script>

<?php
include('includes/MainMenuLinksArray.php');
?>