<?php
// Gunakan session check helper
require_once __DIR__ . '/../../config/session_check.php';
require_once __DIR__ . '/../../DataBase/koneksi.php';
require_once __DIR__ . '/../../config/RencanaKerjaPermission.php';

// Cek role access
$allowedRoles = ['A', 'DH', 'S', 'D', 'M', 'admin', 'director', 'dept_head', 'staff'];
if (!checkRole($allowedRoles)) {
    echo '<div style="padding: 40px; text-align: center;">
            <h2>Access Denied</h2>
            <p>Anda tidak memiliki akses ke halaman ini.</p>
          </div>';
    exit;
}

// Get session variables
$userId = (int) $_SESSION['user_id'];
$userRole = trim($_SESSION['role']);

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

// Check permissions - ALL ROLES can edit/add
$canEdit = true; // All roles can edit their own tasks
$canAdd = true;  // All roles can add tasks

// AUTO-DETECT column names from database
$detectResult = $conn->query("SHOW COLUMNS FROM rencana_kerja");
$dateColumn = 'tenggat_waktu';
$taskNameColumn = 'judul_tugas';

if ($detectResult) {
    while ($col = $detectResult->fetch_assoc()) {
        $fieldName = $col['Field'];
        
        if (stripos($fieldName, 'deadline') !== false) {
            $dateColumn = $fieldName;
        } elseif (stripos($fieldName, 'tenggat') !== false && $dateColumn === 'tenggat_waktu') {
            $dateColumn = $fieldName;
        }
        
        if (stripos($fieldName, 'task_name') !== false) {
            $taskNameColumn = $fieldName;
        } elseif (stripos($fieldName, 'judul') !== false && $taskNameColumn === 'judul_tugas') {
            $taskNameColumn = $fieldName;
        }
    }
}

// Get date filter
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build date filter
$dateFilter = '';
$dateParams = [];
if ($dateFrom && $dateTo) {
    $dateFilter = " AND rk.$dateColumn BETWEEN ? AND ?";
    $dateParams = [$dateFrom, $dateTo];
} elseif ($dateFrom) {
    $dateFilter = " AND rk.$dateColumn >= ?";
    $dateParams = [$dateFrom];
} elseif ($dateTo) {
    $dateFilter = " AND rk.$dateColumn <= ?";
    $dateParams = [$dateTo];
}

// Build WHERE clause based on permissions
$whereClause = "rk.is_deleted = 0";

if (!$permSummary['can_view_all']) {
    $whereClause .= " AND rk.assigned_to = ?";
    $useUserFilter = true;
} else {
    $useUserFilter = false;
}

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

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

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

// Build parameters array
if ($useUserFilter) {
    $params = [$userId];
    $types = 'i';
} else {
    $params = [];
    $types = '';
}

// Add date filter params
if (!empty($dateParams)) {
    foreach ($dateParams as $param) {
        $params[] = $param;
        $types .= 's';
    }
}

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

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

$users = $permission->getAssignableUsers();
$departments = $permission->getAccessibleDepartments();

$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';
        
        // Department logic
        if (empty($task['department'])) {
            $task['department'] = $task['assignee_department'] ?? 'N/A';
        }
        
        $allTasks[] = $task;
    }
}

$stmt->close();

// Statistics
$statsWhereClause = "rk.is_deleted = 0";
if (!$permSummary['can_view_all']) {
    $statsWhereClause .= " AND rk.assigned_to = ?";
}

$statsSql = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN status = 'stuck' THEN 1 ELSE 0 END) as stuck,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
    FROM rencana_kerja rk
    WHERE $statsWhereClause
    $dateFilter
";

$statsStmt = $conn->prepare($statsSql);
if (!empty($params)) {
    $statsStmt->bind_param($types, ...$params);
}
$statsStmt->execute();
$statsResult = $statsStmt->get_result();
$stats = $statsResult->fetch_assoc();
$statsStmt->close();

// 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</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 */
        .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;
            flex-wrap: wrap;
            gap: 20px;
        }

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

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

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

        .search-box {
            position: relative;
        }

        .search-box input {
            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;
            width: 250px;
            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;
            width: 300px;
        }

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

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

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

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

        .btn-primary {
            padding: 10px 24px;
            background: white;
            color: #7AB2B2;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

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

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

        /* STATS CARDS - COMPACT VERSION */
        .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;
        }

        /* TABLE */
        .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;
        }

        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;
            background: #f1f5f9;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
            color: #475569;
        }

        .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 MENU */
        .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 */
        .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;
        }

        /* ALERTS */
        .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;
        }

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

            .header {
                padding: 20px 25px;
            }

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

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

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

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

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

            .date-input {
                width: 100%;
            }

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

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

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

    <!-- ALERTS -->
    <?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; ?>

    <!-- HEADER -->
    <div class="header">
        <div class="header-content">
            <div class="header-left">
                <h1>Rencana Kerja</h1>
                <p>Kelola dan Monitor Tugas Anda</p>
            </div>
            <div class="header-actions">
                <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>
                <?php if ($canAdd): ?>
                <a href="../rencana_kerja/add_rencana_kerja.php" class="btn-primary">
                    <i class="fas fa-plus"></i>
                    Tambah Tugas
                </a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- STATS GRID -->
    <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>

    <!-- TABLE -->
    <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>Belum ada tugas yang ditugaskan kepada Anda</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($paginatedTasks as $task): ?>
                        <tr>
                            <td>
                                <div class="task-title"><?= htmlspecialchars(substr($task[$taskNameColumn] ?? 'N/A', 0, 60)) ?></div>
                            </td>
                            <td>
                                <span class="dept-badge"><?= htmlspecialchars($task['department'] ?? 'N/A') ?></span>
                            </td>
                            <td><?= date('d M Y', strtotime($task[$dateColumn])) ?></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'] ?>">
                                            <a href="../rencana_kerja/detail_rencana_kerja.php?id=<?= $task['id'] ?>" class="dropdown-item">
                                                <i class="fas fa-eye"></i>
                                                <span>Lihat Detail</span>
                                            </a>
                                            <?php if ($canEdit): ?>
                                            <a href="../rencana_kerja/edit_rencana_kerja.php?id=<?= $task['id'] ?>" class="dropdown-item">
                                                <i class="fas fa-edit"></i>
                                                <span>Edit</span>
                                            </a>
                                            <?php endif; ?>
                                            <?php if (in_array($userRole, ['A', 'DH'])): ?>
                                            <button onclick="deleteTask(<?= $task['id'] ?>)" class="dropdown-item delete">
                                                <i class="fas fa-trash"></i>
                                                <span>Hapus</span>
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- PAGINATION -->
        <?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>
        // Auto-hide alerts
        setTimeout(() => {
            document.getElementById('successAlert')?.remove();
            document.getElementById('errorAlert')?.remove();
        }, 5000);

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

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

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

        // Date filter
        document.getElementById('dateFrom')?.addEventListener('change', applyDateFilter);
        document.getElementById('dateTo')?.addEventListener('change', applyDateFilter);

        function applyDateFilter() {
            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 deleteTask(id) {
            if (confirm('Apakah Anda yakin ingin menghapus tugas ini?')) {
                window.location.href = `../rencana_kerja/delete_rencana_kerja.php?id=${id}`;
            }
        }
    </script>

</body>
</html>