<?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'])) : '';

// ✅ FIX: File ini khusus untuk Dept Head
$allowedRoles = ['dept_head', 'dh'];

if (!in_array($userRole, $allowedRoles)) {
    header("Location: ../../dashboard.php");
    exit;
}

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

// 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'] : '';

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

// ✅ CRITICAL: Dept Head HANYA lihat department sendiri (HARD-CODED)
if ($userDepartment) {
    $whereConditions[] = "assignee.department = ?";
    $params[] = $userDepartment;
    $types .= 's';
}

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

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

// Main query - ✅ SORT BY DEADLINE (terdekat dulu)
$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.full_name 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();

// ✅ FIX: Statistics query - TAMBAHKAN rk. prefix di semua status
$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 Assignee (seperti admin tapi per assignee)
$statsByAssigneeSql = "
    SELECT 
        assignee.full_name as assignee_name,
        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.full_name
    ORDER BY assignee.full_name
";

$statsByAssigneeStmt = $conn->prepare($statsByAssigneeSql);

$tasksByAssignee = [];
if ($statsByAssigneeStmt) {
    if (!empty($params)) {
        $statsByAssigneeStmt->bind_param($types, ...$params);
    }
    
    $statsByAssigneeStmt->execute();
    $statsByAssigneeResult = $statsByAssigneeStmt->get_result();
    
    while ($row = $statsByAssigneeResult->fetch_assoc()) {
        $assignee = $row['assignee_name'] ?? 'Tidak Ada Assignee';
        $tasksByAssignee[$assignee] = [
            'total' => $row['total'],
            'done' => $row['completed'],
            'progress' => $row['in_progress'],
            'stuck' => $row['stuck'],
            'pending' => $row['pending']
        ];
    }
    $statsByAssigneeStmt->close();
}

ksort($tasksByAssignee);

// ✅ Assign unique colors to each assignee
$assigneeColors = [];
$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 assignees
$allAssigneesForColors = array_unique(array_merge(
    array_keys($tasksByAssignee),
    array_column($allTasks, 'assignee_name')
));

$colorIndex = 0;
foreach ($allAssigneesForColors as $assignee) {
    if (!empty($assignee)) {
        $assigneeColors[$assignee] = $colorPalette[$colorIndex % count($colorPalette)];
        $colorIndex++;
    }
}

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

// Group tasks by assignee
$tasksByAssigneeGroup = [];
foreach ($allTasks as $task) {
    $assignee = $task['assignee_name'] ?? 'Tidak Ada Assignee';
    if (!isset($tasksByAssigneeGroup[$assignee])) {
        $tasksByAssigneeGroup[$assignee] = [];
    }
    $tasksByAssigneeGroup[$assignee][] = $task;
}
ksort($tasksByAssigneeGroup);

// 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 - Dept Head</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;
        }

        /* Department Notice */
        .dept-notice {
            background: linear-gradient(135deg, rgba(122, 178, 178, 0.1), rgba(77, 134, 156, 0.1));
            border-left: 4px solid #7AB2B2;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .dept-notice i {
            color: #7AB2B2;
            font-size: 20px;
        }

        .dept-notice strong {
            color: #1e293b;
        }

        .dept-notice p {
            color: #475569;
            margin: 0;
            font-size: 14px;
        }

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

        /* ✅ Assignee Stats Section */
        .assignee-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;
        }

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

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

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

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

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

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

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

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

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

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

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

        .assignee-name {
            font-weight: 700;
            color: #1e293b;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .assignee-avatar {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 12px;
        }

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

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

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

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

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

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

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

        tr.assignee-separator td {
            padding: 15px 20px;
            font-weight: 800;
            font-size: 14px;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

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

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

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

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

        .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 {
                width: 100%;
            }

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

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

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

            table {
                min-width: 800px;
            }
        }
    </style>
</head>
<body>

    <?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 Department</h1>
                <p>Monitor dan Kelola Tugas Tim Anda</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 ?? '') ?>">
            </div>
        </div>
    </div>

    <!-- Department Notice -->
    <?php if ($userDepartment): ?>
    <div class="dept-notice">
        <i class="fas fa-building"></i>
        <div>
            <strong>Department: <?= htmlspecialchars($userDepartment) ?></strong>
            <p>Anda melihat semua tugas untuk department Anda</p>
        </div>
    </div>
    <?php endif; ?>

    <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($tasksByAssignee)): ?>
    <div class="assignee-toggle" onclick="toggleAssigneeStats()">
        <div class="assignee-toggle-header">
            <div class="assignee-toggle-title">
                <i class="fas fa-users"></i>
                Statistik per Assignee
                <span class="assignee-count"><?= count($tasksByAssignee) ?> Orang</span>
            </div>
            <i class="fas fa-chevron-down chevron" id="assigneeChevron"></i>
        </div>
        <div class="assignee-dropdown" id="assigneeDropdown">
            <div class="assignee-grid">
                <?php foreach ($tasksByAssignee as $assignee => $assigneeStats): 
                    $colors = $assigneeColors[$assignee] ?? $defaultColor;
                ?>
                <div class="assignee-item" style="border-left-color: <?= $colors['border'] ?>; background: <?= $colors['bg'] ?>;">
                    <div class="assignee-header">
                        <div class="assignee-name" style="color: <?= $colors['text'] ?>;">
                            <div class="assignee-avatar" style="background: <?= $colors['border'] ?>;">
                                <?= strtoupper(substr($assignee, 0, 1)) ?>
                            </div>
                            <?= htmlspecialchars($assignee) ?>
                        </div>
                        <div class="assignee-total" style="background: <?= $colors['border'] ?>;"><?= $assigneeStats['total'] ?> tugas</div>
                    </div>
                    <div class="assignee-stats">
                        <div class="assignee-stat-item">
                            <div class="assignee-stat-value done"><?= $assigneeStats['done'] ?></div>
                            <div class="assignee-stat-label">Selesai</div>
                        </div>
                        <div class="assignee-stat-item">
                            <div class="assignee-stat-value progress"><?= $assigneeStats['progress'] ?></div>
                            <div class="assignee-stat-label">Progress</div>
                        </div>
                        <div class="assignee-stat-item">
                            <div class="assignee-stat-value stuck"><?= $assigneeStats['stuck'] ?></div>
                            <div class="assignee-stat-label">Hambat</div>
                        </div>
                        <div class="assignee-stat-item">
                            <div class="assignee-stat-value pending"><?= $assigneeStats['pending'] ?></div>
                            <div class="assignee-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>Tenggat</th>
                    <th>Progress</th>
                    <th>Status</th>
                    <th style="text-align: center;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($paginatedTasks)): ?>
                    <tr>
                        <td colspan="5">
                            <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 
                    $currentAssignee = null;
                    foreach ($paginatedTasks as $task): 
                        if ($currentAssignee !== $task['assignee_name']):
                            $currentAssignee = $task['assignee_name'];
                            $colors = $assigneeColors[$currentAssignee] ?? $defaultColor;
                    ?>
                        <tr class="assignee-separator" style="border-color: <?= $colors['border'] ?>; background: <?= $colors['bg'] ?> !important;">
                            <td colspan="5" style="color: <?= $colors['text'] ?>;">
                                <div class="assignee-avatar" style="background: <?= $colors['border'] ?>;">
                                    <?= strtoupper(substr($currentAssignee, 0, 1)) ?>
                                </div>
                                <?= htmlspecialchars($currentAssignee) ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                        <tr>
                            <td>
                                <div class="task-title"><?= htmlspecialchars(substr($task['judul_tugas'] ?? 'N/A', 0, 60)) ?></div>
                            </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="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 : '' ?>" 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 : '' ?>" 
                       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 : '' ?>" 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 toggleAssigneeStats() {
            const dropdown = document.getElementById('assigneeDropdown');
            const chevron = document.getElementById('assigneeChevron');
            dropdown.classList.toggle('show');
            chevron.classList.toggle('open');
        }

        document.getElementById('searchInput')?.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('tbody tr:not(.assignee-separator)');
            const separators = document.querySelectorAll('tbody tr.assignee-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('assignee-separator')) {
                        prevSeparator.style.display = '';
                    }
                }
            });
        });

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