<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';
require_once __DIR__ . '/../../config/RencanaKerjaPermission.php';

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = isset($_SESSION['role']) ? strtolower(trim($_SESSION['role'])) : '';
$userId = (int) $_SESSION['user_id'];
$userDept = $_SESSION['department'] ?? null;

// Initialize permission checker
$permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $userRole);
$permSummary = $permission->getPermissionSummary();

// Debug: Check database connection
if (!$conn) {
    die("Database connection failed!");
}

// Get filters
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$filterDepartment = isset($_GET['department']) ? $_GET['department'] : '';

// Build WHERE conditions
$whereConditions = ["rk.is_deleted = 0"];
$params = [];
$types = '';

// Role-based filtering
if ($userRole === 'dept_head' && $userDept) {
    $whereConditions[] = "assignee.department = ?";
    $params[] = $userDept;
    $types .= 's';
} elseif ($userRole === 'staff') {
    $whereConditions[] = "rk.assigned_to = ?";
    $params[] = $userId;
    $types .= 'i';
}

// Date filters
if ($dateFrom && $dateTo) {
    $whereConditions[] = "rk.tenggat_waktu BETWEEN ? AND ?";
    $params[] = $dateFrom;
    $params[] = $dateTo;
    $types .= 'ss';
} elseif ($dateFrom) {
    $whereConditions[] = "rk.tenggat_waktu >= ?";
    $params[] = $dateFrom;
    $types .= 's';
} elseif ($dateTo) {
    $whereConditions[] = "rk.tenggat_waktu <= ?";
    $params[] = $dateTo;
    $types .= 's';
}

// Department filter (only for admin/director)
if ($filterDepartment && in_array($userRole, ['admin', 'director'])) {
    $whereConditions[] = "assignee.department = ?";
    $params[] = $filterDepartment;
    $types .= 's';
}

$whereClause = implode(' AND ', $whereConditions);

// Main query
$sql = "
    SELECT 
        rk.*,
        creator.full_name AS creator_name,
        assignee.full_name AS assignee_name,
        assignee.department AS department,
        approver.full_name AS approver_name
    FROM rencana_kerja rk
    LEFT JOIN users creator ON rk.created_by = creator.id
    LEFT JOIN users assignee ON rk.assigned_to = assignee.id
    LEFT JOIN users approver ON rk.approval_by = approver.id
    WHERE $whereClause
    ORDER BY assignee.department ASC, rk.tenggat_waktu ASC
";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    die("Query preparation failed: " . $conn->error);
}

// Bind parameters if any
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$allTasks = [];
if ($result && $result->num_rows > 0) {
    while ($task = $result->fetch_assoc()) {
        $task['creator_name'] = $task['creator_name'] ?? 'N/A';
        $task['assignee_name'] = $task['assignee_name'] ?? 'N/A';
        $task['approver_name'] = $task['approver_name'] ?? 'N/A';
        $allTasks[] = $task;
    }
}

$stmt->close();

// Statistics query
$statsSql = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN status = 'stuck' THEN 1 ELSE 0 END) as stuck,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
    FROM rencana_kerja rk
    LEFT JOIN users assignee ON rk.assigned_to = assignee.id
    WHERE $whereClause
";

$statsStmt = $conn->prepare($statsSql);

if (!$statsStmt) {
    $stats = ['total' => 0, 'completed' => 0, 'in_progress' => 0, 'stuck' => 0, 'pending' => 0];
} else {
    if (!empty($params)) {
        $statsStmt->bind_param($types, ...$params);
    }
    $statsStmt->execute();
    $statsResult = $statsStmt->get_result();
    $stats = $statsResult->fetch_assoc();
    $statsStmt->close();
}

// Get all departments for filter dropdown (admin/director only)
$allDepartments = [];
if (in_array($userRole, ['admin', 'director'])) {
    $deptSql = "SELECT DISTINCT department FROM users WHERE department IS NOT NULL AND department != '' ORDER BY department";
    $deptResult = $conn->query($deptSql);
    if ($deptResult) {
        while ($row = $deptResult->fetch_assoc()) {
            $allDepartments[] = $row['department'];
        }
    }
}

// Group tasks by department
$tasksByDept = [];
foreach ($allTasks as $task) {
    $dept = $task['department'] ?? 'Tidak Ada Department';
    if (!isset($tasksByDept[$dept])) {
        $tasksByDept[$dept] = [];
    }
    $tasksByDept[$dept][] = $task;
}
ksort($tasksByDept);

// Pagination settings
$itemsPerPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, $currentPage);
$totalItems = count($allTasks);
$totalPages = ceil($totalItems / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;
$paginatedTasks = array_slice($allTasks, $offset, $itemsPerPage);

// Page title based on role
$pageTitle = match($userRole) {
    'admin' => 'Rencana Kerja - Admin',
    'director' => 'Rencana Kerja - Director',
    'dept_head' => 'Rencana Kerja - Department Head',
    'staff' => 'Rencana Kerja - Staff',
    default => 'Rencana Kerja'
};

$addTaskUrl = 'pages/rencana_kerja/add_rencana_kerja.php';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            color: #1e293b;
            min-height: 100vh;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        /* Header Styles */
        .header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 30px 40px;
            border-radius: 20px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(122, 178, 178, 0.3);
            position: sticky;
            top: 20px;
            z-index: 100;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header-icon {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(10px);
        }

        .header-icon i {
            font-size: 28px;
        }

        .header-title h1 {
            font-size: 28px;
            font-weight: 900;
            margin-bottom: 5px;
            letter-spacing: -0.5px;
        }

        .header-title p {
            font-size: 14px;
            opacity: 0.9;
            font-weight: 500;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            padding: 12px 20px 12px 45px;
            border: 2px solid rgba(255,255,255,0.3);
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            color: white;
            font-size: 14px;
            width: 260px;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .search-box input::placeholder {
            color: rgba(255,255,255,0.7);
        }

        .search-box input:focus {
            outline: none;
            background: rgba(255,255,255,0.25);
            border-color: white;
            width: 320px;
        }

        .search-box i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255,255,255,0.8);
            font-size: 16px;
        }

        .date-filter {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .date-input, .dept-select {
            padding: 12px 16px;
            border: 2px solid rgba(255,255,255,0.3);
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            color: white;
            font-size: 14px;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .date-input:focus, .dept-select:focus {
            outline: none;
            background: rgba(255,255,255,0.25);
            border-color: white;
        }

        .date-input::-webkit-calendar-picker-indicator {
            filter: invert(1);
            cursor: pointer;
        }

        .dept-select {
            min-width: 180px;
        }

        .dept-select option {
            background: #4D869C;
            color: white;
        }

        .btn-primary {
            padding: 12px 24px;
            background: white;
            color: #7AB2B2;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(255,255,255,0.3);
        }

        /* Statistics Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
            cursor: pointer;
            border-top: 4px solid var(--color);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: var(--color);
            opacity: 0.1;
            transform: translate(30%, -30%);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.15);
        }

        .stat-card.total { --color: #3b82f6; }
        .stat-card.done { --color: #10b981; }
        .stat-card.progress { --color: #f59e0b; }
        .stat-card.stuck { --color: #ef4444; }
        .stat-card.pending { --color: #64748b; }

        .stat-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            background: var(--color);
            color: white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }

        .stat-info {
            flex: 1;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 900;
            color: #1e293b;
            line-height: 1;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 12px;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-detail {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
            position: relative;
            z-index: 1;
        }

        .stat-detail.show {
            max-height: 500px;
        }

        .stat-footer {
            padding-top: 15px;
            border-top: 2px solid #f1f5f9;
            margin-top: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            z-index: 1;
        }

        .stat-footer span {
            font-size: 12px;
            font-weight: 600;
            color: #64748b;
        }

        .stat-footer i {
            color: var(--color);
            transition: transform 0.3s ease;
        }

        .stat-card:hover .stat-footer i {
            transform: translateY(2px);
        }

        .dept-breakdown {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #e2e8f0;
        }

        .dept-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 0;
            font-size: 13px;
        }

        .dept-name {
            color: #64748b;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .dept-count {
            font-weight: 800;
            color: var(--color);
            background: rgba(var(--color-rgb), 0.1);
            padding: 4px 12px;
            border-radius: 20px;
        }

        /* View Switcher */
        .view-controls {
            background: white;
            padding: 20px 30px;
            border-radius: 16px;
            margin-bottom: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 20px;
        }

        .view-tabs {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .view-tab {
            padding: 10px 20px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
        }

        .view-tab:hover {
            border-color: #7AB2B2;
            color: #7AB2B2;
        }

        .view-tab.active {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            border-color: #7AB2B2;
            color: white;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        /* Department Navigation */
        .dept-nav {
            background: white;
            padding: 20px 30px;
            border-radius: 16px;
            margin-bottom: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .dept-nav h3 {
            font-size: 14px;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .dept-nav-links {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .dept-nav-link {
            padding: 10px 18px;
            background: linear-gradient(135deg, #f8fafc, #e2e8f0);
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            text-decoration: none;
            color: #1e293b;
            font-size: 13px;
            font-weight: 700;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .dept-nav-link:hover {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            border-color: #7AB2B2;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        .dept-nav-count {
            padding: 3px 10px;
            background: rgba(255,255,255,0.5);
            border-radius: 12px;
            font-size: 11px;
            font-weight: 900;
        }

        .dept-nav-link:hover .dept-nav-count {
            background: rgba(255,255,255,0.3);
        }

        /* Table Styles */
        .table-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead {
            background: linear-gradient(135deg, #f8fafc, #e2e8f0);
        }

        th {
            padding: 18px 20px;
            text-align: left;
            font-size: 12px;
            font-weight: 800;
            color: #1e293b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 3px solid #e2e8f0;
        }

        tbody tr {
            border-bottom: 1px solid #f1f5f9;
            transition: all 0.2s ease;
        }

        tbody tr:hover {
            background: #f8fafc;
        }

        td {
            padding: 18px 20px;
            color: #334155;
            font-size: 14px;
        }

        .task-title {
            font-weight: 700;
            color: #1e293b;
            font-size: 15px;
            margin-bottom: 5px;
        }

        .task-desc {
            font-size: 12px;
            color: #64748b;
            margin-top: 5px;
        }

        .dept-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 14px;
            background: linear-gradient(135deg, #e0f2fe, #dbeafe);
            border: 2px solid #bae6fd;
            border-radius: 10px;
            font-size: 12px;
            font-weight: 700;
            color: #0369a1;
        }

        .progress-container {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .progress-bar {
            flex: 1;
            height: 8px;
            background: #e2e8f0;
            border-radius: 10px;
            overflow: hidden;
            max-width: 100px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #7AB2B2, #4D869C);
            border-radius: 10px;
            transition: width 0.3s ease;
        }

        .progress-text {
            font-size: 13px;
            font-weight: 900;
            color: #1e293b;
            min-width: 45px;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 14px;
            border-radius: 10px;
            font-size: 12px;
            font-weight: 700;
            border: 2px solid;
        }

        .status-badge.done {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #065f46;
            border-color: #6ee7b7;
        }

        .status-badge.progress {
            background: linear-gradient(135deg, #dbeafe, #bfdbfe);
            color: #1e40af;
            border-color: #93c5fd;
        }

        .status-badge.stuck {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            border-color: #fca5a5;
        }

        .status-badge.pending {
            background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
            color: #475569;
            border-color: #cbd5e1;
        }

        .assignee {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .assignee-avatar {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 900;
            font-size: 16px;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        .assignee-name {
            font-weight: 700;
            color: #1e293b;
            font-size: 14px;
        }

        /* Action Buttons */
        .actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }

        .action-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .action-btn.view {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
        }

        .action-btn.view:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        }

        .action-btn.edit {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
        }

        .action-btn.edit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
        }

        .action-btn.delete {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }

        .action-btn.delete:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
        }

        /* Department View */
        .dept-section {
            background: white;
            border-radius: 16px;
            margin-bottom: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            scroll-margin-top: 100px;
        }

        .dept-header {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            padding: 25px 30px;
            color: white;
        }

        .dept-header h2 {
            font-size: 24px;
            font-weight: 900;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .dept-count-badge {
            padding: 6px 18px;
            background: rgba(255,255,255,0.2);
            border-radius: 20px;
            font-size: 14px;
            font-weight: 800;
            margin-left: auto;
        }

        .dept-tasks {
            padding: 30px;
        }

        .task-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
        }

        .task-card {
            background: linear-gradient(135deg, #ffffff, #f8fafc);
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .task-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.15);
            border-color: #7AB2B2;
        }

        .task-card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }

        .task-card-title {
            font-weight: 800;
            color: #1e293b;
            font-size: 15px;
            line-height: 1.4;
            flex: 1;
        }

        .task-card-status {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            margin-left: 10px;
        }

        .task-card-assignee {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 0;
            border-top: 2px solid #f1f5f9;
            border-bottom: 2px solid #f1f5f9;
            margin-bottom: 12px;
        }

        .task-card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
        }

        .task-card-date {
            color: #64748b;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .task-card-progress {
            font-weight: 900;
            color: #7AB2B2;
        }

        /* Kanban View */
        .kanban-board {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        .kanban-column {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .kanban-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 3px solid;
        }

        .kanban-column.pending .kanban-header { border-color: #64748b; }
        .kanban-column.progress .kanban-header { border-color: #3b82f6; }
        .kanban-column.stuck .kanban-header { border-color: #ef4444; }
        .kanban-column.done .kanban-header { border-color: #10b981; }

        .kanban-title {
            font-size: 16px;
            font-weight: 900;
            color: #1e293b;
        }

        .kanban-tasks {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* Pagination */
        .pagination {
            background: white;
            padding: 25px 30px;
            border-radius: 16px;
            margin-top: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .pagination-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .pagination-info {
            font-size: 14px;
            color: #64748b;
            font-weight: 600;
        }

        .pagination-info strong {
            color: #7AB2B2;
            font-weight: 900;
        }

        .pagination-controls {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .page-btn {
            padding: 10px 16px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            text-decoration: none;
            display: inline-block;
        }

        .page-btn:hover:not(.disabled) {
            border-color: #7AB2B2;
            color: #7AB2B2;
        }

        .page-btn.active {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            border-color: #7AB2B2;
            color: white;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        .page-btn.disabled {
            opacity: 0.4;
            cursor: not-allowed;
        }

        .per-page-select {
            padding: 10px 16px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            margin-left: 15px;
        }

        /* Alert Styles */
        .alert {
            position: fixed;
            top: 30px;
            right: 30px;
            background: white;
            padding: 20px 25px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            z-index: 1000;
            max-width: 420px;
            animation: slideIn 0.3s ease;
            border-left: 5px solid;
        }

        @keyframes slideIn {
            from {
                transform: translateX(500px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .alert.success {
            border-color: #10b981;
        }

        .alert.error {
            border-color: #ef4444;
        }

        .alert-header {
            display: flex;
            align-items: start;
            gap: 15px;
        }

        .alert-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .alert.success .alert-icon {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #065f46;
        }

        .alert.error .alert-icon {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
        }

        .alert-content {
            flex: 1;
        }

        .alert-title {
            font-weight: 900;
            margin-bottom: 5px;
            font-size: 16px;
        }

        .alert.success .alert-title {
            color: #065f46;
        }

        .alert.error .alert-title {
            color: #991b1b;
        }

        .alert-message {
            font-size: 13px;
            color: #64748b;
            font-weight: 500;
        }

        .alert-close {
            background: none;
            border: none;
            font-size: 20px;
            color: #94a3b8;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .alert-close:hover {
            background: #f1f5f9;
            color: #64748b;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }

        .empty-icon {
            width: 100px;
            height: 100px;
            margin: 0 auto 20px;
            background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .empty-icon i {
            font-size: 48px;
            color: #cbd5e1;
        }

        .empty-state h3 {
            font-size: 20px;
            font-weight: 900;
            color: #1e293b;
            margin-bottom: 10px;
        }

        .empty-state p {
            font-size: 14px;
            color: #64748b;
            font-weight: 500;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .header {
                padding: 20px 25px;
                top: 15px;
            }

            .header-content {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
                flex-direction: column;
            }

            .search-box input {
                width: 100%;
            }

            .search-box input:focus {
                width: 100%;
            }

            .date-filter {
                width: 100%;
                flex-direction: column;
            }

            .date-input, .dept-select {
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .table-container {
                overflow-x: auto;
            }

            table {
                min-width: 900px;
            }

            .task-grid {
                grid-template-columns: 1fr;
            }

            .kanban-board {
                grid-template-columns: 1fr;
            }
        }

        /* Hide views by default */
        .view-content {
            display: none;
        }

        .view-content.active {
            display: block;
        }
    </style>
</head>
<body>

    <?php if (isset($_SESSION['success_message'])): ?>
    <div id="successAlert" class="alert success">
        <div class="alert-header">
            <div class="alert-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="alert-content">
                <div class="alert-title">Berhasil!</div>
                <div class="alert-message"><?= htmlspecialchars($_SESSION['success_message']) ?></div>
            </div>
            <button class="alert-close" onclick="this.parentElement.remove()">×</button>
        </div>
    </div>
    <?php unset($_SESSION['success_message']); endif; ?>

    <?php if (isset($_SESSION['error_message'])): ?>
    <div id="errorAlert" class="alert error">
        <div class="alert-header">
            <div class="alert-icon">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="alert-content">
                <div class="alert-title">Error!</div>
                <div class="alert-message"><?= htmlspecialchars($_SESSION['error_message']) ?></div>
            </div>
            <button class="alert-close" onclick="this.parentElement.remove()">×</button>
        </div>
    </div>
    <?php unset($_SESSION['error_message']); endif; ?>

    <div class="container">
        <div class="header">
            <div class="header-content">
                <div class="header-left">
                    <div class="header-icon">
                        <i class="fas fa-tasks"></i>
                    </div>
                    <div class="header-title">
                        <h1><?= $pageTitle ?></h1>
                        <p><i class="fas fa-calendar"></i> <?= date('l, d F Y') ?></p>
                    </div>
                </div>
                <div class="header-actions">
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" id="searchInput" placeholder="Cari tugas, department, assignee...">
                    </div>
                    <div class="date-filter">
                        <input type="date" id="dateFrom" class="date-input" value="<?= htmlspecialchars($dateFrom ?? '') ?>">
                        <input type="date" id="dateTo" class="date-input" value="<?= htmlspecialchars($dateTo ?? '') ?>">
                        <?php if (!empty($allDepartments)): ?>
                        <select id="deptFilter" class="dept-select" onchange="applyFilters()">
                            <option value="">Semua Department</option>
                            <?php foreach ($allDepartments as $dept): ?>
                                <option value="<?= htmlspecialchars($dept) ?>" <?= $filterDepartment === $dept ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($dept) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php endif; ?>
                    </div>
                    <?php if ($permSummary['can_create']): ?>
                    <button onclick="goToAdd()" class="btn-primary">
                        <i class="fas fa-plus"></i>
                        Tambah Tugas
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card total" onclick="toggleStatDetail('total')">
                <div class="stat-header">
                    <div class="stat-icon">
                        <i class="fas fa-list-check"></i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value"><?= $stats['total'] ?? 0 ?></div>
                        <div class="stat-label">Total Tugas</div>
                    </div>
                </div>
                <div class="stat-footer">
                    <span><i class="fas fa-building"></i> <?= count($tasksByDept) ?> Departments</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <div id="detail-total" class="stat-detail">
                    <div class="dept-breakdown">
                        <?php foreach ($tasksByDept as $dept => $deptTasks): ?>
                            <div class="dept-item">
                                <span class="dept-name">
                                    <i class="fas fa-circle" style="font-size: 6px;"></i>
                                    <?= htmlspecialchars($dept) ?>
                                </span>
                                <span class="dept-count" style="--color-rgb: 59, 130, 246;"><?= count($deptTasks) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="stat-card done" onclick="toggleStatDetail('done')">
                <div class="stat-header">
                    <div class="stat-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value"><?= $stats['completed'] ?? 0 ?></div>
                        <div class="stat-label">Selesai</div>
                    </div>
                </div>
                <div class="stat-footer">
                    <span>Lihat per Department</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <div id="detail-done" class="stat-detail">
                    <div class="dept-breakdown">
                        <?php 
                        $hasCompleted = false;
                        foreach ($tasksByDept as $dept => $deptTasks): 
                            $completedCount = count(array_filter($deptTasks, fn($t) => strtolower($t['status']) === 'done'));
                            if ($completedCount > 0):
                                $hasCompleted = true;
                        ?>
                            <div class="dept-item">
                                <span class="dept-name">
                                    <i class="fas fa-circle" style="font-size: 6px;"></i>
                                    <?= htmlspecialchars($dept) ?>
                                </span>
                                <span class="dept-count" style="--color-rgb: 16, 185, 129;"><?= $completedCount ?></span>
                            </div>
                        <?php 
                            endif;
                        endforeach; 
                        if (!$hasCompleted):
                        ?>
                            <div style="text-align: center; padding: 15px; color: #64748b; font-size: 12px;">
                                <i class="fas fa-inbox"></i> Belum ada tugas selesai
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="stat-card progress" onclick="toggleStatDetail('progress')">
                <div class="stat-header">
                    <div class="stat-icon">
                        <i class="fas fa-spinner"></i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value"><?= $stats['in_progress'] ?? 0 ?></div>
                        <div class="stat-label">Progress</div>
                    </div>
                </div>
                <div class="stat-footer">
                    <span>Lihat per Department</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <div id="detail-progress" class="stat-detail">
                    <div class="dept-breakdown">
                        <?php 
                        $hasProgress = false;
                        foreach ($tasksByDept as $dept => $deptTasks): 
                            $progressCount = count(array_filter($deptTasks, fn($t) => strtolower($t['status']) === 'progress'));
                            if ($progressCount > 0):
                                $hasProgress = true;
                        ?>
                            <div class="dept-item">
                                <span class="dept-name">
                                    <i class="fas fa-circle" style="font-size: 6px;"></i>
                                    <?= htmlspecialchars($dept) ?>
                                </span>
                                <span class="dept-count" style="--color-rgb: 245, 158, 11;"><?= $progressCount ?></span>
                            </div>
                        <?php 
                            endif;
                        endforeach; 
                        if (!$hasProgress):
                        ?>
                            <div style="text-align: center; padding: 15px; color: #64748b; font-size: 12px;">
                                <i class="fas fa-inbox"></i> Tidak ada tugas dalam progress
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="stat-card stuck" onclick="toggleStatDetail('stuck')">
                <div class="stat-header">
                    <div class="stat-icon">
                        <i class="fas fa-triangle-exclamation"></i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value"><?= $stats['stuck'] ?? 0 ?></div>
                        <div class="stat-label">Terhambat</div>
                    </div>
                </div>
                <div class="stat-footer">
                    <span>Lihat per Department</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <div id="detail-stuck" class="stat-detail">
                    <div class="dept-breakdown">
                        <?php 
                        $hasStuck = false;
                        foreach ($tasksByDept as $dept => $deptTasks): 
                            $stuckCount = count(array_filter($deptTasks, fn($t) => strtolower($t['status']) === 'stuck'));
                            if ($stuckCount > 0):
                                $hasStuck = true;
                        ?>
                            <div class="dept-item">
                                <span class="dept-name">
                                    <i class="fas fa-circle" style="font-size: 6px;"></i>
                                    <?= htmlspecialchars($dept) ?>
                                </span>
                                <span class="dept-count" style="--color-rgb: 239, 68, 68;"><?= $stuckCount ?></span>
                            </div>
                        <?php 
                            endif;
                        endforeach; 
                        if (!$hasStuck):
                        ?>
                            <div style="text-align: center; padding: 15px; background: #d1fae5; border-radius: 8px; color: #065f46; font-size: 12px; font-weight: 600;">
                                <i class="fas fa-check-circle"></i> Tidak ada tugas terhambat
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php if (count($tasksByDept) > 1): ?>
        <div class="dept-nav">
            <h3><i class="fas fa-building"></i> Quick Jump ke Department:</h3>
            <div class="dept-nav-links">
                <?php foreach ($tasksByDept as $dept => $tasks): ?>
                    <a href="#dept-<?= htmlspecialchars(str_replace(' ', '-', $dept)) ?>" class="dept-nav-link">
                        <i class="fas fa-building"></i>
                        <?= htmlspecialchars($dept) ?>
                        <span class="dept-nav-count"><?= count($tasks) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="view-controls">
            <div class="view-tabs">
                <span style="font-size: 14px; font-weight: 800; color: #1e293b; margin-right: 10px;">
                    <i class="fas fa-eye"></i> Tampilan:
                </span>
                <button class="view-tab active" onclick="switchView('list')" id="listViewBtn">
                    <i class="fas fa-list"></i>
                    List
                </button>
                <button class="view-tab" onclick="switchView('department')" id="deptViewBtn">
                    <i class="fas fa-building"></i>
                    Department
                </button>
                <button class="view-tab" onclick="switchView('kanban')" id="kanbanViewBtn">
                    <i class="fas fa-columns"></i>
                    Kanban
                </button>
            </div>
        </div>

        <!-- List View -->
        <div id="listView" class="view-content active">
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Tugas</th>
                            <th>Department</th>
                            <th>Tenggat</th>
                            <th>Progress</th>
                            <th>Status</th>
                            <th>Ditugaskan</th>
                            <th style="text-align: center;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($paginatedTasks)): ?>
                            <tr>
                                <td colspan="8">
                                    <div class="empty-state">
                                        <div class="empty-icon">
                                            <i class="fas fa-inbox"></i>
                                        </div>
                                        <h3>Belum Ada Tugas</h3>
                                        <p>Mulai tambahkan tugas untuk tim Anda</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($paginatedTasks as $index => $task): ?>
                                <tr>
                                    <td><strong><?= $offset + $index + 1 ?></strong></td>
                                    <td>
                                        <div class="task-title"><?= htmlspecialchars(substr($task['judul_tugas'] ?? 'N/A', 0, 60)) ?></div>
                                        <?php if (!empty($task['deskripsi'])): ?>
                                            <div class="task-desc"><?= htmlspecialchars(substr($task['deskripsi'], 0, 80)) . (strlen($task['deskripsi']) > 80 ? '...' : '') ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="dept-badge">
                                            <i class="fas fa-building"></i>
                                            <?= htmlspecialchars($task['department'] ?? 'N/A') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <strong style="color: #7AB2B2;">
                                            <i class="fas fa-calendar"></i>
                                            <?= date('d M Y', strtotime($task['tenggat_waktu'])) ?>
                                        </strong>
                                    </td>
                                    <td>
                                        <div class="progress-container">
                                            <div class="progress-bar">
                                                <div class="progress-fill" style="width: <?= $task['progress'] ?? 0 ?>%"></div>
                                            </div>
                                            <span class="progress-text"><?= $task['progress'] ?? 0 ?>%</span>
                                        </div>
                                    </td>
                                    <td>
                                        <?php
                                        $statusConfig = [
                                            'done' => ['class' => 'done', 'icon' => 'check-circle', 'text' => 'Selesai'],
                                            'progress' => ['class' => 'progress', 'icon' => 'spinner', 'text' => 'Progress'],
                                            'stuck' => ['class' => 'stuck', 'icon' => 'triangle-exclamation', 'text' => 'Terhambat'],
                                            'pending' => ['class' => 'pending', 'icon' => 'clock', 'text' => 'Pending']
                                        ];
                                        $status = $statusConfig[$task['status']] ?? $statusConfig['pending'];
                                        ?>
                                        <span class="status-badge <?= $status['class'] ?>">
                                            <i class="fas fa-<?= $status['icon'] ?>"></i>
                                            <?= $status['text'] ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="assignee">
                                            <div class="assignee-avatar">
                                                <?= strtoupper(substr($task['assignee_name'], 0, 1)) ?>
                                            </div>
                                            <span class="assignee-name"><?= htmlspecialchars(substr($task['assignee_name'], 0, 25)) ?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="actions">
                                            <button onclick="viewTask(<?= $task['id'] ?>)" class="action-btn view">
                                                <i class="fas fa-eye"></i> Lihat
                                            </button>
                                            <?php if ($permSummary['can_edit']): ?>
                                            <button onclick="editTask(<?= $task['id'] ?>)" class="action-btn edit">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <?php endif; ?>
                                            <?php if ($permSummary['can_delete']): ?>
                                            <button onclick="deleteTask(<?= $task['id'] ?>)" class="action-btn delete">
                                                <i class="fas fa-trash"></i> Hapus
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <div class="pagination-wrapper">
                    <div class="pagination-info">
                        Menampilkan <strong><?= $offset + 1 ?></strong> sampai 
                        <strong><?= min($offset + $itemsPerPage, $totalItems) ?></strong> dari 
                        <strong><?= $totalItems ?></strong> hasil
                    </div>
                    <div class="pagination-controls">
                        <?php if ($currentPage > 1): ?>
                            <a href="?page=<?= $currentPage - 1 ?>&per_page=<?= $itemsPerPage ?><?= $dateFrom ? '&date_from='.$dateFrom : '' ?><?= $dateTo ? '&date_to='.$dateTo : '' ?><?= $filterDepartment ? '&department='.$filterDepartment : '' ?>" 
                               class="page-btn">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        <?php else: ?>
                            <span class="page-btn disabled">
                                <i class="fas fa-chevron-left"></i>
                            </span>
                        <?php endif; ?>

                        <?php
                        $startPage = max(1, $currentPage - 2);
                        $endPage = min($totalPages, $currentPage + 2);
                        for ($i = $startPage; $i <= $endPage; $i++):
                        ?>
                            <a href="?page=<?= $i ?>&per_page=<?= $itemsPerPage ?><?= $dateFrom ? '&date_from='.$dateFrom : '' ?><?= $dateTo ? '&date_to='.$dateTo : '' ?><?= $filterDepartment ? '&department='.$filterDepartment : '' ?>" 
                               class="page-btn <?= $i === $currentPage ? 'active' : '' ?>">
                                <?= $i ?>
                            </a>
                        <?php endfor; ?>

                        <?php if ($currentPage < $totalPages): ?>
                            <a href="?page=<?= $currentPage + 1 ?>&per_page=<?= $itemsPerPage ?><?= $dateFrom ? '&date_from='.$dateFrom : '' ?><?= $dateTo ? '&date_to='.$dateTo : '' ?><?= $filterDepartment ? '&department='.$filterDepartment : '' ?>" 
                               class="page-btn">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        <?php else: ?>
                            <span class="page-btn disabled">
                                <i class="fas fa-chevron-right"></i>
                            </span>
                        <?php endif; ?>

                        <select onchange="changePerPage(this.value)" class="per-page-select">
                            <option value="10" <?= $itemsPerPage === 10 ? 'selected' : '' ?>>10 / halaman</option>
                            <option value="25" <?= $itemsPerPage === 25 ? 'selected' : '' ?>>25 / halaman</option>
                            <option value="50" <?= $itemsPerPage === 50 ? 'selected' : '' ?>>50 / halaman</option>
                            <option value="100" <?= $itemsPerPage === 100 ? 'selected' : '' ?>>100 / halaman</option>
                        </select>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Department View -->
        <div id="departmentView" class="view-content">
            <?php foreach ($tasksByDept as $dept => $deptTasks): ?>
                <div id="dept-<?= htmlspecialchars(str_replace(' ', '-', $dept)) ?>" class="dept-section">
                    <div class="dept-header">
                        <h2>
                            <i class="fas fa-building"></i>
                            <?= htmlspecialchars($dept) ?>
                            <span class="dept-count-badge"><?= count($deptTasks) ?> Tugas</span>
                        </h2>
                    </div>
                    <div class="dept-tasks">
                        <div class="task-grid">
                            <?php foreach ($deptTasks as $task): ?>
                                <div class="task-card" onclick="viewTask(<?= $task['id'] ?>)">
                                    <div class="task-card-header">
                                        <div class="task-card-title"><?= htmlspecialchars($task['judul_tugas'] ?? 'N/A') ?></div>
                                        <?php
                                        $statusColors = [
                                            'done' => 'background: linear-gradient(135deg, #10b981, #059669);',
                                            'progress' => 'background: linear-gradient(135deg, #3b82f6, #2563eb);',
                                            'stuck' => 'background: linear-gradient(135deg, #ef4444, #dc2626);',
                                            'pending' => 'background: linear-gradient(135deg, #64748b, #475569);'
                                        ];
                                        $statusIcons = [
                                            'done' => 'check-circle',
                                            'progress' => 'spinner',
                                            'stuck' => 'triangle-exclamation',
                                            'pending' => 'clock'
                                        ];
                                        $statusKey = $task['status'] ?? 'pending';
                                        ?>
                                        <div class="task-card-status" style="<?= $statusColors[$statusKey] ?? $statusColors['pending'] ?>">
                                            <i class="fas fa-<?= $statusIcons[$statusKey] ?? $statusIcons['pending'] ?> " style="color: white; font-size: 16px;"></i>
                                        </div>
                                    </div>
                                    <div class="task-card-assignee">
                                        <div class="assignee-avatar" style="width: 32px; height: 32px; font-size: 14px;">
                                            <?= strtoupper(substr($task['assignee_name'] ?? '', 0, 1)) ?: '?' ?>
                                        </div>
                                        <span style="font-size: 13px; font-weight: 600; color: #1e293b;">
                                            <?= htmlspecialchars($task['assignee_name'] ?? 'N/A') ?>
                                        </span>
                                    </div>
                                    <div class="task-card-footer">
                                        <span class="task-card-date">
                                            <i class="fas fa-calendar"></i>
                                            <?= date('d M Y', strtotime($task['tenggat_waktu'])) ?>
                                        </span>
                                        <span class="task-card-progress"><?= $task['progress'] ?? 0 ?>%</span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Kanban View -->
        <div id="kanbanView" class="view-content">
            <div class="kanban-board">
                <div class="kanban-column pending">
                    <div class="kanban-header">
                        <i class="fas fa-clock" style="color: #64748b;"></i>
                        <span class="kanban-title">Pending</span>
                    </div>
                    <div class="kanban-tasks" id="pendingTasks"></div>
                </div>
                <div class="kanban-column progress">
                    <div class="kanban-header">
                        <i class="fas fa-spinner" style="color: #3b82f6;"></i>
                        <span class="kanban-title">Progress</span>
                    </div>
                    <div class="kanban-tasks" id="progressTasks"></div>
                </div>
                <div class="kanban-column stuck">
                    <div class="kanban-header">
                        <i class="fas fa-triangle-exclamation" style="color: #ef4444;"></i>
                        <span class="kanban-title">Terhambat</span>
                    </div>
                    <div class="kanban-tasks" id="stuckTasks"></div>
                </div>
                <div class="kanban-column done">
                    <div class="kanban-header">
                        <i class="fas fa-check-circle" style="color: #10b981;"></i>
                        <span class="kanban-title">Selesai</span>
                    </div>
                    <div class="kanban-tasks" id="completedTasks"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const tasks = <?= json_encode($allTasks) ?>;

        // Auto hide alerts
        setTimeout(() => {
            document.getElementById('successAlert')?.remove();
            document.getElementById('errorAlert')?.remove();
        }, 5000);

        function goToAdd() {
            if (parent && parent.document.getElementById('contentFrame')) {
                parent.document.getElementById('contentFrame').src = '<?= $addTaskUrl ?>';
            } else {
                window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('<?= $addTaskUrl ?>');
            }
        }

        function toggleStatDetail(type) {
            const detail = document.getElementById(`detail-${type}`);
            const allDetails = document.querySelectorAll('.stat-detail');
            
            allDetails.forEach(d => {
                if (d.id !== `detail-${type}`) {
                    d.classList.remove('show');
                }
            });
            
            detail.classList.toggle('show');
        }

        function switchView(view) {
            document.querySelectorAll('.view-content').forEach(v => v.classList.remove('active'));
            document.querySelectorAll('.view-tab').forEach(t => t.classList.remove('active'));
            
            if (view === 'list') {
                document.getElementById('listView').classList.add('active');
                document.getElementById('listViewBtn').classList.add('active');
            } else if (view === 'department') {
                document.getElementById('departmentView').classList.add('active');
                document.getElementById('deptViewBtn').classList.add('active');
            } else if (view === 'kanban') {
                document.getElementById('kanbanView').classList.add('active');
                document.getElementById('kanbanViewBtn').classList.add('active');
                renderKanban();
            }
        }

        function renderKanban() {
            const columns = {
                pending: document.getElementById('pendingTasks'),
                progress: document.getElementById('progressTasks'),
                stuck: document.getElementById('stuckTasks'),
                done: document.getElementById('completedTasks')
            };

            Object.values(columns).forEach(col => col.innerHTML = '');

            tasks.forEach(task => {
                const status = (task.status || 'pending').toLowerCase();
                const column = columns[status] || columns.pending;
                
                if (column) {
                    const card = document.createElement('div');
                    card.className = 'task-card';
                    card.onclick = () => viewTask(task.id);
                    card.innerHTML = `
                        <div class="task-card-header">
                            <div class="task-card-title">${task.judul_tugas || 'N/A'}</div>
                        </div>
                        <div class="task-card-assignee">
                            <div class="assignee-avatar" style="width: 32px; height: 32px; font-size: 14px;">
                                ${task.assignee_name ? task.assignee_name.charAt(0).toUpperCase() : '?'}
                            </div>
                            <span style="font-size: 13px; font-weight: 600; color: #1e293b;">
                                ${task.assignee_name || 'N/A'}
                            </span>
                        </div>
                        <div style="padding: 10px 0; border-top: 2px solid #f1f5f9; margin-top: 10px;">
                            <span class="dept-badge">
                                <i class="fas fa-building"></i>
                                ${task.department || 'N/A'}
                            </span>
                        </div>
                        <div class="task-card-footer">
                            <span class="task-card-date">
                                <i class="fas fa-calendar"></i>
                                ${new Date(task.tenggat_waktu).toLocaleDateString('id-ID', {day: 'numeric', month: 'short', year: 'numeric'})}
                            </span>
                            <span class="task-card-progress">${task.progress || 0}%</span>
                        </div>
                    `;
                    column.appendChild(card);
                }
            });
        }

        document.getElementById('searchInput')?.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('#listView tbody tr');
            rows.forEach(row => {
                row.style.display = row.textContent.toLowerCase().includes(searchTerm) ? '' : 'none';
            });
        });

        document.getElementById('dateFrom')?.addEventListener('change', applyFilters);
        document.getElementById('dateTo')?.addEventListener('change', applyFilters);

        function applyFilters() {
            const dateFrom = document.getElementById('dateFrom').value;
            const dateTo = document.getElementById('dateTo').value;
            const dept = document.getElementById('deptFilter')?.value || '';
            const url = new URL(window.location.href);
            
            if (dateFrom) url.searchParams.set('date_from', dateFrom);
            else url.searchParams.delete('date_from');
            
            if (dateTo) url.searchParams.set('date_to', dateTo);
            else url.searchParams.delete('date_to');
            
            if (dept) url.searchParams.set('department', dept);
            else url.searchParams.delete('department');
            
            window.location.href = url.toString();
        }

        function changePerPage(perPage) {
            const url = new URL(window.location.href);
            url.searchParams.set('per_page', perPage);
            url.searchParams.set('page', '1');
            window.location.href = url.toString();
        }

        function viewTask(id) {
            if (parent && parent.document.getElementById('contentFrame')) {
                parent.document.getElementById('contentFrame').src = 'pages/rencana_kerja/detail_rencana_kerja.php?id=' + id;
            } else {
                window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('pages/rencana_kerja/detail_rencana_kerja.php?id=' + id);
            }
        }

        function editTask(id) {
            if (parent && parent.document.getElementById('contentFrame')) {
                parent.document.getElementById('contentFrame').src = 'pages/rencana_kerja/edit_rencana_kerja.php?id=' + id;
            } else {
                window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('pages/rencana_kerja/edit_rencana_kerja.php?id=' + id);
            }
        }

        function deleteTask(id) {
            if (confirm('⚠️ Apakah Anda yakin ingin menghapus tugas ini?\n\nTindakan ini tidak dapat dibatalkan!')) {
                if (parent && parent.document.getElementById('contentFrame')) {
                    parent.document.getElementById('contentFrame').src = 'pages/rencana_kerja/delete_rencana_kerja.php?id=' + id;
                } else {
                    window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent('pages/rencana_kerja/delete_rencana_kerja.php?id=' + id);
                }
            }
        }
    </script>

</body>
</html>