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

// ✅ DEBUGGING - Hapus setelah berhasil
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$userRole = isset($_SESSION['role']) ? strtolower(trim($_SESSION['role'])) : '';

if ($userRole !== 'admin') {
    header("Location: ../../dashboard.php");
    exit;
}

$userId = (int) $_SESSION['user_id'];

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

// ✅ DEBUGGING - Cek apakah ada data
$testQuery = "SELECT COUNT(*) as total FROM rencana_kerja WHERE is_deleted = 0";
$testResult = $conn->query($testQuery);
$testData = $testResult->fetch_assoc();

// 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 = '';

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

if ($filterDepartment) {
    $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';
        
        // Normalize department
        if (empty($task['department']) || $task['department'] === 'N/A') {
            $task['department'] = 'Tidak Ada Department';
        }
        
        $allTasks[] = $task;
    }
}

$stmt->close();

// Statistics query
$statsSql = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN rk.status = 'done' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN rk.status = 'progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN rk.status = 'stuck' THEN 1 ELSE 0 END) as stuck,
        SUM(CASE WHEN rk.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();
}

// Statistics by Department
$statsByDeptSql = "
    SELECT 
        assignee.department as department,
        COUNT(*) as total,
        SUM(CASE WHEN rk.status = 'done' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN rk.status = 'progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN rk.status = 'stuck' THEN 1 ELSE 0 END) as stuck,
        SUM(CASE WHEN rk.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
    GROUP BY assignee.department
    ORDER BY assignee.department
";

$statsByDeptStmt = $conn->prepare($statsByDeptSql);

$tasksByDepartment = [];
if ($statsByDeptStmt) {
    if (!empty($params)) {
        $statsByDeptStmt->bind_param($types, ...$params);
    }
    
    $statsByDeptStmt->execute();
    $statsByDeptResult = $statsByDeptStmt->get_result();
    
    while ($row = $statsByDeptResult->fetch_assoc()) {
        $dept = $row['department'] ?? 'Tidak Ada Department';
        $tasksByDepartment[$dept] = [
            'total' => $row['total'],
            'done' => $row['completed'],
            'progress' => $row['in_progress'],
            'stuck' => $row['stuck'],
            'pending' => $row['pending']
        ];
    }
    $statsByDeptStmt->close();
}

ksort($tasksByDepartment);

// ✅ Assign unique colors to each department
$departmentColors = [];
$colorPalette = [
    ['bg' => '#E3F2FD', 'border' => '#2196F3', 'text' => '#1976D2'], // Blue
    ['bg' => '#F3E5F5', 'border' => '#9C27B0', 'text' => '#7B1FA2'], // Purple
    ['bg' => '#E8F5E9', 'border' => '#4CAF50', 'text' => '#388E3C'], // Green
    ['bg' => '#FFF3E0', 'border' => '#FF9800', 'text' => '#F57C00'], // Orange
    ['bg' => '#FCE4EC', 'border' => '#E91E63', 'text' => '#C2185B'], // Pink
    ['bg' => '#E0F2F1', 'border' => '#009688', 'text' => '#00796B'], // Teal
    ['bg' => '#FFF9C4', 'border' => '#FDD835', 'text' => '#F9A825'], // Yellow
    ['bg' => '#FFEBEE', 'border' => '#F44336', 'text' => '#D32F2F'], // Red
];

// Get all unique departments from both stats and tasks
$allDepartmentsForColors = array_unique(array_merge(
    array_keys($tasksByDepartment),
    array_column($allTasks, 'department')
));

$colorIndex = 0;
foreach ($allDepartmentsForColors as $dept) {
    if (!empty($dept)) {
        $departmentColors[$dept] = $colorPalette[$colorIndex % count($colorPalette)];
        $colorIndex++;
    }
}

// Default fallback color for undefined departments
$defaultColor = ['bg' => '#F1F5F9', 'border' => '#CBD5E1', 'text' => '#475569'];

// Get all departments for filter dropdown
$deptSql = "SELECT DISTINCT department FROM users WHERE department IS NOT NULL AND department != '' ORDER BY department";
$deptResult = $conn->query($deptSql);
$allDepartments = [];
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
$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);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rencana Kerja - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            padding: 25px;
            color: #1e293b;
        }

        .header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 30px 40px;
            border-radius: 20px;
            margin-bottom: 25px;
            box-shadow: 0 8px 25px rgba(122, 178, 178, 0.25);
        }

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

        .header-left h1 {
            font-size: 28px;
            font-weight: 800;
            margin-bottom: 5px;
        }

        .header-left p {
            font-size: 15px;
            opacity: 0.95;
        }

        .header-right {
            margin-left: auto;
        }

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

        .btn-add-task:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(255,255,255,0.4);
            background: #ffffff;
        }

        .btn-add-task i {
            font-size: 16px;
        }

        .filter-section {
            display: flex;
            gap: 12px;
            align-items: stretch;
            padding-top: 20px;
            border-top: 2px solid rgba(255,255,255,0.2);
        }

        .search-box {
            position: relative;
            flex: 1;
        }

        .search-box input {
            width: 100%;
            height: 100%;
            padding: 10px 15px 10px 40px;
            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;
        }

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

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

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

        .date-input {
            padding: 10px 15px;
            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;
            min-width: 160px;
        }

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

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

        /* ============================================================
           MODERN CUSTOM DROPDOWN STYLES - FIXED
           ============================================================ */
        .custom-dropdown {
            position: relative;
            min-width: 200px;
        }

        .dropdown-trigger {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            height: 100%;
            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;
            cursor: pointer;
            transition: all 0.3s ease;
            user-select: none;
            gap: 10px;
        }

        .dropdown-trigger:hover {
            background: rgba(255,255,255,0.25);
            border-color: rgba(255,255,255,0.5);
        }

        .dropdown-trigger.active {
            background: rgba(255,255,255,0.25);
            border-color: white;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .dropdown-trigger #selectedDept {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-weight: 600;
        }

        .dropdown-icon {
            font-size: 10px;
            transition: transform 0.3s ease;
            display: inline-block;
            flex-shrink: 0;
        }

        .dropdown-trigger.active .dropdown-icon {
            transform: rotate(180deg);
        }

        .dropdown-options {
            position: absolute;
            top: calc(100% + 8px);
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            z-index: 1000;
            max-height: 0;
            overflow: hidden;
        }

        .dropdown-options.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
            max-height: 450px;
        }

        .dropdown-search {
            padding: 12px;
            border-bottom: 2px solid #f1f5f9;
            position: sticky;
            top: 0;
            background: white;
            z-index: 10;
            border-radius: 12px 12px 0 0;
        }

        .dropdown-search-wrapper {
            position: relative;
        }

        .dropdown-search-wrapper i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            font-size: 14px;
        }

        .dropdown-search input {
            width: 100%;
            padding: 10px 15px 10px 38px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 13px;
            transition: all 0.2s ease;
            background: #f8fafc;
            color: #1e293b;
            font-weight: 500;
        }

        .dropdown-search input::placeholder {
            color: #94a3b8;
        }

        .dropdown-search input:focus {
            outline: none;
            border-color: #7AB2B2;
            background: white;
        }

        .dropdown-options-inner {
            max-height: 320px;
            overflow-y: auto;
            padding: 8px;
        }

        /* Custom Scrollbar */
        .dropdown-options-inner::-webkit-scrollbar {
            width: 6px;
        }

        .dropdown-options-inner::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
            margin: 4px 0;
        }

        .dropdown-options-inner::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 10px;
        }

        .dropdown-options-inner::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        .dropdown-option {
            padding: 12px 16px;
            color: #334155;
            font-size: 14px;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 10px;
            position: relative;
        }

        .dropdown-option:hover {
            background: #f8fafc;
            color: #7AB2B2;
            padding-left: 20px;
        }

        .dropdown-option.selected {
            background: linear-gradient(135deg, rgba(122, 178, 178, 0.15), rgba(77, 134, 156, 0.15));
            color: #7AB2B2;
            font-weight: 700;
            border-left: 3px solid #7AB2B2;
        }

        .dropdown-option.selected::after {
            content: '✓';
            position: absolute;
            right: 16px;
            font-weight: 700;
            color: #7AB2B2;
            font-size: 16px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            padding: 20px 18px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--color);
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.08);
        }

        .stat-card.total::before { background: #3b82f6; }
        .stat-card.done::before { background: #10b981; }
        .stat-card.progress::before { background: #f59e0b; }
        .stat-card.stuck::before { background: #ef4444; }

        .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            font-size: 20px;
        }

        .stat-card.total .stat-icon {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
        }

        .stat-card.done .stat-icon {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }

        .stat-card.progress .stat-icon {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }

        .stat-card.stuck .stat-icon {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 4px;
            line-height: 1;
        }

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

        /* Department Stats Section */
        .dept-toggle {
            background: white;
            padding: 18px 25px;
            border-radius: 12px;
            margin-bottom: 25px;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            transition: all 0.3s ease;
        }

        .dept-toggle:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .dept-toggle-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .dept-toggle-title {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 15px;
            font-weight: 700;
            color: #1e293b;
        }

        .dept-toggle-title i {
            color: #7AB2B2;
            font-size: 18px;
        }

        .dept-count {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            color: white;
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 600;
        }

        .chevron {
            color: #94a3b8;
            transition: transform 0.3s ease;
            font-size: 16px;
        }

        .chevron.open {
            transform: rotate(180deg);
        }

        .dept-dropdown {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .dept-dropdown.show {
            max-height: 800px;
            margin-top: 18px;
        }

        .dept-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 15px;
        }

        /* ✅ Colored Department Cards */
        .dept-item {
            background: white;
            border-radius: 10px;
            padding: 18px;
            transition: all 0.3s ease;
            border-left: 4px solid;
        }

        .dept-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.1);
        }

        .dept-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

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

        .dept-total {
            color: white;
            padding: 4px 10px;
            border-radius: 10px;
            font-size: 11px;
            font-weight: 600;
        }

        .dept-stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;
            text-align: center;
        }

        .dept-stat-item {
            padding: 10px 6px;
            border-radius: 8px;
            background: #f8fafc;
        }

        .dept-stat-value {
            font-size: 18px;
            font-weight: 800;
            line-height: 1;
            margin-bottom: 4px;
        }

        .dept-stat-value.done { color: #10b981; }
        .dept-stat-value.progress { color: #f59e0b; }
        .dept-stat-value.stuck { color: #ef4444; }
        .dept-stat-value.pending { color: #64748b; }

        .dept-stat-label {
            font-size: 10px;
            color: #64748b;
            font-weight: 600;
        }

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

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

        thead {
            background: #f8fafc;
        }

        th {
            padding: 18px 20px;
            text-align: left;
            font-size: 12px;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
        }

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

        tbody tr:hover {
            background: #f8fafc;
        }

        /* ✅ Department Separator Row with Color */
        tr.dept-separator {
            background: white !important;
            border-top: 3px solid;
            border-bottom: 3px solid;
        }

        tr.dept-separator td {
            padding: 15px 20px;
            font-weight: 800;
            font-size: 14px;
            letter-spacing: 0.5px;
        }

        tr.dept-separator:hover {
            background: white !important;
        }

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

        .task-title {
            font-weight: 600;
            color: #1e293b;
        }

        .dept-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
        }

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

        .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: 700;
            color: #64748b;
            min-width: 40px;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-badge.done {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }

        .status-badge.progress {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }

        .status-badge.stuck {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .status-badge.pending {
            background: rgba(100, 116, 139, 0.1);
            color: #64748b;
        }

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

        .assignee-avatar {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 14px;
        }

        .assignee-name {
            font-weight: 600;
            color: #334155;
        }

        .actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }

        .dropdown-container {
            position: relative;
        }

        .action-btn.more {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            font-size: 16px;
            background: rgba(100, 116, 139, 0.1);
            color: #64748b;
        }

        .action-btn.more:hover {
            background: #64748b;
            color: white;
        }

        .dropdown-menu {
            position: absolute;
            right: 0;
            top: 100%;
            margin-top: 5px;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            min-width: 160px;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.2s ease;
        }

        .dropdown-menu.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            color: #334155;
            text-decoration: none;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.2s ease;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
            cursor: pointer;
        }

        .dropdown-item:first-child {
            border-radius: 8px 8px 0 0;
        }

        .dropdown-item:last-child {
            border-radius: 0 0 8px 8px;
        }

        .dropdown-item:hover {
            background: #f8fafc;
            color: #7AB2B2;
        }

        .dropdown-item.delete:hover {
            background: #fef2f2;
            color: #ef4444;
        }

        .dropdown-item i {
            font-size: 16px;
            width: 20px;
            text-align: center;
        }

        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 25px;
            background: #f8fafc;
            border-top: 2px solid #e2e8f0;
        }

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

        .pagination-info span {
            color: #1e293b;
            font-weight: 700;
        }

        .pagination-buttons {
            display: flex;
            gap: 8px;
        }

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

        .page-btn:hover {
            border-color: #7AB2B2;
            color: #7AB2B2;
        }

        .page-btn.active {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            border-color: #7AB2B2;
            color: white;
        }

        .alert {
            position: fixed;
            top: 25px;
            right: 25px;
            background: white;
            padding: 20px 25px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            z-index: 1000;
            max-width: 400px;
            animation: slideIn 0.3s ease;
        }

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

        .alert.success {
            border-left: 4px solid #10b981;
        }

        .alert.error {
            border-left: 4px solid #ef4444;
        }

        .alert-title {
            font-weight: 700;
            margin-bottom: 5px;
            font-size: 15px;
        }

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

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

        .alert-message {
            font-size: 14px;
            color: #64748b;
        }

        .alert-close {
            position: absolute;
            top: 15px;
            right: 15px;
            background: none;
            border: none;
            font-size: 20px;
            color: #94a3b8;
            cursor: pointer;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }

        .empty-state i {
            font-size: 64px;
            color: #cbd5e1;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            font-size: 20px;
            color: #475569;
            margin-bottom: 8px;
        }

        .empty-state p {
            font-size: 14px;
            color: #94a3b8;
        }

        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .header {
                padding: 20px 25px;
            }

            .header-content {
                flex-direction: row !important;
                justify-content: space-between;
                margin-bottom: 15px;
            }

            .header-left h1 {
                font-size: 20px;
            }

            .header-left p {
                font-size: 13px;
            }

            .btn-add-task {
                padding: 10px 20px;
                font-size: 14px;
            }

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

            .search-box {
                width: 100%;
            }

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

            .date-input, .custom-dropdown {
                width: 100%;
            }

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

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

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

            table {
                min-width: 800px;
            }
        }
    </style>
</head>
<body>
    <!-- DEBUG INFO -->
    <?php if ($testData): ?>
    <!-- Total tasks in DB: <?= $testData['total'] ?> -->
    <!-- Tasks displayed: <?= count($allTasks) ?> -->
    <!-- User Role: <?= $userRole ?> -->
    <?php endif; ?>

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

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

    <div class="header">
        <div class="header-content">
            <div class="header-left">
                <h1>Rencana Kerja</h1>
                <p>Kelola dan Monitor Semua Tugas Tim</p>
            </div>
            <div class="header-right">
                <button onclick="goToAdd()" class="btn-add-task">
                    <i class="fas fa-plus"></i>
                    Tambah Tugas
                </button>
            </div>
        </div>
        
        <!-- Filter Section -->
        <div class="filter-section">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Cari tugas...">
            </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 ?? '') ?>">
                
                <!-- ✅ MODERN CUSTOM DROPDOWN - FIXED -->
                <?php if (!empty($allDepartments)): ?>
                <div class="custom-dropdown" id="departmentDropdown">
                    <div class="dropdown-trigger" onclick="toggleDeptDropdown()">
                        <span id="selectedDept">
                            <?= !empty($filterDepartment) ? htmlspecialchars($filterDepartment) : 'Semua Department' ?>
                        </span>
                        <span class="dropdown-icon">▼</span>
                    </div>
                    <div class="dropdown-options">
                        <!-- Search Box -->
                        <div class="dropdown-search">
                            <div class="dropdown-search-wrapper">
                                <i class="fas fa-search"></i>
                                <input type="text" 
                                       id="deptSearchInput" 
                                       placeholder="Cari department..." 
                                       onclick="event.stopPropagation()"
                                       oninput="filterDepartments()">
                            </div>
                        </div>
                        
                        <div class="dropdown-options-inner" id="departmentList">
                            <div class="dropdown-option <?= empty($filterDepartment) ? 'selected' : '' ?>" 
                                 onclick="selectDepartment('', 'Semua Department')"
                                 data-dept="semua department">
                                <span>Semua Department</span>
                            </div>
                            <?php foreach ($allDepartments as $dept): ?>
                                <div class="dropdown-option <?= $filterDepartment === $dept ? 'selected' : '' ?>" 
                                     onclick="selectDepartment('<?= htmlspecialchars($dept) ?>', '<?= htmlspecialchars($dept) ?>')"
                                     data-dept="<?= strtolower(htmlspecialchars($dept)) ?>">
                                    <span><?= htmlspecialchars($dept) ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card total">
            <div class="stat-icon">
                <i class="fas fa-list-check"></i>
            </div>
            <div class="stat-value"><?= $stats['total'] ?? 0 ?></div>
            <div class="stat-label">Total Tugas</div>
        </div>

        <div class="stat-card done">
            <div class="stat-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-value"><?= $stats['completed'] ?? 0 ?></div>
            <div class="stat-label">Selesai</div>
        </div>

        <div class="stat-card progress">
            <div class="stat-icon">
                <i class="fas fa-spinner"></i>
            </div>
            <div class="stat-value"><?= $stats['in_progress'] ?? 0 ?></div>
            <div class="stat-label">Progress</div>
        </div>

        <div class="stat-card stuck">
            <div class="stat-icon">
                <i class="fas fa-triangle-exclamation"></i>
            </div>
            <div class="stat-value"><?= $stats['stuck'] ?? 0 ?></div>
            <div class="stat-label">Terhambat</div>
        </div>
    </div>

    <?php if (!empty($tasksByDepartment)): ?>
    <div class="dept-toggle" onclick="toggleDeptStats()">
        <div class="dept-toggle-header">
            <div class="dept-toggle-title">
                <i class="fas fa-building"></i>
                Statistik per Department
                <span class="dept-count"><?= count($tasksByDepartment) ?> Department</span>
            </div>
            <i class="fas fa-chevron-down chevron" id="deptChevron"></i>
        </div>
        <div class="dept-dropdown" id="deptDropdown">
            <div class="dept-grid">
                <?php foreach ($tasksByDepartment as $dept => $deptStats): 
                    $colors = $departmentColors[$dept] ?? $defaultColor;
                ?>
                <div class="dept-item" style="border-left-color: <?= $colors['border'] ?>; background: <?= $colors['bg'] ?>;">
                    <div class="dept-header">
                        <div class="dept-name" style="color: <?= $colors['text'] ?>;"><?= htmlspecialchars($dept) ?></div>
                        <div class="dept-total" style="background: <?= $colors['border'] ?>;"><?= $deptStats['total'] ?> tugas</div>
                    </div>
                    <div class="dept-stats">
                        <div class="dept-stat-item">
                            <div class="dept-stat-value done"><?= $deptStats['done'] ?></div>
                            <div class="dept-stat-label">Selesai</div>
                        </div>
                        <div class="dept-stat-item">
                            <div class="dept-stat-value progress"><?= $deptStats['progress'] ?></div>
                            <div class="dept-stat-label">Progress</div>
                        </div>
                        <div class="dept-stat-item">
                            <div class="dept-stat-value stuck"><?= $deptStats['stuck'] ?></div>
                            <div class="dept-stat-label">Hambat</div>
                        </div>
                        <div class="dept-stat-item">
                            <div class="dept-stat-value pending"><?= $deptStats['pending'] ?></div>
                            <div class="dept-stat-label">Pending</div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Tugas</th>
                    <th>Department</th>
                    <th>Tenggat</th>
                    <th>Progress</th>
                    <th>Status</th>
                    <th>Assignee</th>
                    <th style="text-align: center;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($paginatedTasks)): ?>
                    <tr>
                        <td colspan="7">
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <h3>Belum Ada Tugas</h3>
                                <p>Mulai tambahkan tugas untuk tim Anda</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php 
                    $currentDept = null;
                    foreach ($paginatedTasks as $task): 
                        if ($currentDept !== $task['department']):
                            $currentDept = $task['department'];
                            $colors = $departmentColors[$currentDept] ?? $defaultColor;
                    ?>
                        <tr class="dept-separator" style="border-color: <?= $colors['border'] ?>; background: <?= $colors['bg'] ?> !important;">
                            <td colspan="7" style="color: <?= $colors['text'] ?>;">
                                <i class="fas fa-building"></i>
                                <?= htmlspecialchars($currentDept) ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                        <tr>
                            <td>
                                <div class="task-title"><?= htmlspecialchars(substr($task['judul_tugas'] ?? 'N/A', 0, 60)) ?></div>
                            </td>
                            <td>
                                <?php 
                                $colors = $departmentColors[$task['department']] ?? $defaultColor;
                                ?>
                                <span class="dept-badge" style="background: <?= $colors['bg'] ?>; color: <?= $colors['text'] ?>;">
                                    <?= htmlspecialchars($task['department'] ?? 'N/A') ?>
                                </span>
                            </td>
                            <td><?= date('d M Y', strtotime($task['tenggat_waktu'])) ?></td>
                            <td>
                                <div class="progress-bar-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', 'text' => 'Selesai'],
                                    'progress' => ['class' => 'progress', 'text' => 'Progress'],
                                    'stuck' => ['class' => 'stuck', 'text' => 'Terhambat'],
                                    'pending' => ['class' => 'pending', 'text' => 'Pending']
                                ];
                                $status = $statusConfig[$task['status']] ?? $statusConfig['pending'];
                                ?>
                                <span class="status-badge <?= $status['class'] ?>"><?= $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, 20)) ?></span>
                                </div>
                            </td>
                            <td>
                                <div class="actions">
                                    <div class="dropdown-container">
                                        <button class="action-btn more" onclick="toggleDropdown(<?= $task['id'] ?>)">
                                            <i class="fas fa-ellipsis-vertical"></i>
                                        </button>
                                        <div class="dropdown-menu" id="dropdown-<?= $task['id'] ?>">
                                            <button onclick="viewTask(<?= $task['id'] ?>)" class="dropdown-item">
                                                <i class="fas fa-eye"></i>
                                                <span>Lihat Detail</span>
                                            </button>
                                            <button onclick="editTask(<?= $task['id'] ?>)" class="dropdown-item">
                                                <i class="fas fa-edit"></i>
                                                <span>Edit</span>
                                            </button>
                                            <button onclick="deleteTask(<?= $task['id'] ?>)" class="dropdown-item delete">
                                                <i class="fas fa-trash"></i>
                                                <span>Hapus</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <div class="pagination-info">
                Menampilkan <span><?= $offset + 1 ?>-<?= min($offset + $itemsPerPage, $totalItems) ?></span> dari <span><?= $totalItems ?></span> tugas
            </div>
            <div class="pagination-buttons">
                <?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> Previous
                    </a>
                <?php endif; ?>

                <?php
                $startPage = max(1, $currentPage - 1);
                $endPage = min($totalPages, $currentPage + 1);
                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">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

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

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

        function toggleDropdown(id) {
            const dropdown = document.getElementById(`dropdown-${id}`);
            const allDropdowns = document.querySelectorAll('.dropdown-menu');
            
            allDropdowns.forEach(d => {
                if (d !== dropdown) {
                    d.classList.remove('show');
                }
            });
            
            dropdown.classList.toggle('show');
        }

        document.addEventListener('click', function(e) {
            if (!e.target.closest('.dropdown-container')) {
                document.querySelectorAll('.dropdown-menu').forEach(d => {
                    d.classList.remove('show');
                });
            }
        });

        function toggleDeptStats() {
            const dropdown = document.getElementById('deptDropdown');
            const chevron = document.getElementById('deptChevron');
            dropdown.classList.toggle('show');
            chevron.classList.toggle('open');
        }

        // ============================================================
        // MODERN DROPDOWN FUNCTIONS - FIXED
        // ============================================================
        
        // Toggle dropdown dengan animasi smooth
        function toggleDeptDropdown() {
            const trigger = document.querySelector('#departmentDropdown .dropdown-trigger');
            const options = document.querySelector('#departmentDropdown .dropdown-options');
            
            // Close other dropdowns
            document.querySelectorAll('.custom-dropdown').forEach(dropdown => {
                if (dropdown.id !== 'departmentDropdown') {
                    const otherTrigger = dropdown.querySelector('.dropdown-trigger');
                    const otherOptions = dropdown.querySelector('.dropdown-options');
                    otherTrigger?.classList.remove('active');
                    otherOptions?.classList.remove('show');
                }
            });
            
            // Toggle current dropdown
            trigger.classList.toggle('active');
            options.classList.toggle('show');
            
            // Focus search input when opened
            if (options.classList.contains('show')) {
                setTimeout(() => {
                    document.getElementById('deptSearchInput')?.focus();
                }, 100);
            } else {
                // Clear search when closed
                const searchInput = document.getElementById('deptSearchInput');
                if (searchInput) {
                    searchInput.value = '';
                    filterDepartments();
                }
            }
        }

        // Select department dengan smooth transition
        function selectDepartment(value, text) {
            // Update display text dengan animasi
            const selectedText = document.getElementById('selectedDept');
            selectedText.style.opacity = '0.5';
            
            setTimeout(() => {
                selectedText.textContent = text;
                selectedText.style.opacity = '1';
            }, 150);
            
            // Update selected state
            document.querySelectorAll('#departmentDropdown .dropdown-option').forEach(opt => {
                opt.classList.remove('selected');
            });
            event.target.closest('.dropdown-option').classList.add('selected');
            
            // Close dropdown dengan delay
            setTimeout(() => {
                toggleDeptDropdown();
            }, 200);
            
            // Apply filter
            setTimeout(() => {
                applyFilters(value);
            }, 300);
        }

        // Filter departments dalam dropdown (Search Feature)
        function filterDepartments() {
            const searchInput = document.getElementById('deptSearchInput');
            const searchTerm = searchInput.value.toLowerCase();
            const options = document.querySelectorAll('#departmentList .dropdown-option');
            
            let visibleCount = 0;
            
            options.forEach(option => {
                const deptName = option.getAttribute('data-dept');
                const isMatch = deptName.includes(searchTerm);
                
                if (isMatch) {
                    option.style.display = 'flex';
                    visibleCount++;
                } else {
                    option.style.display = 'none';
                }
            });
            
            // Show "no results" message if needed
            const existingMsg = document.getElementById('noResultsMsg');
            if (existingMsg) existingMsg.remove();
            
            if (visibleCount === 0) {
                const noResultsMsg = document.createElement('div');
                noResultsMsg.id = 'noResultsMsg';
                noResultsMsg.style.cssText = 'padding: 20px; text-align: center; color: #94a3b8; font-size: 13px;';
                noResultsMsg.innerHTML = '<i class="fas fa-search"></i><br><br>Tidak ada department ditemukan';
                document.getElementById('departmentList').appendChild(noResultsMsg);
            }
        }

        // Close dropdown saat klik di luar
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.custom-dropdown')) {
                document.querySelectorAll('.dropdown-options').forEach(opt => {
                    opt.classList.remove('show');
                });
                document.querySelectorAll('.dropdown-trigger').forEach(trigger => {
                    trigger.classList.remove('active');
                });
            }
        });

        // Prevent dropdown close saat klik di dalam
        document.querySelectorAll('.dropdown-options').forEach(dropdown => {
            dropdown.addEventListener('click', function(e) {
                e.stopPropagation();
            });
        });

        // Keyboard navigation
        document.addEventListener('keydown', function(e) {
            const dropdown = document.querySelector('#departmentDropdown .dropdown-options.show');
            if (!dropdown) return;
            
            const options = Array.from(dropdown.querySelectorAll('.dropdown-option[style*="display: flex"], .dropdown-option:not([style*="display: none"])'));
            const currentIndex = options.findIndex(opt => opt === document.activeElement);
            
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                const nextIndex = (currentIndex + 1) % options.length;
                options[nextIndex]?.focus();
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                const prevIndex = currentIndex <= 0 ? options.length - 1 : currentIndex - 1;
                options[prevIndex]?.focus();
            } else if (e.key === 'Enter' && currentIndex >= 0) {
                e.preventDefault();
                options[currentIndex]?.click();
            } else if (e.key === 'Escape') {
                toggleDeptDropdown();
            }
        });

        // ============================================================
        // EXISTING FUNCTIONS
        // ============================================================

        document.getElementById('searchInput')?.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('tbody tr:not(.dept-separator)');
            const separators = document.querySelectorAll('tbody tr.dept-separator');
            
            separators.forEach(sep => sep.style.display = 'none');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                const isMatch = text.includes(searchTerm);
                row.style.display = isMatch ? '' : 'none';
                
                if (isMatch) {
                    const prevSeparator = row.previousElementSibling;
                    if (prevSeparator && prevSeparator.classList.contains('dept-separator')) {
                        prevSeparator.style.display = '';
                    }
                }
            });
        });

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

        function applyFilters(deptValue) {
            const dateFrom = document.getElementById('dateFrom')?.value || '';
            const dateTo = document.getElementById('dateTo')?.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 (deptValue !== undefined) {
                if (deptValue) url.searchParams.set('department', deptValue);
                else url.searchParams.delete('department');
            }
            
            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?')) {
                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>